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
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/FreesoundClient.java
FreesoundClient.redeemAuthorisationCodeForAccessToken
public Response<AccessTokenDetails> redeemAuthorisationCodeForAccessToken(final String authorisationCode) throws FreesoundClientException { """ Redeem an authorisation code received from freesound.org for an access token that can be used to make calls to OAuth2 protected resources. @param authorisationCode The authorisation code received @return Details of the access token returned @throws FreesoundClientException Any exception thrown during call """ final OAuth2AccessTokenRequest tokenRequest = new OAuth2AccessTokenRequest(clientId, clientSecret, authorisationCode); return executeQuery(tokenRequest); }
java
public Response<AccessTokenDetails> redeemAuthorisationCodeForAccessToken(final String authorisationCode) throws FreesoundClientException { final OAuth2AccessTokenRequest tokenRequest = new OAuth2AccessTokenRequest(clientId, clientSecret, authorisationCode); return executeQuery(tokenRequest); }
[ "public", "Response", "<", "AccessTokenDetails", ">", "redeemAuthorisationCodeForAccessToken", "(", "final", "String", "authorisationCode", ")", "throws", "FreesoundClientException", "{", "final", "OAuth2AccessTokenRequest", "tokenRequest", "=", "new", "OAuth2AccessTokenRequest...
Redeem an authorisation code received from freesound.org for an access token that can be used to make calls to OAuth2 protected resources. @param authorisationCode The authorisation code received @return Details of the access token returned @throws FreesoundClientException Any exception thrown during call
[ "Redeem", "an", "authorisation", "code", "received", "from", "freesound", ".", "org", "for", "an", "access", "token", "that", "can", "be", "used", "to", "make", "calls", "to", "OAuth2", "protected", "resources", "." ]
train
https://github.com/Sonoport/freesound-java/blob/ab029e25de068c6f8cc028bc7f916938fd97c036/src/main/java/com/sonoport/freesound/FreesoundClient.java#L248-L254
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java
ComputationGraph.rnnTimeStep
public INDArray[] rnnTimeStep(MemoryWorkspace outputWorkspace, INDArray... inputs) { """ See {@link #rnnTimeStep(INDArray...)} for details.<br> If no memory workspace is provided, the output will be detached (not in any workspace).<br> If a memory workspace is provided, the output activation array (i.e., the INDArray returned by this method) will be placed in the specified workspace. This workspace must be opened by the user before calling this method - and the user is responsible for (a) closing this workspace, and (b) ensuring the output array is not used out of scope (i.e., not used after closing the workspace to which it belongs - as this is likely to cause either an exception when used, or a crash). @param inputs Input activations @param outputWorkspace Output workspace. May be null @return The output/activations from the network (either detached or in the specified workspace if provided) """ try{ return rnnTimeStepHelper(outputWorkspace, inputs); } catch (OutOfMemoryError e){ CrashReportingUtil.writeMemoryCrashDump(this, e); throw e; } }
java
public INDArray[] rnnTimeStep(MemoryWorkspace outputWorkspace, INDArray... inputs){ try{ return rnnTimeStepHelper(outputWorkspace, inputs); } catch (OutOfMemoryError e){ CrashReportingUtil.writeMemoryCrashDump(this, e); throw e; } }
[ "public", "INDArray", "[", "]", "rnnTimeStep", "(", "MemoryWorkspace", "outputWorkspace", ",", "INDArray", "...", "inputs", ")", "{", "try", "{", "return", "rnnTimeStepHelper", "(", "outputWorkspace", ",", "inputs", ")", ";", "}", "catch", "(", "OutOfMemoryError...
See {@link #rnnTimeStep(INDArray...)} for details.<br> If no memory workspace is provided, the output will be detached (not in any workspace).<br> If a memory workspace is provided, the output activation array (i.e., the INDArray returned by this method) will be placed in the specified workspace. This workspace must be opened by the user before calling this method - and the user is responsible for (a) closing this workspace, and (b) ensuring the output array is not used out of scope (i.e., not used after closing the workspace to which it belongs - as this is likely to cause either an exception when used, or a crash). @param inputs Input activations @param outputWorkspace Output workspace. May be null @return The output/activations from the network (either detached or in the specified workspace if provided)
[ "See", "{", "@link", "#rnnTimeStep", "(", "INDArray", "...", ")", "}", "for", "details", ".", "<br", ">", "If", "no", "memory", "workspace", "is", "provided", "the", "output", "will", "be", "detached", "(", "not", "in", "any", "workspace", ")", ".", "<...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java#L3418-L3425
JOML-CI/JOML
src/org/joml/Quaterniond.java
Quaterniond.fromAxisAngleDeg
public Quaterniond fromAxisAngleDeg(Vector3dc axis, double angle) { """ Set this quaternion to be a representation of the supplied axis and angle (in degrees). @param axis the rotation axis @param angle the angle in degrees @return this """ return fromAxisAngleRad(axis.x(), axis.y(), axis.z(), Math.toRadians(angle)); }
java
public Quaterniond fromAxisAngleDeg(Vector3dc axis, double angle) { return fromAxisAngleRad(axis.x(), axis.y(), axis.z(), Math.toRadians(angle)); }
[ "public", "Quaterniond", "fromAxisAngleDeg", "(", "Vector3dc", "axis", ",", "double", "angle", ")", "{", "return", "fromAxisAngleRad", "(", "axis", ".", "x", "(", ")", ",", "axis", ".", "y", "(", ")", ",", "axis", ".", "z", "(", ")", ",", "Math", "."...
Set this quaternion to be a representation of the supplied axis and angle (in degrees). @param axis the rotation axis @param angle the angle in degrees @return this
[ "Set", "this", "quaternion", "to", "be", "a", "representation", "of", "the", "supplied", "axis", "and", "angle", "(", "in", "degrees", ")", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaterniond.java#L686-L688
innoq/LiQID
ldap-connector/src/main/java/com/innoq/ldap/connector/LdapHelper.java
LdapHelper.checkCredentials
@Override public boolean checkCredentials(final String uid, final String password) { """ We use this method to check the given credentials to be valid. To prevent the check every action call, the result (if true) will be cached for 60s. @param uid the given uid. @param password the given password. @return true if credentials are valid, otherwise false. """ StringBuilder sb = new StringBuilder(userIdentifyer + "=").append(uid).append(","); sb.append(Configuration.getProperty(instanceName + LdapKeys.ATTR_OU_PEOPLE)).append(","); sb.append(baseDn); if (uid == null || uid.isEmpty() || password == null || password.isEmpty()) { return false; } try { Hashtable<String,String> environment = (Hashtable<String,String>) ctx.getEnvironment().clone(); environment.put(Context.SECURITY_PRINCIPAL, sb.toString()); environment.put(Context.SECURITY_CREDENTIALS, password); DirContext dirContext = new InitialDirContext(environment); dirContext.close(); validationCount++; return true; } catch (NamingException ex) { handleNamingException("NamingException " + ex.getLocalizedMessage() + "\n", ex); } return false; }
java
@Override public boolean checkCredentials(final String uid, final String password) { StringBuilder sb = new StringBuilder(userIdentifyer + "=").append(uid).append(","); sb.append(Configuration.getProperty(instanceName + LdapKeys.ATTR_OU_PEOPLE)).append(","); sb.append(baseDn); if (uid == null || uid.isEmpty() || password == null || password.isEmpty()) { return false; } try { Hashtable<String,String> environment = (Hashtable<String,String>) ctx.getEnvironment().clone(); environment.put(Context.SECURITY_PRINCIPAL, sb.toString()); environment.put(Context.SECURITY_CREDENTIALS, password); DirContext dirContext = new InitialDirContext(environment); dirContext.close(); validationCount++; return true; } catch (NamingException ex) { handleNamingException("NamingException " + ex.getLocalizedMessage() + "\n", ex); } return false; }
[ "@", "Override", "public", "boolean", "checkCredentials", "(", "final", "String", "uid", ",", "final", "String", "password", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "userIdentifyer", "+", "\"=\"", ")", ".", "append", "(", "uid", ")...
We use this method to check the given credentials to be valid. To prevent the check every action call, the result (if true) will be cached for 60s. @param uid the given uid. @param password the given password. @return true if credentials are valid, otherwise false.
[ "We", "use", "this", "method", "to", "check", "the", "given", "credentials", "to", "be", "valid", ".", "To", "prevent", "the", "check", "every", "action", "call", "the", "result", "(", "if", "true", ")", "will", "be", "cached", "for", "60s", "." ]
train
https://github.com/innoq/LiQID/blob/ae3de2c1fd78c40219780d510eba57c931901279/ldap-connector/src/main/java/com/innoq/ldap/connector/LdapHelper.java#L590-L610
OpenLiberty/open-liberty
dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/services/impl/MemoryPersistenceManagerImpl.java
MemoryPersistenceManagerImpl.getStepExecutionTopLevelFromJobExecutionIdAndStepName
private TopLevelStepExecutionEntity getStepExecutionTopLevelFromJobExecutionIdAndStepName(long jobExecutionId, String stepName) { """ Not well-suited to factor out into an interface method since for JPA it's embedded in a tran typically """ JobExecutionEntity jobExecution = data.executionInstanceData.get(jobExecutionId); // Copy list to avoid ConcurrentModificationException for (StepThreadExecutionEntity stepExec : new ArrayList<StepThreadExecutionEntity>(jobExecution.getStepThreadExecutions())) { if (stepExec.getStepName().equals(stepName)) { if (stepExec instanceof TopLevelStepExecutionEntity) { return (TopLevelStepExecutionEntity) stepExec; } } } // Bad if we've gotten here. throw new IllegalStateException("Couldn't find top-level step execution for jobExecution = " + jobExecutionId + ", and stepName = " + stepName); }
java
private TopLevelStepExecutionEntity getStepExecutionTopLevelFromJobExecutionIdAndStepName(long jobExecutionId, String stepName) { JobExecutionEntity jobExecution = data.executionInstanceData.get(jobExecutionId); // Copy list to avoid ConcurrentModificationException for (StepThreadExecutionEntity stepExec : new ArrayList<StepThreadExecutionEntity>(jobExecution.getStepThreadExecutions())) { if (stepExec.getStepName().equals(stepName)) { if (stepExec instanceof TopLevelStepExecutionEntity) { return (TopLevelStepExecutionEntity) stepExec; } } } // Bad if we've gotten here. throw new IllegalStateException("Couldn't find top-level step execution for jobExecution = " + jobExecutionId + ", and stepName = " + stepName); }
[ "private", "TopLevelStepExecutionEntity", "getStepExecutionTopLevelFromJobExecutionIdAndStepName", "(", "long", "jobExecutionId", ",", "String", "stepName", ")", "{", "JobExecutionEntity", "jobExecution", "=", "data", ".", "executionInstanceData", ".", "get", "(", "jobExecuti...
Not well-suited to factor out into an interface method since for JPA it's embedded in a tran typically
[ "Not", "well", "-", "suited", "to", "factor", "out", "into", "an", "interface", "method", "since", "for", "JPA", "it", "s", "embedded", "in", "a", "tran", "typically" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/services/impl/MemoryPersistenceManagerImpl.java#L791-L803
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/msvc/VisualStudioNETProjectWriter.java
VisualStudioNETProjectWriter.getRuntimeLibrary
private String getRuntimeLibrary(final CommandLineCompilerConfiguration compilerConfig, final boolean isDebug) { """ Get value of RuntimeLibrary property. @param compilerConfig compiler configuration. @param isDebug true if generating debug configuration. @return value of RuntimeLibrary property. """ String rtl = null; final String[] args = compilerConfig.getPreArguments(); for (final String arg : args) { if (arg.startsWith("/MT")) { if (isDebug) { rtl = "1"; } else { rtl = "0"; } } else if (arg.startsWith("/MD")) { if (isDebug) { rtl = "3"; } else { rtl = "2"; } } } return rtl; }
java
private String getRuntimeLibrary(final CommandLineCompilerConfiguration compilerConfig, final boolean isDebug) { String rtl = null; final String[] args = compilerConfig.getPreArguments(); for (final String arg : args) { if (arg.startsWith("/MT")) { if (isDebug) { rtl = "1"; } else { rtl = "0"; } } else if (arg.startsWith("/MD")) { if (isDebug) { rtl = "3"; } else { rtl = "2"; } } } return rtl; }
[ "private", "String", "getRuntimeLibrary", "(", "final", "CommandLineCompilerConfiguration", "compilerConfig", ",", "final", "boolean", "isDebug", ")", "{", "String", "rtl", "=", "null", ";", "final", "String", "[", "]", "args", "=", "compilerConfig", ".", "getPreA...
Get value of RuntimeLibrary property. @param compilerConfig compiler configuration. @param isDebug true if generating debug configuration. @return value of RuntimeLibrary property.
[ "Get", "value", "of", "RuntimeLibrary", "property", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/msvc/VisualStudioNETProjectWriter.java#L460-L479
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.eachWithIndex
public static <T> T eachWithIndex(T self, Closure closure) { """ Iterates through an aggregate type or data structure, passing each item and the item's index (a counter starting at zero) to the given closure. @param self an Object @param closure a Closure to operate on each item @return the self Object @since 1.0 """ final Object[] args = new Object[2]; int counter = 0; for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { args[0] = iter.next(); args[1] = counter++; closure.call(args); } return self; }
java
public static <T> T eachWithIndex(T self, Closure closure) { final Object[] args = new Object[2]; int counter = 0; for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { args[0] = iter.next(); args[1] = counter++; closure.call(args); } return self; }
[ "public", "static", "<", "T", ">", "T", "eachWithIndex", "(", "T", "self", ",", "Closure", "closure", ")", "{", "final", "Object", "[", "]", "args", "=", "new", "Object", "[", "2", "]", ";", "int", "counter", "=", "0", ";", "for", "(", "Iterator", ...
Iterates through an aggregate type or data structure, passing each item and the item's index (a counter starting at zero) to the given closure. @param self an Object @param closure a Closure to operate on each item @return the self Object @since 1.0
[ "Iterates", "through", "an", "aggregate", "type", "or", "data", "structure", "passing", "each", "item", "and", "the", "item", "s", "index", "(", "a", "counter", "starting", "at", "zero", ")", "to", "the", "given", "closure", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L1904-L1913
wisdom-framework/wisdom-jdbc
wisdom-jdbc-drivers/abstract-jdbc-driver/src/main/java/org/wisdom/jdbc/driver/helpers/BeanUtils.java
BeanUtils.throwSQLException
public static void throwSQLException(Exception cause, String theType, String value) throws SQLException { """ An helper method to build and throw a SQL Exception when a property cannot be set. @param cause the cause @param theType the type of the property @param value the value of the property @throws SQLException the SQL Exception """ throw new SQLException("Invalid " + theType + " value: " + value, cause); }
java
public static void throwSQLException(Exception cause, String theType, String value) throws SQLException { throw new SQLException("Invalid " + theType + " value: " + value, cause); }
[ "public", "static", "void", "throwSQLException", "(", "Exception", "cause", ",", "String", "theType", ",", "String", "value", ")", "throws", "SQLException", "{", "throw", "new", "SQLException", "(", "\"Invalid \"", "+", "theType", "+", "\" value: \"", "+", "valu...
An helper method to build and throw a SQL Exception when a property cannot be set. @param cause the cause @param theType the type of the property @param value the value of the property @throws SQLException the SQL Exception
[ "An", "helper", "method", "to", "build", "and", "throw", "a", "SQL", "Exception", "when", "a", "property", "cannot", "be", "set", "." ]
train
https://github.com/wisdom-framework/wisdom-jdbc/blob/931f5acf0b2bcb0a8f3b683d60d326caafd09a72/wisdom-jdbc-drivers/abstract-jdbc-driver/src/main/java/org/wisdom/jdbc/driver/helpers/BeanUtils.java#L167-L170
VoltDB/voltdb
third_party/java/src/org/apache/zookeeper_voltpatches/jmx/MBeanRegistry.java
MBeanRegistry.makeFullPath
public String makeFullPath(String prefix, String... name) { """ Generate a filesystem-like path. @param prefix path prefix @param name path elements @return absolute path """ StringBuilder sb=new StringBuilder(prefix == null ? "/" : (prefix.equals("/")?prefix:prefix+"/")); boolean first=true; for (String s : name) { if(s==null) continue; if(!first){ sb.append("/"); }else first=false; sb.append(s); } return sb.toString(); }
java
public String makeFullPath(String prefix, String... name) { StringBuilder sb=new StringBuilder(prefix == null ? "/" : (prefix.equals("/")?prefix:prefix+"/")); boolean first=true; for (String s : name) { if(s==null) continue; if(!first){ sb.append("/"); }else first=false; sb.append(s); } return sb.toString(); }
[ "public", "String", "makeFullPath", "(", "String", "prefix", ",", "String", "...", "name", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "prefix", "==", "null", "?", "\"/\"", ":", "(", "prefix", ".", "equals", "(", "\"/\"", ")", "?",...
Generate a filesystem-like path. @param prefix path prefix @param name path elements @return absolute path
[ "Generate", "a", "filesystem", "-", "like", "path", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/zookeeper_voltpatches/jmx/MBeanRegistry.java#L145-L157
NextFaze/power-adapters
power-adapters/src/main/java/com/nextfaze/poweradapters/binding/ViewHolderBinder.java
ViewHolderBinder.bindViewHolder
@Deprecated protected void bindViewHolder(@NonNull T t, @NonNull H h, @NonNull Holder holder) { """ Use {@link #bindViewHolder(Container, T, ViewHolder, Holder)} instead. """ }
java
@Deprecated protected void bindViewHolder(@NonNull T t, @NonNull H h, @NonNull Holder holder) { }
[ "@", "Deprecated", "protected", "void", "bindViewHolder", "(", "@", "NonNull", "T", "t", ",", "@", "NonNull", "H", "h", ",", "@", "NonNull", "Holder", "holder", ")", "{", "}" ]
Use {@link #bindViewHolder(Container, T, ViewHolder, Holder)} instead.
[ "Use", "{" ]
train
https://github.com/NextFaze/power-adapters/blob/cdf00b1b723ed9d6bcd549ae9741a19dd59651e1/power-adapters/src/main/java/com/nextfaze/poweradapters/binding/ViewHolderBinder.java#L87-L89
OpenLiberty/open-liberty
dev/com.ibm.ws.security.appbnd/src/com/ibm/ws/security/appbnd/internal/delegation/DefaultDelegationProvider.java
DefaultDelegationProvider.createAppToSecurityRolesMapping
public void createAppToSecurityRolesMapping(String appName, Collection<SecurityRole> securityRoles) { """ Creates the application to security roles mapping for a given application. @param appName the name of the application for which the mappings belong to. @param securityRoles the security roles of the application. """ //only add it if we don't have a cached copy appToSecurityRolesMap.putIfAbsent(appName, securityRoles); }
java
public void createAppToSecurityRolesMapping(String appName, Collection<SecurityRole> securityRoles) { //only add it if we don't have a cached copy appToSecurityRolesMap.putIfAbsent(appName, securityRoles); }
[ "public", "void", "createAppToSecurityRolesMapping", "(", "String", "appName", ",", "Collection", "<", "SecurityRole", ">", "securityRoles", ")", "{", "//only add it if we don't have a cached copy", "appToSecurityRolesMap", ".", "putIfAbsent", "(", "appName", ",", "security...
Creates the application to security roles mapping for a given application. @param appName the name of the application for which the mappings belong to. @param securityRoles the security roles of the application.
[ "Creates", "the", "application", "to", "security", "roles", "mapping", "for", "a", "given", "application", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.appbnd/src/com/ibm/ws/security/appbnd/internal/delegation/DefaultDelegationProvider.java#L196-L199
Netflix/zeno
src/main/java/com/netflix/zeno/serializer/FrameworkSerializer.java
FrameworkSerializer.serializeSortedMap
public <K, V> void serializeSortedMap(S rec, String fieldName, String keyTypeName, String valueTypeName, SortedMap<K, V> obj) { """ Serialize sorted map @param rec @param fieldName @param typeName @param obj """ serializeMap(rec, fieldName, keyTypeName, valueTypeName, obj); }
java
public <K, V> void serializeSortedMap(S rec, String fieldName, String keyTypeName, String valueTypeName, SortedMap<K, V> obj) { serializeMap(rec, fieldName, keyTypeName, valueTypeName, obj); }
[ "public", "<", "K", ",", "V", ">", "void", "serializeSortedMap", "(", "S", "rec", ",", "String", "fieldName", ",", "String", "keyTypeName", ",", "String", "valueTypeName", ",", "SortedMap", "<", "K", ",", "V", ">", "obj", ")", "{", "serializeMap", "(", ...
Serialize sorted map @param rec @param fieldName @param typeName @param obj
[ "Serialize", "sorted", "map" ]
train
https://github.com/Netflix/zeno/blob/e571a3f1e304942724d454408fe6417fe18c20fd/src/main/java/com/netflix/zeno/serializer/FrameworkSerializer.java#L165-L167
vst/commons-math-extensions
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
DMatrixUtils.roundDoubleToClosest
public static double roundDoubleToClosest (double value, double steps) { """ Same functionality as {@link DMatrixUtils#roundToClosest(double, double)} but operating on double values. @param value The value to be rounded. @param steps Steps. @return Rounded value. """ final double down = DMatrixUtils.roundDoubleDownTo(value, steps); final double up = DMatrixUtils.roundDoubleUpTo(value, steps); if (Math.abs(value - down) < Math.abs(value - up)) { return down; } return up; }
java
public static double roundDoubleToClosest (double value, double steps) { final double down = DMatrixUtils.roundDoubleDownTo(value, steps); final double up = DMatrixUtils.roundDoubleUpTo(value, steps); if (Math.abs(value - down) < Math.abs(value - up)) { return down; } return up; }
[ "public", "static", "double", "roundDoubleToClosest", "(", "double", "value", ",", "double", "steps", ")", "{", "final", "double", "down", "=", "DMatrixUtils", ".", "roundDoubleDownTo", "(", "value", ",", "steps", ")", ";", "final", "double", "up", "=", "DMa...
Same functionality as {@link DMatrixUtils#roundToClosest(double, double)} but operating on double values. @param value The value to be rounded. @param steps Steps. @return Rounded value.
[ "Same", "functionality", "as", "{", "@link", "DMatrixUtils#roundToClosest", "(", "double", "double", ")", "}", "but", "operating", "on", "double", "values", "." ]
train
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L364-L371
OpenLiberty/open-liberty
dev/com.ibm.ws.security/src/com/ibm/ws/security/internal/SecurityServiceImpl.java
SecurityServiceImpl.autoDetectService
private <V> V autoDetectService(String serviceName, ConcurrentServiceReferenceMap<String, V> map) { """ When the configuration element is not defined, use some "auto-detect" logic to try and return the single Service of a specified field. If there is no service, or multiple services, that is considered an error case which "auto-detect" can not resolve. @param serviceName name of the service @param map ConcurrentServiceReferenceMap of registered services @return id of the single service registered in map. Will not return null. """ Iterator<V> services = map.getServices(); if (services.hasNext() == false) { Tr.error(tc, "SECURITY_SERVICE_NO_SERVICE_AVAILABLE", serviceName); throw new IllegalStateException(Tr.formatMessage(tc, "SECURITY_SERVICE_NO_SERVICE_AVAILABLE", serviceName)); } V service = services.next(); if (services.hasNext()) { Tr.error(tc, "SECURITY_SERVICE_MULTIPLE_SERVICE_AVAILABLE", serviceName); throw new IllegalStateException(Tr.formatMessage(tc, "SECURITY_SERVICE_MULTIPLE_SERVICE_AVAILABLE", serviceName)); } return service; }
java
private <V> V autoDetectService(String serviceName, ConcurrentServiceReferenceMap<String, V> map) { Iterator<V> services = map.getServices(); if (services.hasNext() == false) { Tr.error(tc, "SECURITY_SERVICE_NO_SERVICE_AVAILABLE", serviceName); throw new IllegalStateException(Tr.formatMessage(tc, "SECURITY_SERVICE_NO_SERVICE_AVAILABLE", serviceName)); } V service = services.next(); if (services.hasNext()) { Tr.error(tc, "SECURITY_SERVICE_MULTIPLE_SERVICE_AVAILABLE", serviceName); throw new IllegalStateException(Tr.formatMessage(tc, "SECURITY_SERVICE_MULTIPLE_SERVICE_AVAILABLE", serviceName)); } return service; }
[ "private", "<", "V", ">", "V", "autoDetectService", "(", "String", "serviceName", ",", "ConcurrentServiceReferenceMap", "<", "String", ",", "V", ">", "map", ")", "{", "Iterator", "<", "V", ">", "services", "=", "map", ".", "getServices", "(", ")", ";", "...
When the configuration element is not defined, use some "auto-detect" logic to try and return the single Service of a specified field. If there is no service, or multiple services, that is considered an error case which "auto-detect" can not resolve. @param serviceName name of the service @param map ConcurrentServiceReferenceMap of registered services @return id of the single service registered in map. Will not return null.
[ "When", "the", "configuration", "element", "is", "not", "defined", "use", "some", "auto", "-", "detect", "logic", "to", "try", "and", "return", "the", "single", "Service", "of", "a", "specified", "field", ".", "If", "there", "is", "no", "service", "or", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security/src/com/ibm/ws/security/internal/SecurityServiceImpl.java#L401-L414
deeplearning4j/deeplearning4j
datavec/datavec-api/src/main/java/org/datavec/api/writable/Text.java
Text.encode
public static ByteBuffer encode(String string, boolean replace) throws CharacterCodingException { """ Converts the provided String to bytes using the UTF-8 encoding. If <code>replace</code> is true, then malformed input is replaced with the substitution character, which is U+FFFD. Otherwise the method throws a MalformedInputException. @return ByteBuffer: bytes stores at ByteBuffer.array() and length is ByteBuffer.limit() """ CharsetEncoder encoder = ENCODER_FACTORY.get(); if (replace) { encoder.onMalformedInput(CodingErrorAction.REPLACE); encoder.onUnmappableCharacter(CodingErrorAction.REPLACE); } ByteBuffer bytes = encoder.encode(CharBuffer.wrap(string.toCharArray())); if (replace) { encoder.onMalformedInput(CodingErrorAction.REPORT); encoder.onUnmappableCharacter(CodingErrorAction.REPORT); } return bytes; }
java
public static ByteBuffer encode(String string, boolean replace) throws CharacterCodingException { CharsetEncoder encoder = ENCODER_FACTORY.get(); if (replace) { encoder.onMalformedInput(CodingErrorAction.REPLACE); encoder.onUnmappableCharacter(CodingErrorAction.REPLACE); } ByteBuffer bytes = encoder.encode(CharBuffer.wrap(string.toCharArray())); if (replace) { encoder.onMalformedInput(CodingErrorAction.REPORT); encoder.onUnmappableCharacter(CodingErrorAction.REPORT); } return bytes; }
[ "public", "static", "ByteBuffer", "encode", "(", "String", "string", ",", "boolean", "replace", ")", "throws", "CharacterCodingException", "{", "CharsetEncoder", "encoder", "=", "ENCODER_FACTORY", ".", "get", "(", ")", ";", "if", "(", "replace", ")", "{", "enc...
Converts the provided String to bytes using the UTF-8 encoding. If <code>replace</code> is true, then malformed input is replaced with the substitution character, which is U+FFFD. Otherwise the method throws a MalformedInputException. @return ByteBuffer: bytes stores at ByteBuffer.array() and length is ByteBuffer.limit()
[ "Converts", "the", "provided", "String", "to", "bytes", "using", "the", "UTF", "-", "8", "encoding", ".", "If", "<code", ">", "replace<", "/", "code", ">", "is", "true", "then", "malformed", "input", "is", "replaced", "with", "the", "substitution", "charac...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-api/src/main/java/org/datavec/api/writable/Text.java#L374-L386
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_line_serviceName_phone_PUT
public void billingAccount_line_serviceName_phone_PUT(String billingAccount, String serviceName, OvhPhone body) throws IOException { """ Alter this object properties REST: PUT /telephony/{billingAccount}/line/{serviceName}/phone @param body [required] New object properties @param billingAccount [required] The name of your billingAccount @param serviceName [required] """ String qPath = "/telephony/{billingAccount}/line/{serviceName}/phone"; StringBuilder sb = path(qPath, billingAccount, serviceName); exec(qPath, "PUT", sb.toString(), body); }
java
public void billingAccount_line_serviceName_phone_PUT(String billingAccount, String serviceName, OvhPhone body) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/phone"; StringBuilder sb = path(qPath, billingAccount, serviceName); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "billingAccount_line_serviceName_phone_PUT", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "OvhPhone", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/line/{serviceName}/phone\"", ";", ...
Alter this object properties REST: PUT /telephony/{billingAccount}/line/{serviceName}/phone @param body [required] New object properties @param billingAccount [required] The name of your billingAccount @param serviceName [required]
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L982-L986
walkmod/walkmod-core
src/main/java/org/walkmod/WalkModFacade.java
WalkModFacade.addIncludesToChain
public void addIncludesToChain(String chain, List<String> includes, boolean recursive, boolean setToReader, boolean setToWriter) { """ Adds a list of includes rules into a chain @param chain Chain to apply the includes list @param includes List of includes @param recursive If it necessary to set the parameter to all the submodules. @param setToReader If it is added into the reader includes list @param setToWriter If it is added into the writer includes list """ long startTime = System.currentTimeMillis(); Exception exception = null; if (cfg.exists()) { userDir = new File(System.getProperty("user.dir")).getAbsolutePath(); System.setProperty("user.dir", options.getExecutionDirectory().getAbsolutePath()); try { ConfigurationManager manager = new ConfigurationManager(cfg, false); manager.getProjectConfigurationProvider().addIncludesToChain(chain, includes, recursive, setToReader, setToWriter); } catch (Exception e) { exception = e; } finally { System.setProperty("user.dir", userDir); updateMsg(startTime, exception); } } }
java
public void addIncludesToChain(String chain, List<String> includes, boolean recursive, boolean setToReader, boolean setToWriter) { long startTime = System.currentTimeMillis(); Exception exception = null; if (cfg.exists()) { userDir = new File(System.getProperty("user.dir")).getAbsolutePath(); System.setProperty("user.dir", options.getExecutionDirectory().getAbsolutePath()); try { ConfigurationManager manager = new ConfigurationManager(cfg, false); manager.getProjectConfigurationProvider().addIncludesToChain(chain, includes, recursive, setToReader, setToWriter); } catch (Exception e) { exception = e; } finally { System.setProperty("user.dir", userDir); updateMsg(startTime, exception); } } }
[ "public", "void", "addIncludesToChain", "(", "String", "chain", ",", "List", "<", "String", ">", "includes", ",", "boolean", "recursive", ",", "boolean", "setToReader", ",", "boolean", "setToWriter", ")", "{", "long", "startTime", "=", "System", ".", "currentT...
Adds a list of includes rules into a chain @param chain Chain to apply the includes list @param includes List of includes @param recursive If it necessary to set the parameter to all the submodules. @param setToReader If it is added into the reader includes list @param setToWriter If it is added into the writer includes list
[ "Adds", "a", "list", "of", "includes", "rules", "into", "a", "chain" ]
train
https://github.com/walkmod/walkmod-core/blob/fa79b836894fa00ca4b3e2bd26326a44b778f46f/src/main/java/org/walkmod/WalkModFacade.java#L1049-L1068
Metatavu/edelphi
edelphi/src/main/java/fi/metatavu/edelphi/utils/QueryDataUtils.java
QueryDataUtils.writeCsv
private static byte[] writeCsv(String[] columnHeaders, List<String[]> rows) throws IOException { """ Writes a CSV file @param columnHeaders headers @param rows rows @return CSV file @throws IOException throws IOException when CSV writing fails """ return writeCsv(columnHeaders, rows.stream().toArray(String[][]::new)); }
java
private static byte[] writeCsv(String[] columnHeaders, List<String[]> rows) throws IOException { return writeCsv(columnHeaders, rows.stream().toArray(String[][]::new)); }
[ "private", "static", "byte", "[", "]", "writeCsv", "(", "String", "[", "]", "columnHeaders", ",", "List", "<", "String", "[", "]", ">", "rows", ")", "throws", "IOException", "{", "return", "writeCsv", "(", "columnHeaders", ",", "rows", ".", "stream", "("...
Writes a CSV file @param columnHeaders headers @param rows rows @return CSV file @throws IOException throws IOException when CSV writing fails
[ "Writes", "a", "CSV", "file" ]
train
https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/utils/QueryDataUtils.java#L244-L246
Azure/azure-sdk-for-java
storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java
StorageAccountsInner.getByResourceGroupAsync
public Observable<StorageAccountInner> getByResourceGroupAsync(String resourceGroupName, String accountName) { """ Returns the properties for the specified storage account including but not limited to name, SKU name, location, and account status. The ListKeys operation should be used to retrieve storage keys. @param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive. @param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the StorageAccountInner object """ return getByResourceGroupWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<StorageAccountInner>, StorageAccountInner>() { @Override public StorageAccountInner call(ServiceResponse<StorageAccountInner> response) { return response.body(); } }); }
java
public Observable<StorageAccountInner> getByResourceGroupAsync(String resourceGroupName, String accountName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<StorageAccountInner>, StorageAccountInner>() { @Override public StorageAccountInner call(ServiceResponse<StorageAccountInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "StorageAccountInner", ">", "getByResourceGroupAsync", "(", "String", "resourceGroupName", ",", "String", "accountName", ")", "{", "return", "getByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ")", ".", ...
Returns the properties for the specified storage account including but not limited to name, SKU name, location, and account status. The ListKeys operation should be used to retrieve storage keys. @param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive. @param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the StorageAccountInner object
[ "Returns", "the", "properties", "for", "the", "specified", "storage", "account", "including", "but", "not", "limited", "to", "name", "SKU", "name", "location", "and", "account", "status", ".", "The", "ListKeys", "operation", "should", "be", "used", "to", "retr...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java#L509-L516
census-instrumentation/opencensus-java
contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardMetrics.java
DropWizardMetrics.collectGauge
@SuppressWarnings("rawtypes") @Nullable private Metric collectGauge(MetricName dropwizardMetric, Gauge gauge) { """ Returns a {@code Metric} collected from {@link Gauge}. @param dropwizardMetric the metric name. @param gauge the gauge object to collect. @return a {@code Metric}. """ // TODO cache dropwizard MetricName -> OC MetricDescriptor, Labels conversion String metricName = DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "gauge"); String metricDescription = DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), gauge); AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels = DropWizardUtils.generateLabels(dropwizardMetric); // Figure out which gauge instance and call the right method to get value Type type; Value value; Object obj = gauge.getValue(); if (obj instanceof Number) { type = Type.GAUGE_DOUBLE; value = Value.doubleValue(((Number) obj).doubleValue()); } else if (obj instanceof Boolean) { type = Type.GAUGE_INT64; value = Value.longValue(((Boolean) obj) ? 1 : 0); } else { // Ignoring Gauge (gauge.getKey()) with unhandled type. return null; } MetricDescriptor metricDescriptor = MetricDescriptor.create(metricName, metricDescription, DEFAULT_UNIT, type, labels.getKey()); TimeSeries timeSeries = TimeSeries.createWithOnePoint(labels.getValue(), Point.create(value, clock.now()), null); return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries); }
java
@SuppressWarnings("rawtypes") @Nullable private Metric collectGauge(MetricName dropwizardMetric, Gauge gauge) { // TODO cache dropwizard MetricName -> OC MetricDescriptor, Labels conversion String metricName = DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "gauge"); String metricDescription = DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), gauge); AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels = DropWizardUtils.generateLabels(dropwizardMetric); // Figure out which gauge instance and call the right method to get value Type type; Value value; Object obj = gauge.getValue(); if (obj instanceof Number) { type = Type.GAUGE_DOUBLE; value = Value.doubleValue(((Number) obj).doubleValue()); } else if (obj instanceof Boolean) { type = Type.GAUGE_INT64; value = Value.longValue(((Boolean) obj) ? 1 : 0); } else { // Ignoring Gauge (gauge.getKey()) with unhandled type. return null; } MetricDescriptor metricDescriptor = MetricDescriptor.create(metricName, metricDescription, DEFAULT_UNIT, type, labels.getKey()); TimeSeries timeSeries = TimeSeries.createWithOnePoint(labels.getValue(), Point.create(value, clock.now()), null); return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "@", "Nullable", "private", "Metric", "collectGauge", "(", "MetricName", "dropwizardMetric", ",", "Gauge", "gauge", ")", "{", "// TODO cache dropwizard MetricName -> OC MetricDescriptor, Labels conversion", "String", "metricN...
Returns a {@code Metric} collected from {@link Gauge}. @param dropwizardMetric the metric name. @param gauge the gauge object to collect. @return a {@code Metric}.
[ "Returns", "a", "{", "@code", "Metric", "}", "collected", "from", "{", "@link", "Gauge", "}", "." ]
train
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardMetrics.java#L104-L134
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/lss/LssClient.java
LssClient.pauseAppStream
public PauseAppStreamResponse pauseAppStream(String app, String stream) { """ Pause your app stream by app name and stream name @param app app name @param stream stream name @return the response """ PauseAppStreamRequest pauseAppStreamRequest = new PauseAppStreamRequest(); pauseAppStreamRequest.setApp(app); pauseAppStreamRequest.setStream(stream); return pauseAppStream(pauseAppStreamRequest); }
java
public PauseAppStreamResponse pauseAppStream(String app, String stream) { PauseAppStreamRequest pauseAppStreamRequest = new PauseAppStreamRequest(); pauseAppStreamRequest.setApp(app); pauseAppStreamRequest.setStream(stream); return pauseAppStream(pauseAppStreamRequest); }
[ "public", "PauseAppStreamResponse", "pauseAppStream", "(", "String", "app", ",", "String", "stream", ")", "{", "PauseAppStreamRequest", "pauseAppStreamRequest", "=", "new", "PauseAppStreamRequest", "(", ")", ";", "pauseAppStreamRequest", ".", "setApp", "(", "app", ")"...
Pause your app stream by app name and stream name @param app app name @param stream stream name @return the response
[ "Pause", "your", "app", "stream", "by", "app", "name", "and", "stream", "name" ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssClient.java#L907-L912
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java
SDMath.lastIndex
public SDVariable lastIndex(String name, SDVariable in, Condition condition, boolean keepDims, int... dimensions) { """ Last index reduction operation.<br> Returns a variable that contains the index of the last element that matches the specified condition (for each slice along the specified dimensions)<br> Note that if keepDims = true, the output variable has the same rank as the input variable, with the reduced dimensions having size 1. This can be useful for later broadcast operations (such as subtracting the mean along a dimension).<br> Example: if input has shape [a,b,c] and dimensions=[1] then output has shape: keepDims = true: [a,1,c]<br> keepDims = false: [a,c] @param name Name of the output variable @param in Input variable @param condition Condition to check on input variable @param dimensions Dimensions to reduce over. If dimensions are not specified, full array reduction is performed @return Reduced array of rank (input rank - num dimensions) """ SDVariable ret = f().lastIndex(in, condition, keepDims, dimensions); return updateVariableNameAndReference(ret, name); }
java
public SDVariable lastIndex(String name, SDVariable in, Condition condition, boolean keepDims, int... dimensions) { SDVariable ret = f().lastIndex(in, condition, keepDims, dimensions); return updateVariableNameAndReference(ret, name); }
[ "public", "SDVariable", "lastIndex", "(", "String", "name", ",", "SDVariable", "in", ",", "Condition", "condition", ",", "boolean", "keepDims", ",", "int", "...", "dimensions", ")", "{", "SDVariable", "ret", "=", "f", "(", ")", ".", "lastIndex", "(", "in",...
Last index reduction operation.<br> Returns a variable that contains the index of the last element that matches the specified condition (for each slice along the specified dimensions)<br> Note that if keepDims = true, the output variable has the same rank as the input variable, with the reduced dimensions having size 1. This can be useful for later broadcast operations (such as subtracting the mean along a dimension).<br> Example: if input has shape [a,b,c] and dimensions=[1] then output has shape: keepDims = true: [a,1,c]<br> keepDims = false: [a,c] @param name Name of the output variable @param in Input variable @param condition Condition to check on input variable @param dimensions Dimensions to reduce over. If dimensions are not specified, full array reduction is performed @return Reduced array of rank (input rank - num dimensions)
[ "Last", "index", "reduction", "operation", ".", "<br", ">", "Returns", "a", "variable", "that", "contains", "the", "index", "of", "the", "last", "element", "that", "matches", "the", "specified", "condition", "(", "for", "each", "slice", "along", "the", "spec...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java#L1505-L1508
VueGWT/vue-gwt
processors/src/main/java/com/axellience/vuegwt/processors/component/template/parser/TemplateParser.java
TemplateParser.parseHtmlTemplate
public TemplateParserResult parseHtmlTemplate(String htmlTemplate, TemplateParserContext context, Elements elements, Messager messager, URI htmlTemplateUri) { """ Parse a given HTML template and return the a result object containing the expressions and a transformed HTML. @param htmlTemplate The HTML template to process, as a String @param context Context of the Component we are currently processing @param messager Used to report errors in template during Annotation Processing @return A {@link TemplateParserResult} containing the processed template and expressions """ this.context = context; this.elements = elements; this.messager = messager; this.logger = new TemplateParserLogger(context, messager); this.htmlTemplateUri = htmlTemplateUri; initJerichoConfig(this.logger); Source source = new Source(htmlTemplate); outputDocument = new OutputDocument(source); result = new TemplateParserResult(context); processImports(source); result.setScopedCss(processScopedCss(source)); source.getChildElements().forEach(this::processElement); result.setProcessedTemplate(outputDocument.toString()); return result; }
java
public TemplateParserResult parseHtmlTemplate(String htmlTemplate, TemplateParserContext context, Elements elements, Messager messager, URI htmlTemplateUri) { this.context = context; this.elements = elements; this.messager = messager; this.logger = new TemplateParserLogger(context, messager); this.htmlTemplateUri = htmlTemplateUri; initJerichoConfig(this.logger); Source source = new Source(htmlTemplate); outputDocument = new OutputDocument(source); result = new TemplateParserResult(context); processImports(source); result.setScopedCss(processScopedCss(source)); source.getChildElements().forEach(this::processElement); result.setProcessedTemplate(outputDocument.toString()); return result; }
[ "public", "TemplateParserResult", "parseHtmlTemplate", "(", "String", "htmlTemplate", ",", "TemplateParserContext", "context", ",", "Elements", "elements", ",", "Messager", "messager", ",", "URI", "htmlTemplateUri", ")", "{", "this", ".", "context", "=", "context", ...
Parse a given HTML template and return the a result object containing the expressions and a transformed HTML. @param htmlTemplate The HTML template to process, as a String @param context Context of the Component we are currently processing @param messager Used to report errors in template during Annotation Processing @return A {@link TemplateParserResult} containing the processed template and expressions
[ "Parse", "a", "given", "HTML", "template", "and", "return", "the", "a", "result", "object", "containing", "the", "expressions", "and", "a", "transformed", "HTML", "." ]
train
https://github.com/VueGWT/vue-gwt/blob/961cd83aed6fe8e2dd80c279847f1b3f62918a1f/processors/src/main/java/com/axellience/vuegwt/processors/component/template/parser/TemplateParser.java#L101-L121
playn/playn
java-base/src/playn/java/JavaGraphics.java
JavaGraphics.registerFont
public void registerFont (String name, java.awt.Font font) { """ Registers a font with the graphics system. @param name the name under which to register the font. @param font the Java font, which can be loaded from a path via {@link JavaAssets#getFont}. """ if (font == null) throw new NullPointerException(); fonts.put(name, font); }
java
public void registerFont (String name, java.awt.Font font) { if (font == null) throw new NullPointerException(); fonts.put(name, font); }
[ "public", "void", "registerFont", "(", "String", "name", ",", "java", ".", "awt", ".", "Font", "font", ")", "{", "if", "(", "font", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "fonts", ".", "put", "(", "name", ",", "font...
Registers a font with the graphics system. @param name the name under which to register the font. @param font the Java font, which can be loaded from a path via {@link JavaAssets#getFont}.
[ "Registers", "a", "font", "with", "the", "graphics", "system", "." ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/java-base/src/playn/java/JavaGraphics.java#L72-L75
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java
TypesafeConfigUtils.loadConfig
public static Config loadConfig(URL configUrl, boolean useSystemEnvironment) { """ Load, Parse & Resolve configurations from a URL, with default parse & resolve options. @param configUrl @param useSystemEnvironment {@code true} to resolve substitutions falling back to environment variables @return """ return loadConfig(ConfigParseOptions.defaults(), ConfigResolveOptions.defaults().setUseSystemEnvironment(useSystemEnvironment), configUrl); }
java
public static Config loadConfig(URL configUrl, boolean useSystemEnvironment) { return loadConfig(ConfigParseOptions.defaults(), ConfigResolveOptions.defaults().setUseSystemEnvironment(useSystemEnvironment), configUrl); }
[ "public", "static", "Config", "loadConfig", "(", "URL", "configUrl", ",", "boolean", "useSystemEnvironment", ")", "{", "return", "loadConfig", "(", "ConfigParseOptions", ".", "defaults", "(", ")", ",", "ConfigResolveOptions", ".", "defaults", "(", ")", ".", "set...
Load, Parse & Resolve configurations from a URL, with default parse & resolve options. @param configUrl @param useSystemEnvironment {@code true} to resolve substitutions falling back to environment variables @return
[ "Load", "Parse", "&", "Resolve", "configurations", "from", "a", "URL", "with", "default", "parse", "&", "resolve", "options", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java#L103-L107
googleapis/google-oauth-java-client
google-oauth-client/src/main/java/com/google/api/client/auth/oauth2/AuthorizationCodeFlow.java
AuthorizationCodeFlow.newCredential
@SuppressWarnings("deprecation") private Credential newCredential(String userId) { """ Returns a new credential instance based on the given user ID. @param userId user ID or {@code null} if not using a persisted credential store """ Credential.Builder builder = new Credential.Builder(method).setTransport(transport) .setJsonFactory(jsonFactory) .setTokenServerEncodedUrl(tokenServerEncodedUrl) .setClientAuthentication(clientAuthentication) .setRequestInitializer(requestInitializer) .setClock(clock); if (credentialDataStore != null) { builder.addRefreshListener( new DataStoreCredentialRefreshListener(userId, credentialDataStore)); } else if (credentialStore != null) { builder.addRefreshListener(new CredentialStoreRefreshListener(userId, credentialStore)); } builder.getRefreshListeners().addAll(refreshListeners); return builder.build(); }
java
@SuppressWarnings("deprecation") private Credential newCredential(String userId) { Credential.Builder builder = new Credential.Builder(method).setTransport(transport) .setJsonFactory(jsonFactory) .setTokenServerEncodedUrl(tokenServerEncodedUrl) .setClientAuthentication(clientAuthentication) .setRequestInitializer(requestInitializer) .setClock(clock); if (credentialDataStore != null) { builder.addRefreshListener( new DataStoreCredentialRefreshListener(userId, credentialDataStore)); } else if (credentialStore != null) { builder.addRefreshListener(new CredentialStoreRefreshListener(userId, credentialStore)); } builder.getRefreshListeners().addAll(refreshListeners); return builder.build(); }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "private", "Credential", "newCredential", "(", "String", "userId", ")", "{", "Credential", ".", "Builder", "builder", "=", "new", "Credential", ".", "Builder", "(", "method", ")", ".", "setTransport", "(", ...
Returns a new credential instance based on the given user ID. @param userId user ID or {@code null} if not using a persisted credential store
[ "Returns", "a", "new", "credential", "instance", "based", "on", "the", "given", "user", "ID", "." ]
train
https://github.com/googleapis/google-oauth-java-client/blob/7a829f8fd4d216c7d5882a82b9b58930fb375592/google-oauth-client/src/main/java/com/google/api/client/auth/oauth2/AuthorizationCodeFlow.java#L276-L292
OpenLiberty/open-liberty
dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/ChannelFrameworkImpl.java
ChannelFrameworkImpl.stringForMap
public static String stringForMap(Map<Object, Object> map) { """ Utility method to extract a string representing the contents of a map. This is currently used by various methods as part of debug tracing. @param map @return string representing contents of Map """ StringBuilder sbOutput = new StringBuilder(); if (map == null) { sbOutput.append("\tNULL"); } else { for (Entry<Object, Object> entry : map.entrySet()) { sbOutput.append('\t').append(entry).append('\n'); } } return sbOutput.toString(); }
java
public static String stringForMap(Map<Object, Object> map) { StringBuilder sbOutput = new StringBuilder(); if (map == null) { sbOutput.append("\tNULL"); } else { for (Entry<Object, Object> entry : map.entrySet()) { sbOutput.append('\t').append(entry).append('\n'); } } return sbOutput.toString(); }
[ "public", "static", "String", "stringForMap", "(", "Map", "<", "Object", ",", "Object", ">", "map", ")", "{", "StringBuilder", "sbOutput", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "map", "==", "null", ")", "{", "sbOutput", ".", "append", ...
Utility method to extract a string representing the contents of a map. This is currently used by various methods as part of debug tracing. @param map @return string representing contents of Map
[ "Utility", "method", "to", "extract", "a", "string", "representing", "the", "contents", "of", "a", "map", ".", "This", "is", "currently", "used", "by", "various", "methods", "as", "part", "of", "debug", "tracing", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/ChannelFrameworkImpl.java#L700-L710
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MultiIndex.java
MultiIndex.getIndexReaders
synchronized IndexReader[] getIndexReaders(String[] indexNames, IndexListener listener) throws IOException { """ Returns <code>IndexReader</code>s for the indexes named <code>indexNames</code>. An <code>IndexListener</code> is registered and notified when documents are deleted from one of the indexes in <code>indexNames</code>. <br> Note: the number of <code>IndexReaders</code> returned by this method is not necessarily the same as the number of index names passed. An index might have been deleted and is not reachable anymore. @param indexNames the names of the indexes for which to obtain readers. @param listener the listener to notify when documents are deleted. @return the <code>IndexReaders</code>. @throws IOException if an error occurs acquiring the index readers. """ Set<String> names = new HashSet<String>(Arrays.asList(indexNames)); Map<ReadOnlyIndexReader, PersistentIndex> indexReaders = new HashMap<ReadOnlyIndexReader, PersistentIndex>(); try { for (Iterator<PersistentIndex> it = indexes.iterator(); it.hasNext();) { PersistentIndex index = it.next(); if (names.contains(index.getName())) { indexReaders.put(index.getReadOnlyIndexReader(listener), index); } } } catch (IOException e) { // release readers obtained so far for (Iterator<Entry<ReadOnlyIndexReader, PersistentIndex>> it = indexReaders.entrySet().iterator(); it .hasNext();) { Map.Entry<ReadOnlyIndexReader, PersistentIndex> entry = it.next(); final ReadOnlyIndexReader reader = entry.getKey(); try { SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { reader.release(); return null; } }); } catch (IOException ex) { LOG.warn("Exception releasing index reader: " + ex); } (entry.getValue()).resetListener(); } throw e; } return indexReaders.keySet().toArray(new IndexReader[indexReaders.size()]); }
java
synchronized IndexReader[] getIndexReaders(String[] indexNames, IndexListener listener) throws IOException { Set<String> names = new HashSet<String>(Arrays.asList(indexNames)); Map<ReadOnlyIndexReader, PersistentIndex> indexReaders = new HashMap<ReadOnlyIndexReader, PersistentIndex>(); try { for (Iterator<PersistentIndex> it = indexes.iterator(); it.hasNext();) { PersistentIndex index = it.next(); if (names.contains(index.getName())) { indexReaders.put(index.getReadOnlyIndexReader(listener), index); } } } catch (IOException e) { // release readers obtained so far for (Iterator<Entry<ReadOnlyIndexReader, PersistentIndex>> it = indexReaders.entrySet().iterator(); it .hasNext();) { Map.Entry<ReadOnlyIndexReader, PersistentIndex> entry = it.next(); final ReadOnlyIndexReader reader = entry.getKey(); try { SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { reader.release(); return null; } }); } catch (IOException ex) { LOG.warn("Exception releasing index reader: " + ex); } (entry.getValue()).resetListener(); } throw e; } return indexReaders.keySet().toArray(new IndexReader[indexReaders.size()]); }
[ "synchronized", "IndexReader", "[", "]", "getIndexReaders", "(", "String", "[", "]", "indexNames", ",", "IndexListener", "listener", ")", "throws", "IOException", "{", "Set", "<", "String", ">", "names", "=", "new", "HashSet", "<", "String", ">", "(", "Array...
Returns <code>IndexReader</code>s for the indexes named <code>indexNames</code>. An <code>IndexListener</code> is registered and notified when documents are deleted from one of the indexes in <code>indexNames</code>. <br> Note: the number of <code>IndexReaders</code> returned by this method is not necessarily the same as the number of index names passed. An index might have been deleted and is not reachable anymore. @param indexNames the names of the indexes for which to obtain readers. @param listener the listener to notify when documents are deleted. @return the <code>IndexReaders</code>. @throws IOException if an error occurs acquiring the index readers.
[ "Returns", "<code", ">", "IndexReader<", "/", "code", ">", "s", "for", "the", "indexes", "named", "<code", ">", "indexNames<", "/", "code", ">", ".", "An", "<code", ">", "IndexListener<", "/", "code", ">", "is", "registered", "and", "notified", "when", "...
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MultiIndex.java#L1146-L1191
SeaCloudsEU/SeaCloudsPlatform
sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/TemplateRestEntity.java
TemplateRestEntity.deleteTemplate
@DELETE @Path(" { """ Deletes a template given the corresponding template_id <pre> DELETE /templates/{template_id} Request: DELETE /templates HTTP/1.1 Response: {@code <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <message code="204" message="The template with uuid:contract-template-2007-12-04 was deleted successfully"/> } </pre> Example: <li>curl -X DELETE localhost:8080/sla-service/templates/contract-template-2007-12-04</li> @param id of the template @throws Exception """uuid}") public Response deleteTemplate(@PathParam("uuid") String uuid) { logger.debug("DELETE /templates/{}", uuid); TemplateHelperE templateRestHelper = getTemplateHelper(); boolean deleted; try { deleted = templateRestHelper.deleteTemplateByUuid(uuid); if (deleted) return buildResponse(HttpStatus.OK, /*egarrido it was returned HttpStatus.NO_CONTENT, I don't know why */ "Template with uuid " + uuid + " was deleted successfully"); else return buildResponse(HttpStatus.NOT_FOUND, printError(HttpStatus.NOT_FOUND, "There is no template with uuid " + uuid + " in the SLA Repository Database")); } catch (DBExistsHelperException e) { logger.info("deleteTemplate Conflict:"+e.getMessage()); return buildResponse(HttpStatus.CONFLICT, printError(HttpStatus.CONFLICT, e.getMessage())); } }
java
@DELETE @Path("{uuid}") public Response deleteTemplate(@PathParam("uuid") String uuid) { logger.debug("DELETE /templates/{}", uuid); TemplateHelperE templateRestHelper = getTemplateHelper(); boolean deleted; try { deleted = templateRestHelper.deleteTemplateByUuid(uuid); if (deleted) return buildResponse(HttpStatus.OK, /*egarrido it was returned HttpStatus.NO_CONTENT, I don't know why */ "Template with uuid " + uuid + " was deleted successfully"); else return buildResponse(HttpStatus.NOT_FOUND, printError(HttpStatus.NOT_FOUND, "There is no template with uuid " + uuid + " in the SLA Repository Database")); } catch (DBExistsHelperException e) { logger.info("deleteTemplate Conflict:"+e.getMessage()); return buildResponse(HttpStatus.CONFLICT, printError(HttpStatus.CONFLICT, e.getMessage())); } }
[ "@", "DELETE", "@", "Path", "(", "\"{uuid}\"", ")", "public", "Response", "deleteTemplate", "(", "@", "PathParam", "(", "\"uuid\"", ")", "String", "uuid", ")", "{", "logger", ".", "debug", "(", "\"DELETE /templates/{}\"", ",", "uuid", ")", ";", "TemplateHelp...
Deletes a template given the corresponding template_id <pre> DELETE /templates/{template_id} Request: DELETE /templates HTTP/1.1 Response: {@code <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <message code="204" message="The template with uuid:contract-template-2007-12-04 was deleted successfully"/> } </pre> Example: <li>curl -X DELETE localhost:8080/sla-service/templates/contract-template-2007-12-04</li> @param id of the template @throws Exception
[ "Deletes", "a", "template", "given", "the", "corresponding", "template_id" ]
train
https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/TemplateRestEntity.java#L245-L264
bbossgroups/bboss-elasticsearch
bboss-elasticsearch-rest/src/main/java/org/frameworkset/elasticsearch/client/RestClientUtil.java
RestClientUtil.createIndiceMapping
public String createIndiceMapping(String indexName,String indexMapping) throws ElasticSearchException { """ 创建索引定义 curl -XPUT 'localhost:9200/test?pretty' -H 'Content-Type: application/json' -d' { "settings" : { "number_of_shards" : 1 }, "mappings" : { "type1" : { "properties" : { "field1" : { "type" : "text" } } } } } @param indexMapping @return @throws ElasticSearchException """ return this.client.executeHttp(handleIndexName(indexName),indexMapping,ClientUtil.HTTP_PUT); }
java
public String createIndiceMapping(String indexName,String indexMapping) throws ElasticSearchException { return this.client.executeHttp(handleIndexName(indexName),indexMapping,ClientUtil.HTTP_PUT); }
[ "public", "String", "createIndiceMapping", "(", "String", "indexName", ",", "String", "indexMapping", ")", "throws", "ElasticSearchException", "{", "return", "this", ".", "client", ".", "executeHttp", "(", "handleIndexName", "(", "indexName", ")", ",", "indexMapping...
创建索引定义 curl -XPUT 'localhost:9200/test?pretty' -H 'Content-Type: application/json' -d' { "settings" : { "number_of_shards" : 1 }, "mappings" : { "type1" : { "properties" : { "field1" : { "type" : "text" } } } } } @param indexMapping @return @throws ElasticSearchException
[ "创建索引定义", "curl", "-", "XPUT", "localhost", ":", "9200", "/", "test?pretty", "-", "H", "Content", "-", "Type", ":", "application", "/", "json", "-", "d", "{", "settings", ":", "{", "number_of_shards", ":", "1", "}", "mappings", ":", "{", "type1", ":", ...
train
https://github.com/bbossgroups/bboss-elasticsearch/blob/31717c8aa2c4c880987be53aeeb8a0cf5183c3a7/bboss-elasticsearch-rest/src/main/java/org/frameworkset/elasticsearch/client/RestClientUtil.java#L2803-L2805
molgenis/molgenis
molgenis-r/src/main/java/org/molgenis/r/RScriptExecutor.java
RScriptExecutor.executeScriptGetValueRequest
private String executeScriptGetValueRequest(String openCpuSessionKey) throws IOException { """ Retrieve and return R script STDOUT response using OpenCPU @param openCpuSessionKey OpenCPU session key @return R script STDOUT @throws IOException if error occured during script response retrieval """ URI scriptGetValueResponseUri = getScriptGetValueResponseUri(openCpuSessionKey); HttpGet httpGet = new HttpGet(scriptGetValueResponseUri); String responseValue; try (CloseableHttpResponse response = httpClient.execute(httpGet)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); responseValue = EntityUtils.toString(entity); EntityUtils.consume(entity); } else { throw new ClientProtocolException(format(FORMAT_UNEXPECTED_RESPONSE_STATUS, statusCode)); } } return responseValue; }
java
private String executeScriptGetValueRequest(String openCpuSessionKey) throws IOException { URI scriptGetValueResponseUri = getScriptGetValueResponseUri(openCpuSessionKey); HttpGet httpGet = new HttpGet(scriptGetValueResponseUri); String responseValue; try (CloseableHttpResponse response = httpClient.execute(httpGet)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); responseValue = EntityUtils.toString(entity); EntityUtils.consume(entity); } else { throw new ClientProtocolException(format(FORMAT_UNEXPECTED_RESPONSE_STATUS, statusCode)); } } return responseValue; }
[ "private", "String", "executeScriptGetValueRequest", "(", "String", "openCpuSessionKey", ")", "throws", "IOException", "{", "URI", "scriptGetValueResponseUri", "=", "getScriptGetValueResponseUri", "(", "openCpuSessionKey", ")", ";", "HttpGet", "httpGet", "=", "new", "Http...
Retrieve and return R script STDOUT response using OpenCPU @param openCpuSessionKey OpenCPU session key @return R script STDOUT @throws IOException if error occured during script response retrieval
[ "Retrieve", "and", "return", "R", "script", "STDOUT", "response", "using", "OpenCPU" ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-r/src/main/java/org/molgenis/r/RScriptExecutor.java#L162-L177
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.setParentList
@UiThread public void setParentList(@NonNull List<P> parentList, boolean preserveExpansionState) { """ Set a new list of parents and notify any registered observers that the data set has changed. <p> This setter does not specify what about the data set has changed, forcing any observers to assume that all existing items and structure may no longer be valid. LayoutManagers will be forced to fully rebind and relayout all visible views.</p> <p> It will always be more efficient to use the more specific change events if you can. Rely on {@code #setParentList(List, boolean)} as a last resort. There will be no animation of changes, unlike the more specific change events listed below. @see #notifyParentInserted(int) @see #notifyParentRemoved(int) @see #notifyParentChanged(int) @see #notifyParentRangeInserted(int, int) @see #notifyChildInserted(int, int) @see #notifyChildRemoved(int, int) @see #notifyChildChanged(int, int) @param preserveExpansionState If true, the adapter will attempt to preserve your parent's last expanded state. This depends on object equality for comparisons of old parents to parents in the new list. If false, only {@link Parent#isInitiallyExpanded()} will be used to determine expanded state. """ mParentList = parentList; notifyParentDataSetChanged(preserveExpansionState); }
java
@UiThread public void setParentList(@NonNull List<P> parentList, boolean preserveExpansionState) { mParentList = parentList; notifyParentDataSetChanged(preserveExpansionState); }
[ "@", "UiThread", "public", "void", "setParentList", "(", "@", "NonNull", "List", "<", "P", ">", "parentList", ",", "boolean", "preserveExpansionState", ")", "{", "mParentList", "=", "parentList", ";", "notifyParentDataSetChanged", "(", "preserveExpansionState", ")",...
Set a new list of parents and notify any registered observers that the data set has changed. <p> This setter does not specify what about the data set has changed, forcing any observers to assume that all existing items and structure may no longer be valid. LayoutManagers will be forced to fully rebind and relayout all visible views.</p> <p> It will always be more efficient to use the more specific change events if you can. Rely on {@code #setParentList(List, boolean)} as a last resort. There will be no animation of changes, unlike the more specific change events listed below. @see #notifyParentInserted(int) @see #notifyParentRemoved(int) @see #notifyParentChanged(int) @see #notifyParentRangeInserted(int, int) @see #notifyChildInserted(int, int) @see #notifyChildRemoved(int, int) @see #notifyChildChanged(int, int) @param preserveExpansionState If true, the adapter will attempt to preserve your parent's last expanded state. This depends on object equality for comparisons of old parents to parents in the new list. If false, only {@link Parent#isInitiallyExpanded()} will be used to determine expanded state.
[ "Set", "a", "new", "list", "of", "parents", "and", "notify", "any", "registered", "observers", "that", "the", "data", "set", "has", "changed", ".", "<p", ">", "This", "setter", "does", "not", "specify", "what", "about", "the", "data", "set", "has", "chan...
train
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L370-L374
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/client/SchedulerClientFactory.java
SchedulerClientFactory.getSchedulerClient
public ISchedulerClient getSchedulerClient() throws SchedulerException { """ Implementation of getSchedulerClient - Used to create objects Currently it creates either HttpServiceSchedulerClient or LibrarySchedulerClient @return getSchedulerClient created. return null if failed to create ISchedulerClient instance """ LOG.fine("Creating scheduler client"); ISchedulerClient schedulerClient; if (Context.schedulerService(config)) { // get the instance of the state manager SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime); Scheduler.SchedulerLocation schedulerLocation = statemgr.getSchedulerLocation(Runtime.topologyName(runtime)); if (schedulerLocation == null) { throw new SchedulerException("Failed to get scheduler location from state manager"); } LOG.log(Level.FINE, "Scheduler is listening on location: {0} ", schedulerLocation.toString()); schedulerClient = new HttpServiceSchedulerClient(config, runtime, schedulerLocation.getHttpEndpoint()); } else { // create an instance of scheduler final IScheduler scheduler = LauncherUtils.getInstance() .getSchedulerInstance(config, runtime); LOG.fine("Invoke scheduler as a library"); schedulerClient = new LibrarySchedulerClient(config, runtime, scheduler); } return schedulerClient; }
java
public ISchedulerClient getSchedulerClient() throws SchedulerException { LOG.fine("Creating scheduler client"); ISchedulerClient schedulerClient; if (Context.schedulerService(config)) { // get the instance of the state manager SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime); Scheduler.SchedulerLocation schedulerLocation = statemgr.getSchedulerLocation(Runtime.topologyName(runtime)); if (schedulerLocation == null) { throw new SchedulerException("Failed to get scheduler location from state manager"); } LOG.log(Level.FINE, "Scheduler is listening on location: {0} ", schedulerLocation.toString()); schedulerClient = new HttpServiceSchedulerClient(config, runtime, schedulerLocation.getHttpEndpoint()); } else { // create an instance of scheduler final IScheduler scheduler = LauncherUtils.getInstance() .getSchedulerInstance(config, runtime); LOG.fine("Invoke scheduler as a library"); schedulerClient = new LibrarySchedulerClient(config, runtime, scheduler); } return schedulerClient; }
[ "public", "ISchedulerClient", "getSchedulerClient", "(", ")", "throws", "SchedulerException", "{", "LOG", ".", "fine", "(", "\"Creating scheduler client\"", ")", ";", "ISchedulerClient", "schedulerClient", ";", "if", "(", "Context", ".", "schedulerService", "(", "conf...
Implementation of getSchedulerClient - Used to create objects Currently it creates either HttpServiceSchedulerClient or LibrarySchedulerClient @return getSchedulerClient created. return null if failed to create ISchedulerClient instance
[ "Implementation", "of", "getSchedulerClient", "-", "Used", "to", "create", "objects", "Currently", "it", "creates", "either", "HttpServiceSchedulerClient", "or", "LibrarySchedulerClient" ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/client/SchedulerClientFactory.java#L52-L81
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java
JBBPDslBuilder.UByte
public JBBPDslBuilder UByte(final String name) { """ Add named unsigned byte field. @param name name of the field, can be null for anonymous one @return the builder instance, must not be null """ final Item item = new Item(BinType.UBYTE, name, this.byteOrder); this.addItem(item); return this; }
java
public JBBPDslBuilder UByte(final String name) { final Item item = new Item(BinType.UBYTE, name, this.byteOrder); this.addItem(item); return this; }
[ "public", "JBBPDslBuilder", "UByte", "(", "final", "String", "name", ")", "{", "final", "Item", "item", "=", "new", "Item", "(", "BinType", ".", "UBYTE", ",", "name", ",", "this", ".", "byteOrder", ")", ";", "this", ".", "addItem", "(", "item", ")", ...
Add named unsigned byte field. @param name name of the field, can be null for anonymous one @return the builder instance, must not be null
[ "Add", "named", "unsigned", "byte", "field", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L893-L897
aws/aws-cloudtrail-processing-library
src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/manager/SqsManager.java
SqsManager.pollQueue
public List<Message> pollQueue() { """ Poll SQS queue for incoming messages, filter them, and return a list of SQS Messages. @return a list of SQS messages. """ boolean success = false; ProgressStatus pollQueueStatus = new ProgressStatus(ProgressState.pollQueue, new BasicPollQueueInfo(0, success)); final Object reportObject = progressReporter.reportStart(pollQueueStatus); ReceiveMessageRequest request = new ReceiveMessageRequest().withAttributeNames(ALL_ATTRIBUTES); request.setQueueUrl(config.getSqsUrl()); request.setVisibilityTimeout(config.getVisibilityTimeout()); request.setMaxNumberOfMessages(DEFAULT_SQS_MESSAGE_SIZE_LIMIT); request.setWaitTimeSeconds(DEFAULT_WAIT_TIME_SECONDS); List<Message> sqsMessages = new ArrayList<Message>(); try { ReceiveMessageResult result = sqsClient.receiveMessage(request); sqsMessages = result.getMessages(); logger.info("Polled " + sqsMessages.size() + " sqs messages from " + config.getSqsUrl()); success = true; } catch (AmazonServiceException e) { LibraryUtils.handleException(exceptionHandler, pollQueueStatus, e, "Failed to poll sqs message."); } finally { LibraryUtils.endToProcess(progressReporter, success, pollQueueStatus, reportObject); } return sqsMessages; }
java
public List<Message> pollQueue() { boolean success = false; ProgressStatus pollQueueStatus = new ProgressStatus(ProgressState.pollQueue, new BasicPollQueueInfo(0, success)); final Object reportObject = progressReporter.reportStart(pollQueueStatus); ReceiveMessageRequest request = new ReceiveMessageRequest().withAttributeNames(ALL_ATTRIBUTES); request.setQueueUrl(config.getSqsUrl()); request.setVisibilityTimeout(config.getVisibilityTimeout()); request.setMaxNumberOfMessages(DEFAULT_SQS_MESSAGE_SIZE_LIMIT); request.setWaitTimeSeconds(DEFAULT_WAIT_TIME_SECONDS); List<Message> sqsMessages = new ArrayList<Message>(); try { ReceiveMessageResult result = sqsClient.receiveMessage(request); sqsMessages = result.getMessages(); logger.info("Polled " + sqsMessages.size() + " sqs messages from " + config.getSqsUrl()); success = true; } catch (AmazonServiceException e) { LibraryUtils.handleException(exceptionHandler, pollQueueStatus, e, "Failed to poll sqs message."); } finally { LibraryUtils.endToProcess(progressReporter, success, pollQueueStatus, reportObject); } return sqsMessages; }
[ "public", "List", "<", "Message", ">", "pollQueue", "(", ")", "{", "boolean", "success", "=", "false", ";", "ProgressStatus", "pollQueueStatus", "=", "new", "ProgressStatus", "(", "ProgressState", ".", "pollQueue", ",", "new", "BasicPollQueueInfo", "(", "0", "...
Poll SQS queue for incoming messages, filter them, and return a list of SQS Messages. @return a list of SQS messages.
[ "Poll", "SQS", "queue", "for", "incoming", "messages", "filter", "them", "and", "return", "a", "list", "of", "SQS", "Messages", "." ]
train
https://github.com/aws/aws-cloudtrail-processing-library/blob/411315808d8d3dc6b45e4182212e3e04d82e3782/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/manager/SqsManager.java#L113-L140
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/common/Similarity.java
Similarity.getSimilarity
public static <T extends Vector> double getSimilarity( SimType similarityType, T a, T b) { """ Calculates the similarity of the two vectors using the provided similarity measure. @param similarityType the similarity evaluation to use when comparing {@code a} and {@code b} @param a a {@code Vector} @param b a {@code Vector} @return the similarity according to the specified measure """ switch (similarityType) { case COSINE: return cosineSimilarity(a, b); case PEARSON_CORRELATION: return correlation(a, b); case EUCLIDEAN: return euclideanSimilarity(a, b); case SPEARMAN_RANK_CORRELATION: return spearmanRankCorrelationCoefficient(a, b); case JACCARD_INDEX: return jaccardIndex(a, b); case AVERAGE_COMMON_FEATURE_RANK: return averageCommonFeatureRank(a, b); case LIN: return linSimilarity(a, b); case KL_DIVERGENCE: return klDivergence(a, b); case KENDALLS_TAU: return kendallsTau(a, b); case TANIMOTO_COEFFICIENT: return tanimotoCoefficient(a, b); } return 0; }
java
public static <T extends Vector> double getSimilarity( SimType similarityType, T a, T b) { switch (similarityType) { case COSINE: return cosineSimilarity(a, b); case PEARSON_CORRELATION: return correlation(a, b); case EUCLIDEAN: return euclideanSimilarity(a, b); case SPEARMAN_RANK_CORRELATION: return spearmanRankCorrelationCoefficient(a, b); case JACCARD_INDEX: return jaccardIndex(a, b); case AVERAGE_COMMON_FEATURE_RANK: return averageCommonFeatureRank(a, b); case LIN: return linSimilarity(a, b); case KL_DIVERGENCE: return klDivergence(a, b); case KENDALLS_TAU: return kendallsTau(a, b); case TANIMOTO_COEFFICIENT: return tanimotoCoefficient(a, b); } return 0; }
[ "public", "static", "<", "T", "extends", "Vector", ">", "double", "getSimilarity", "(", "SimType", "similarityType", ",", "T", "a", ",", "T", "b", ")", "{", "switch", "(", "similarityType", ")", "{", "case", "COSINE", ":", "return", "cosineSimilarity", "("...
Calculates the similarity of the two vectors using the provided similarity measure. @param similarityType the similarity evaluation to use when comparing {@code a} and {@code b} @param a a {@code Vector} @param b a {@code Vector} @return the similarity according to the specified measure
[ "Calculates", "the", "similarity", "of", "the", "two", "vectors", "using", "the", "provided", "similarity", "measure", "." ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/common/Similarity.java#L260-L285
hsiafan/requests
src/main/java/net/dongliu/requests/Header.java
Header.of
public static Header of(String name, String value) { """ Create new header. @param name header name @param value header value @return header """ return new Header(requireNonNull(name), requireNonNull(value)); }
java
public static Header of(String name, String value) { return new Header(requireNonNull(name), requireNonNull(value)); }
[ "public", "static", "Header", "of", "(", "String", "name", ",", "String", "value", ")", "{", "return", "new", "Header", "(", "requireNonNull", "(", "name", ")", ",", "requireNonNull", "(", "value", ")", ")", ";", "}" ]
Create new header. @param name header name @param value header value @return header
[ "Create", "new", "header", "." ]
train
https://github.com/hsiafan/requests/blob/a6cc6f8293e808cc937d3789aec2616a8383dee0/src/main/java/net/dongliu/requests/Header.java#L35-L37
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/component/dataTable/DataTableRenderer.java
DataTableRenderer.determineLanguageUrl
private String determineLanguageUrl(FacesContext fc, String lang) { """ Determine the locale to set-up to dataTable component. The locale is determined in this order: - if customLangUrl is specified, it is the value set up - otherwise, the system check if locale is explicit specified - otherwise it takes from the ViewRoot @param fc @param dataTable @return """ // Build resource url return fc.getApplication().getResourceHandler() .createResource("jq/ui/i18n/dt/datatable-" + lang + ".json", C.BSF_LIBRARY).getRequestPath(); }
java
private String determineLanguageUrl(FacesContext fc, String lang) { // Build resource url return fc.getApplication().getResourceHandler() .createResource("jq/ui/i18n/dt/datatable-" + lang + ".json", C.BSF_LIBRARY).getRequestPath(); }
[ "private", "String", "determineLanguageUrl", "(", "FacesContext", "fc", ",", "String", "lang", ")", "{", "// Build resource url", "return", "fc", ".", "getApplication", "(", ")", ".", "getResourceHandler", "(", ")", ".", "createResource", "(", "\"jq/ui/i18n/dt/datat...
Determine the locale to set-up to dataTable component. The locale is determined in this order: - if customLangUrl is specified, it is the value set up - otherwise, the system check if locale is explicit specified - otherwise it takes from the ViewRoot @param fc @param dataTable @return
[ "Determine", "the", "locale", "to", "set", "-", "up", "to", "dataTable", "component", ".", "The", "locale", "is", "determined", "in", "this", "order", ":", "-", "if", "customLangUrl", "is", "specified", "it", "is", "the", "value", "set", "up", "-", "othe...
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/dataTable/DataTableRenderer.java#L880-L884
prestodb/presto
presto-spi/src/main/java/com/facebook/presto/spi/type/UnscaledDecimal128Arithmetic.java
UnscaledDecimal128Arithmetic.multiplyAndSubtractUnsignedMultiPrecision
private static boolean multiplyAndSubtractUnsignedMultiPrecision(int[] left, int leftOffset, int[] right, int length, int multiplier) { """ Calculate multi-precision [left - right * multiplier] with given left offset and length. Return true when overflow occurred """ long unsignedMultiplier = multiplier & LONG_MASK; int leftIndex = leftOffset - length; long multiplyAccumulator = 0; long subtractAccumulator = INT_BASE; for (int rightIndex = 0; rightIndex < length; rightIndex++, leftIndex++) { multiplyAccumulator = (right[rightIndex] & LONG_MASK) * unsignedMultiplier + multiplyAccumulator; subtractAccumulator = (subtractAccumulator + (left[leftIndex] & LONG_MASK)) - (lowInt(multiplyAccumulator) & LONG_MASK); multiplyAccumulator = (multiplyAccumulator >>> 32); left[leftIndex] = lowInt(subtractAccumulator); subtractAccumulator = (subtractAccumulator >>> 32) + INT_BASE - 1; } subtractAccumulator += (left[leftIndex] & LONG_MASK) - multiplyAccumulator; left[leftIndex] = lowInt(subtractAccumulator); return highInt(subtractAccumulator) == 0; }
java
private static boolean multiplyAndSubtractUnsignedMultiPrecision(int[] left, int leftOffset, int[] right, int length, int multiplier) { long unsignedMultiplier = multiplier & LONG_MASK; int leftIndex = leftOffset - length; long multiplyAccumulator = 0; long subtractAccumulator = INT_BASE; for (int rightIndex = 0; rightIndex < length; rightIndex++, leftIndex++) { multiplyAccumulator = (right[rightIndex] & LONG_MASK) * unsignedMultiplier + multiplyAccumulator; subtractAccumulator = (subtractAccumulator + (left[leftIndex] & LONG_MASK)) - (lowInt(multiplyAccumulator) & LONG_MASK); multiplyAccumulator = (multiplyAccumulator >>> 32); left[leftIndex] = lowInt(subtractAccumulator); subtractAccumulator = (subtractAccumulator >>> 32) + INT_BASE - 1; } subtractAccumulator += (left[leftIndex] & LONG_MASK) - multiplyAccumulator; left[leftIndex] = lowInt(subtractAccumulator); return highInt(subtractAccumulator) == 0; }
[ "private", "static", "boolean", "multiplyAndSubtractUnsignedMultiPrecision", "(", "int", "[", "]", "left", ",", "int", "leftOffset", ",", "int", "[", "]", "right", ",", "int", "length", ",", "int", "multiplier", ")", "{", "long", "unsignedMultiplier", "=", "mu...
Calculate multi-precision [left - right * multiplier] with given left offset and length. Return true when overflow occurred
[ "Calculate", "multi", "-", "precision", "[", "left", "-", "right", "*", "multiplier", "]", "with", "given", "left", "offset", "and", "length", ".", "Return", "true", "when", "overflow", "occurred" ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-spi/src/main/java/com/facebook/presto/spi/type/UnscaledDecimal128Arithmetic.java#L1397-L1413
sirthias/parboiled
parboiled-core/src/main/java/org/parboiled/support/Filters.java
Filters.onlyMatches
public static Predicate<Tuple2<Context<?>, Boolean>> onlyMatches() { """ A predicate usable as a filter (element) of a {@link org.parboiled.parserunners.TracingParseRunner}. Enables printing of rule tracing log messages for all matched rules. @return a predicate """ return new Predicate<Tuple2<Context<?>, Boolean>>() { public boolean apply(Tuple2<Context<?>, Boolean> tuple) { return tuple.b; } }; }
java
public static Predicate<Tuple2<Context<?>, Boolean>> onlyMatches() { return new Predicate<Tuple2<Context<?>, Boolean>>() { public boolean apply(Tuple2<Context<?>, Boolean> tuple) { return tuple.b; } }; }
[ "public", "static", "Predicate", "<", "Tuple2", "<", "Context", "<", "?", ">", ",", "Boolean", ">", ">", "onlyMatches", "(", ")", "{", "return", "new", "Predicate", "<", "Tuple2", "<", "Context", "<", "?", ">", ",", "Boolean", ">", ">", "(", ")", "...
A predicate usable as a filter (element) of a {@link org.parboiled.parserunners.TracingParseRunner}. Enables printing of rule tracing log messages for all matched rules. @return a predicate
[ "A", "predicate", "usable", "as", "a", "filter", "(", "element", ")", "of", "a", "{", "@link", "org", ".", "parboiled", ".", "parserunners", ".", "TracingParseRunner", "}", ".", "Enables", "printing", "of", "rule", "tracing", "log", "messages", "for", "all...
train
https://github.com/sirthias/parboiled/blob/84f3ed43e3e171b4c6ab5e6ca6297d264a9d686a/parboiled-core/src/main/java/org/parboiled/support/Filters.java#L191-L197
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLNegativeObjectPropertyAssertionAxiomImpl_CustomFieldSerializer.java
OWLNegativeObjectPropertyAssertionAxiomImpl_CustomFieldSerializer.deserializeInstance
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLNegativeObjectPropertyAssertionAxiomImpl instance) throws SerializationException { """ Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful """ deserialize(streamReader, instance); }
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLNegativeObjectPropertyAssertionAxiomImpl instance) throws SerializationException { deserialize(streamReader, instance); }
[ "@", "Override", "public", "void", "deserializeInstance", "(", "SerializationStreamReader", "streamReader", ",", "OWLNegativeObjectPropertyAssertionAxiomImpl", "instance", ")", "throws", "SerializationException", "{", "deserialize", "(", "streamReader", ",", "instance", ")", ...
Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful
[ "Deserializes", "the", "content", "of", "the", "object", "from", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamReader", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLNegativeObjectPropertyAssertionAxiomImpl_CustomFieldSerializer.java#L100-L103
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/collection/ArrayUtils.java
ArrayUtils.concat
public static <T> void concat(T[] sourceFirst, T[] sourceSecond, T[] dest) { """ Copies in order {@code sourceFirst} and {@code sourceSecond} into {@code dest}. @param sourceFirst @param sourceSecond @param dest @param <T> """ System.arraycopy(sourceFirst, 0, dest, 0, sourceFirst.length); System.arraycopy(sourceSecond, 0, dest, sourceFirst.length, sourceSecond.length); }
java
public static <T> void concat(T[] sourceFirst, T[] sourceSecond, T[] dest) { System.arraycopy(sourceFirst, 0, dest, 0, sourceFirst.length); System.arraycopy(sourceSecond, 0, dest, sourceFirst.length, sourceSecond.length); }
[ "public", "static", "<", "T", ">", "void", "concat", "(", "T", "[", "]", "sourceFirst", ",", "T", "[", "]", "sourceSecond", ",", "T", "[", "]", "dest", ")", "{", "System", ".", "arraycopy", "(", "sourceFirst", ",", "0", ",", "dest", ",", "0", ","...
Copies in order {@code sourceFirst} and {@code sourceSecond} into {@code dest}. @param sourceFirst @param sourceSecond @param dest @param <T>
[ "Copies", "in", "order", "{", "@code", "sourceFirst", "}", "and", "{", "@code", "sourceSecond", "}", "into", "{", "@code", "dest", "}", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/collection/ArrayUtils.java#L172-L175
Erudika/para
para-client/src/main/java/com/erudika/para/client/ParaClient.java
ParaClient.revokeAllResourcePermissions
public Map<String, Map<String, List<String>>> revokeAllResourcePermissions(String subjectid) { """ Revokes all permission for a subject. @param subjectid subject id (user id) @return a map of the permissions for this subject id """ if (StringUtils.isBlank(subjectid)) { return Collections.emptyMap(); } return getEntity(invokeDelete(Utils.formatMessage("_permissions/{0}", subjectid), null), Map.class); }
java
public Map<String, Map<String, List<String>>> revokeAllResourcePermissions(String subjectid) { if (StringUtils.isBlank(subjectid)) { return Collections.emptyMap(); } return getEntity(invokeDelete(Utils.formatMessage("_permissions/{0}", subjectid), null), Map.class); }
[ "public", "Map", "<", "String", ",", "Map", "<", "String", ",", "List", "<", "String", ">", ">", ">", "revokeAllResourcePermissions", "(", "String", "subjectid", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "subjectid", ")", ")", "{", "return...
Revokes all permission for a subject. @param subjectid subject id (user id) @return a map of the permissions for this subject id
[ "Revokes", "all", "permission", "for", "a", "subject", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-client/src/main/java/com/erudika/para/client/ParaClient.java#L1477-L1482
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java
ByteUtils.memclr
public static void memclr( byte[] array, int offset, int length ) { """ Fill the given array with zeros. @param array the array to clear @param offset the start offset @param length the number of <code>byte</code>s to clear. """ for( int i = 0; i < length; ++i, ++offset ) array[offset] = 0; }
java
public static void memclr( byte[] array, int offset, int length ) { for( int i = 0; i < length; ++i, ++offset ) array[offset] = 0; }
[ "public", "static", "void", "memclr", "(", "byte", "[", "]", "array", ",", "int", "offset", ",", "int", "length", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "++", "i", ",", "++", "offset", ")", "array", "[", "offs...
Fill the given array with zeros. @param array the array to clear @param offset the start offset @param length the number of <code>byte</code>s to clear.
[ "Fill", "the", "given", "array", "with", "zeros", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java#L534-L537
SonarSource/sonarqube
sonar-core/src/main/java/org/sonar/core/util/Protobuf.java
Protobuf.readStream
public static <MSG extends Message> CloseableIterator<MSG> readStream(File file, Parser<MSG> parser) { """ Reads a stream of messages. This method returns an empty iterator if there are no messages. An exception is raised on IO error, if file does not exist or if messages have a different type than {@code parser}. """ try { // the input stream is closed by the CloseableIterator BufferedInputStream input = new BufferedInputStream(new FileInputStream(file)); return readStream(input, parser); } catch (Exception e) { throw ContextException.of("Unable to read messages", e).addContext("file", file); } }
java
public static <MSG extends Message> CloseableIterator<MSG> readStream(File file, Parser<MSG> parser) { try { // the input stream is closed by the CloseableIterator BufferedInputStream input = new BufferedInputStream(new FileInputStream(file)); return readStream(input, parser); } catch (Exception e) { throw ContextException.of("Unable to read messages", e).addContext("file", file); } }
[ "public", "static", "<", "MSG", "extends", "Message", ">", "CloseableIterator", "<", "MSG", ">", "readStream", "(", "File", "file", ",", "Parser", "<", "MSG", ">", "parser", ")", "{", "try", "{", "// the input stream is closed by the CloseableIterator", "BufferedI...
Reads a stream of messages. This method returns an empty iterator if there are no messages. An exception is raised on IO error, if file does not exist or if messages have a different type than {@code parser}.
[ "Reads", "a", "stream", "of", "messages", ".", "This", "method", "returns", "an", "empty", "iterator", "if", "there", "are", "no", "messages", ".", "An", "exception", "is", "raised", "on", "IO", "error", "if", "file", "does", "not", "exist", "or", "if", ...
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-core/src/main/java/org/sonar/core/util/Protobuf.java#L126-L134
knowm/Yank
src/main/java/org/knowm/yank/Yank.java
Yank.insertSQLKey
public static Long insertSQLKey(String sqlKey, Object[] params) throws SQLStatementNotFoundException, YankSQLException { """ Executes a given INSERT SQL prepared statement matching the sqlKey String in a properties file loaded via Yank.addSQLStatements(...) using the default connection pool. Returns the auto-increment id of the inserted row. @param sqlKey The SQL Key found in a properties file corresponding to the desired SQL statement value @param params The replacement parameters @return the auto-increment id of the inserted row, or null if no id is available @throws SQLStatementNotFoundException if an SQL statement could not be found for the given sqlKey String """ return insertSQLKey(YankPoolManager.DEFAULT_POOL_NAME, sqlKey, params); }
java
public static Long insertSQLKey(String sqlKey, Object[] params) throws SQLStatementNotFoundException, YankSQLException { return insertSQLKey(YankPoolManager.DEFAULT_POOL_NAME, sqlKey, params); }
[ "public", "static", "Long", "insertSQLKey", "(", "String", "sqlKey", ",", "Object", "[", "]", "params", ")", "throws", "SQLStatementNotFoundException", ",", "YankSQLException", "{", "return", "insertSQLKey", "(", "YankPoolManager", ".", "DEFAULT_POOL_NAME", ",", "sq...
Executes a given INSERT SQL prepared statement matching the sqlKey String in a properties file loaded via Yank.addSQLStatements(...) using the default connection pool. Returns the auto-increment id of the inserted row. @param sqlKey The SQL Key found in a properties file corresponding to the desired SQL statement value @param params The replacement parameters @return the auto-increment id of the inserted row, or null if no id is available @throws SQLStatementNotFoundException if an SQL statement could not be found for the given sqlKey String
[ "Executes", "a", "given", "INSERT", "SQL", "prepared", "statement", "matching", "the", "sqlKey", "String", "in", "a", "properties", "file", "loaded", "via", "Yank", ".", "addSQLStatements", "(", "...", ")", "using", "the", "default", "connection", "pool", ".",...
train
https://github.com/knowm/Yank/blob/b2071dcd94da99db6904355f9557456b8b292a6b/src/main/java/org/knowm/yank/Yank.java#L66-L70
EdwardRaff/JSAT
JSAT/src/jsat/utils/ListUtils.java
ListUtils.splitList
public static <T> List<List<T>> splitList(List<T> source, int count) { """ This method takes a list and breaks it into <tt>count</tt> lists backed by the original list, with elements being equally spaced among the lists. The lists will be returned in order of the consecutive values they represent in the source list. <br><br><b>NOTE</b>: Because the implementation uses {@link List#subList(int, int) }, changes to the returned lists will be reflected in the source list. @param <T> the type contained in the list @param source the source list that will be used to back the <tt>count</tt> lists @param count the number of lists to partition the source into. @return a lists of lists, each of with the same size with at most a difference of 1. """ if(count <= 0) throw new RuntimeException("Chunks must be greater then 0, not " + count); List<List<T>> chunks = new ArrayList<List<T>>(count); int baseSize = source.size() / count; int remainder = source.size() % count; int start = 0; for(int i = 0; i < count; i++) { int end = start+baseSize; if(remainder-- > 0) end++; chunks.add(source.subList(start, end)); start = end; } return chunks; }
java
public static <T> List<List<T>> splitList(List<T> source, int count) { if(count <= 0) throw new RuntimeException("Chunks must be greater then 0, not " + count); List<List<T>> chunks = new ArrayList<List<T>>(count); int baseSize = source.size() / count; int remainder = source.size() % count; int start = 0; for(int i = 0; i < count; i++) { int end = start+baseSize; if(remainder-- > 0) end++; chunks.add(source.subList(start, end)); start = end; } return chunks; }
[ "public", "static", "<", "T", ">", "List", "<", "List", "<", "T", ">", ">", "splitList", "(", "List", "<", "T", ">", "source", ",", "int", "count", ")", "{", "if", "(", "count", "<=", "0", ")", "throw", "new", "RuntimeException", "(", "\"Chunks mus...
This method takes a list and breaks it into <tt>count</tt> lists backed by the original list, with elements being equally spaced among the lists. The lists will be returned in order of the consecutive values they represent in the source list. <br><br><b>NOTE</b>: Because the implementation uses {@link List#subList(int, int) }, changes to the returned lists will be reflected in the source list. @param <T> the type contained in the list @param source the source list that will be used to back the <tt>count</tt> lists @param count the number of lists to partition the source into. @return a lists of lists, each of with the same size with at most a difference of 1.
[ "This", "method", "takes", "a", "list", "and", "breaks", "it", "into", "<tt", ">", "count<", "/", "tt", ">", "lists", "backed", "by", "the", "original", "list", "with", "elements", "being", "equally", "spaced", "among", "the", "lists", ".", "The", "lists...
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/utils/ListUtils.java#L37-L57
OpenLiberty/open-liberty
dev/com.ibm.ws.ssl/src/com/ibm/websphere/ssl/JSSEHelper.java
JSSEHelper.setInboundConnectionInfo
public void setInboundConnectionInfo(Map<String, Object> connectionInfo) { """ <p> This method sets information about the connection on the thread of execution. This connection information can then be used from Custom Key and Trust Managers. This method is invoked prior to an SSL handshake. </p> <p> It's important to clear the thread after use, especially where thread pools are used. It is not cleared up automatically. Pass in "null" to this API to clear it. </p> @param connectionInfo - This refers to the inbound connection information. @ibm-api """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "setInboundConnectionInfo", connectionInfo); ThreadManager.getInstance().setInboundConnectionInfo(connectionInfo); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "setInboundConnectionInfo"); }
java
public void setInboundConnectionInfo(Map<String, Object> connectionInfo) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "setInboundConnectionInfo", connectionInfo); ThreadManager.getInstance().setInboundConnectionInfo(connectionInfo); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "setInboundConnectionInfo"); }
[ "public", "void", "setInboundConnectionInfo", "(", "Map", "<", "String", ",", "Object", ">", "connectionInfo", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "entry", ...
<p> This method sets information about the connection on the thread of execution. This connection information can then be used from Custom Key and Trust Managers. This method is invoked prior to an SSL handshake. </p> <p> It's important to clear the thread after use, especially where thread pools are used. It is not cleared up automatically. Pass in "null" to this API to clear it. </p> @param connectionInfo - This refers to the inbound connection information. @ibm-api
[ "<p", ">", "This", "method", "sets", "information", "about", "the", "connection", "on", "the", "thread", "of", "execution", ".", "This", "connection", "information", "can", "then", "be", "used", "from", "Custom", "Key", "and", "Trust", "Managers", ".", "This...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ssl/src/com/ibm/websphere/ssl/JSSEHelper.java#L1296-L1302
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/RobotiumWebClient.java
RobotiumWebClient.enableJavascriptAndSetRobotiumWebClient
public void enableJavascriptAndSetRobotiumWebClient(List<WebView> webViews, WebChromeClient originalWebChromeClient) { """ Enables JavaScript in the given {@code WebViews} objects. @param webViews the {@code WebView} objects to enable JavaScript in """ this.originalWebChromeClient = originalWebChromeClient; for(final WebView webView : webViews){ if(webView != null){ inst.runOnMainSync(new Runnable() { public void run() { webView.getSettings().setJavaScriptEnabled(true); webView.setWebChromeClient(robotiumWebClient); } }); } } }
java
public void enableJavascriptAndSetRobotiumWebClient(List<WebView> webViews, WebChromeClient originalWebChromeClient){ this.originalWebChromeClient = originalWebChromeClient; for(final WebView webView : webViews){ if(webView != null){ inst.runOnMainSync(new Runnable() { public void run() { webView.getSettings().setJavaScriptEnabled(true); webView.setWebChromeClient(robotiumWebClient); } }); } } }
[ "public", "void", "enableJavascriptAndSetRobotiumWebClient", "(", "List", "<", "WebView", ">", "webViews", ",", "WebChromeClient", "originalWebChromeClient", ")", "{", "this", ".", "originalWebChromeClient", "=", "originalWebChromeClient", ";", "for", "(", "final", "Web...
Enables JavaScript in the given {@code WebViews} objects. @param webViews the {@code WebView} objects to enable JavaScript in
[ "Enables", "JavaScript", "in", "the", "given", "{", "@code", "WebViews", "}", "objects", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/RobotiumWebClient.java#L50-L62
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/query/CassQuery.java
CassQuery.setRelationalEntities
public void setRelationalEntities(List enhanceEntities, Client client, EntityMetadata m) { """ Sets the relational entities. @param enhanceEntities the enhance entities @param client the client @param m the m """ super.setRelationEntities(enhanceEntities, client, m); }
java
public void setRelationalEntities(List enhanceEntities, Client client, EntityMetadata m) { super.setRelationEntities(enhanceEntities, client, m); }
[ "public", "void", "setRelationalEntities", "(", "List", "enhanceEntities", ",", "Client", "client", ",", "EntityMetadata", "m", ")", "{", "super", ".", "setRelationEntities", "(", "enhanceEntities", ",", "client", ",", "m", ")", ";", "}" ]
Sets the relational entities. @param enhanceEntities the enhance entities @param client the client @param m the m
[ "Sets", "the", "relational", "entities", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/query/CassQuery.java#L1172-L1174
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java
FileUtil.readUtf8Lines
public static <T extends Collection<String>> T readUtf8Lines(URL url, T collection) throws IORuntimeException { """ 从文件中读取每一行数据,编码为UTF-8 @param <T> 集合类型 @param url 文件的URL @param collection 集合 @return 文件中的每行内容的集合 @throws IORuntimeException IO异常 """ return readLines(url, CharsetUtil.CHARSET_UTF_8, collection); }
java
public static <T extends Collection<String>> T readUtf8Lines(URL url, T collection) throws IORuntimeException { return readLines(url, CharsetUtil.CHARSET_UTF_8, collection); }
[ "public", "static", "<", "T", "extends", "Collection", "<", "String", ">", ">", "T", "readUtf8Lines", "(", "URL", "url", ",", "T", "collection", ")", "throws", "IORuntimeException", "{", "return", "readLines", "(", "url", ",", "CharsetUtil", ".", "CHARSET_UT...
从文件中读取每一行数据,编码为UTF-8 @param <T> 集合类型 @param url 文件的URL @param collection 集合 @return 文件中的每行内容的集合 @throws IORuntimeException IO异常
[ "从文件中读取每一行数据,编码为UTF", "-", "8" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L2247-L2249
haraldk/TwelveMonkeys
imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java
QuickDrawContext.eraseRoundRect
public void eraseRoundRect(final Rectangle2D pRectangle, int pArcW, int pArcH) { """ EraseRoundRect(r,int,int) // fills the rectangle's interior with the background pattern @param pRectangle the rectangle to erase @param pArcW width of the oval defining the rounded corner. @param pArcH height of the oval defining the rounded corner. """ eraseShape(toRoundRect(pRectangle, pArcW, pArcH)); }
java
public void eraseRoundRect(final Rectangle2D pRectangle, int pArcW, int pArcH) { eraseShape(toRoundRect(pRectangle, pArcW, pArcH)); }
[ "public", "void", "eraseRoundRect", "(", "final", "Rectangle2D", "pRectangle", ",", "int", "pArcW", ",", "int", "pArcH", ")", "{", "eraseShape", "(", "toRoundRect", "(", "pRectangle", ",", "pArcW", ",", "pArcH", ")", ")", ";", "}" ]
EraseRoundRect(r,int,int) // fills the rectangle's interior with the background pattern @param pRectangle the rectangle to erase @param pArcW width of the oval defining the rounded corner. @param pArcH height of the oval defining the rounded corner.
[ "EraseRoundRect", "(", "r", "int", "int", ")", "//", "fills", "the", "rectangle", "s", "interior", "with", "the", "background", "pattern" ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java#L631-L633
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/validation/SheetBindingErrors.java
SheetBindingErrors.createFieldConversionError
public InternalFieldErrorBuilder createFieldConversionError(final String field, final Class<?> fieldType, final Object rejectedValue) { """ 型変換失敗時のフィールエラー用のビルダを作成します。 @param field フィールドパス。 @param fieldType フィールドのクラスタイプ @param rejectedValue 型変換に失敗した値 @return {@link FieldError}のインスタンスを組み立てるビルダクラス。 """ final String fieldPath = buildFieldPath(field); final String[] codes = messageCodeGenerator.generateTypeMismatchCodes(getObjectName(), fieldPath, fieldType); return new InternalFieldErrorBuilder(this, getObjectName(), fieldPath, codes) .sheetName(getSheetName()) .rejectedValue(rejectedValue) .conversionFailure(true); }
java
public InternalFieldErrorBuilder createFieldConversionError(final String field, final Class<?> fieldType, final Object rejectedValue) { final String fieldPath = buildFieldPath(field); final String[] codes = messageCodeGenerator.generateTypeMismatchCodes(getObjectName(), fieldPath, fieldType); return new InternalFieldErrorBuilder(this, getObjectName(), fieldPath, codes) .sheetName(getSheetName()) .rejectedValue(rejectedValue) .conversionFailure(true); }
[ "public", "InternalFieldErrorBuilder", "createFieldConversionError", "(", "final", "String", "field", ",", "final", "Class", "<", "?", ">", "fieldType", ",", "final", "Object", "rejectedValue", ")", "{", "final", "String", "fieldPath", "=", "buildFieldPath", "(", ...
型変換失敗時のフィールエラー用のビルダを作成します。 @param field フィールドパス。 @param fieldType フィールドのクラスタイプ @param rejectedValue 型変換に失敗した値 @return {@link FieldError}のインスタンスを組み立てるビルダクラス。
[ "型変換失敗時のフィールエラー用のビルダを作成します。" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/validation/SheetBindingErrors.java#L643-L654
derari/cthul
objects/src/main/java/org/cthul/objects/Boxing.java
Boxing.deepUnbox
public static Object deepUnbox(Class<?> type, final Object src) { """ Returns any multidimensional array into an array of primitives. @param type target type @param src source array @return multidimensional array of primitives """ Class<?> compType = type.getComponentType(); if (compType.isArray()) { final Object[] src2 = (Object[]) src; final Object[] result = (Object[]) newArray(compType, src2.length); for (int i = 0; i < src2.length; i++) { result[i] = deepUnbox(compType, src2[i]); } return result; } else { return unboxAll(compType, src, 0, -1); } }
java
public static Object deepUnbox(Class<?> type, final Object src) { Class<?> compType = type.getComponentType(); if (compType.isArray()) { final Object[] src2 = (Object[]) src; final Object[] result = (Object[]) newArray(compType, src2.length); for (int i = 0; i < src2.length; i++) { result[i] = deepUnbox(compType, src2[i]); } return result; } else { return unboxAll(compType, src, 0, -1); } }
[ "public", "static", "Object", "deepUnbox", "(", "Class", "<", "?", ">", "type", ",", "final", "Object", "src", ")", "{", "Class", "<", "?", ">", "compType", "=", "type", ".", "getComponentType", "(", ")", ";", "if", "(", "compType", ".", "isArray", "...
Returns any multidimensional array into an array of primitives. @param type target type @param src source array @return multidimensional array of primitives
[ "Returns", "any", "multidimensional", "array", "into", "an", "array", "of", "primitives", "." ]
train
https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/objects/src/main/java/org/cthul/objects/Boxing.java#L683-L695
jboss/jboss-jsf-api_spec
src/main/java/javax/faces/event/MethodExpressionActionListener.java
MethodExpressionActionListener.restoreState
public void restoreState(FacesContext context, Object state) { """ <p class="changed_modified_2_0">Both {@link MethodExpression} instances described in the constructor must be restored.</p> """ if (context == null) { throw new NullPointerException(); } if (state == null) { return; } methodExpressionOneArg = (MethodExpression) ((Object[]) state)[0]; methodExpressionZeroArg = (MethodExpression) ((Object[]) state)[1]; }
java
public void restoreState(FacesContext context, Object state) { if (context == null) { throw new NullPointerException(); } if (state == null) { return; } methodExpressionOneArg = (MethodExpression) ((Object[]) state)[0]; methodExpressionZeroArg = (MethodExpression) ((Object[]) state)[1]; }
[ "public", "void", "restoreState", "(", "FacesContext", "context", ",", "Object", "state", ")", "{", "if", "(", "context", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "if", "(", "state", "==", "null", ")", "{", "r...
<p class="changed_modified_2_0">Both {@link MethodExpression} instances described in the constructor must be restored.</p>
[ "<p", "class", "=", "changed_modified_2_0", ">", "Both", "{" ]
train
https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/event/MethodExpressionActionListener.java#L182-L193
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/context/VmlGraphicsContext.java
VmlGraphicsContext.drawImage
public void drawImage(Object parent, String name, String href, Bbox bounds, PictureStyle style) { """ Draw an image onto the the <code>GraphicsContext</code>. @param parent parent group object @param name The image's name. @param href The image's location (URL). @param bounds The bounding box that sets the image's origin (x and y), it's width and it's height. @param style A styling object to be passed along with the image. Can be null. """ if (isAttached()) { Element image = helper.createOrUpdateElement(parent, name, "image", style); applyAbsolutePosition(image, bounds.getOrigin()); applyElementSize(image, (int) bounds.getWidth(), (int) bounds.getHeight(), true); Dom.setElementAttribute(image, "src", Dom.makeUrlAbsolute(href)); } }
java
public void drawImage(Object parent, String name, String href, Bbox bounds, PictureStyle style) { if (isAttached()) { Element image = helper.createOrUpdateElement(parent, name, "image", style); applyAbsolutePosition(image, bounds.getOrigin()); applyElementSize(image, (int) bounds.getWidth(), (int) bounds.getHeight(), true); Dom.setElementAttribute(image, "src", Dom.makeUrlAbsolute(href)); } }
[ "public", "void", "drawImage", "(", "Object", "parent", ",", "String", "name", ",", "String", "href", ",", "Bbox", "bounds", ",", "PictureStyle", "style", ")", "{", "if", "(", "isAttached", "(", ")", ")", "{", "Element", "image", "=", "helper", ".", "c...
Draw an image onto the the <code>GraphicsContext</code>. @param parent parent group object @param name The image's name. @param href The image's location (URL). @param bounds The bounding box that sets the image's origin (x and y), it's width and it's height. @param style A styling object to be passed along with the image. Can be null.
[ "Draw", "an", "image", "onto", "the", "the", "<code", ">", "GraphicsContext<", "/", "code", ">", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/VmlGraphicsContext.java#L266-L273
Samsung/GearVRf
GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java
JSONHelpers.optInt
public static <P extends Enum<P>> int optInt(final JSONObject json, P e) { """ Returns the value mapped to {@code e} if it exists and is an {@code int} or can be coerced to an {@code int}. Returns 0 otherwise. @param json {@link JSONObject} to get data from @param e {@link Enum} labeling the data to get """ return json.optInt(e.name()); }
java
public static <P extends Enum<P>> int optInt(final JSONObject json, P e) { return json.optInt(e.name()); }
[ "public", "static", "<", "P", "extends", "Enum", "<", "P", ">", ">", "int", "optInt", "(", "final", "JSONObject", "json", ",", "P", "e", ")", "{", "return", "json", ".", "optInt", "(", "e", ".", "name", "(", ")", ")", ";", "}" ]
Returns the value mapped to {@code e} if it exists and is an {@code int} or can be coerced to an {@code int}. Returns 0 otherwise. @param json {@link JSONObject} to get data from @param e {@link Enum} labeling the data to get
[ "Returns", "the", "value", "mapped", "to", "{", "@code", "e", "}", "if", "it", "exists", "and", "is", "an", "{", "@code", "int", "}", "or", "can", "be", "coerced", "to", "an", "{", "@code", "int", "}", ".", "Returns", "0", "otherwise", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java#L197-L199
rwl/CSparseJ
src/main/java/edu/emory/mathcs/csparsej/tfloat/Scs_sqr.java
Scs_sqr.cs_sqr
public static Scss cs_sqr(int order, Scs A, boolean qr) { """ Symbolic QR or LU ordering and analysis. @param order ordering method to use (0 to 3) @param A column-compressed matrix @param qr analyze for QR if true or LU if false @return symbolic analysis for QR or LU, null on error """ int n, k, post[]; Scss S; boolean ok = true; if (!Scs_util.CS_CSC(A)) return (null); /* check inputs */ n = A.n; S = new Scss(); /* allocate result S */ S.q = Scs_amd.cs_amd(order, A); /* fill-reducing ordering */ if (order > 0 && S.q == null) return (null); if (qr) /* QR symbolic analysis */ { Scs C = order > 0 ? Scs_permute.cs_permute(A, null, S.q, false) : A; S.parent = Scs_etree.cs_etree(C, true); /* etree of C'*C, where C=A(:,q) */ post = Scs_post.cs_post(S.parent, n); S.cp = Scs_counts.cs_counts(C, S.parent, post, true); /* col counts chol(C'*C) */ ok = C != null && S.parent != null && S.cp != null && cs_vcount(C, S); if (ok) for (S.unz = 0, k = 0; k < n; k++) S.unz += S.cp[k]; ok = ok && S.lnz >= 0 && S.unz >= 0; /* int overflow guard */ } else { S.unz = 4 * (A.p[n]) + n; /* for LU factorization only, */ S.lnz = S.unz; /* guess nnz(L) and nnz(U) */ } return (ok ? S : null); /* return result S */ }
java
public static Scss cs_sqr(int order, Scs A, boolean qr) { int n, k, post[]; Scss S; boolean ok = true; if (!Scs_util.CS_CSC(A)) return (null); /* check inputs */ n = A.n; S = new Scss(); /* allocate result S */ S.q = Scs_amd.cs_amd(order, A); /* fill-reducing ordering */ if (order > 0 && S.q == null) return (null); if (qr) /* QR symbolic analysis */ { Scs C = order > 0 ? Scs_permute.cs_permute(A, null, S.q, false) : A; S.parent = Scs_etree.cs_etree(C, true); /* etree of C'*C, where C=A(:,q) */ post = Scs_post.cs_post(S.parent, n); S.cp = Scs_counts.cs_counts(C, S.parent, post, true); /* col counts chol(C'*C) */ ok = C != null && S.parent != null && S.cp != null && cs_vcount(C, S); if (ok) for (S.unz = 0, k = 0; k < n; k++) S.unz += S.cp[k]; ok = ok && S.lnz >= 0 && S.unz >= 0; /* int overflow guard */ } else { S.unz = 4 * (A.p[n]) + n; /* for LU factorization only, */ S.lnz = S.unz; /* guess nnz(L) and nnz(U) */ } return (ok ? S : null); /* return result S */ }
[ "public", "static", "Scss", "cs_sqr", "(", "int", "order", ",", "Scs", "A", ",", "boolean", "qr", ")", "{", "int", "n", ",", "k", ",", "post", "[", "]", ";", "Scss", "S", ";", "boolean", "ok", "=", "true", ";", "if", "(", "!", "Scs_util", ".", ...
Symbolic QR or LU ordering and analysis. @param order ordering method to use (0 to 3) @param A column-compressed matrix @param qr analyze for QR if true or LU if false @return symbolic analysis for QR or LU, null on error
[ "Symbolic", "QR", "or", "LU", "ordering", "and", "analysis", "." ]
train
https://github.com/rwl/CSparseJ/blob/6a6f66bccce1558156a961494358952603b0ac84/src/main/java/edu/emory/mathcs/csparsej/tfloat/Scs_sqr.java#L113-L140
Sefford/fraggle
fraggle/src/main/java/com/sefford/fraggle/FraggleManager.java
FraggleManager.addFragment
public void addFragment(Fragment frag, String tag, FragmentAnimation animation, int flags, int containerId) { """ Adds a fragment to the activity content viewgroup. This will typically pass by a several stages, in this order: <ul> <li>Considering if the necessity of {@link com.sefford.fraggle.interfaces.FraggleFragment#isSingleInstance() adding another instance of such fragment class}</li> <li>{@link #processClearBackstack(int) Processing clearing backstack flags conditions}</li> <li>{@link #processAddToBackstackFlag(String, int, android.app.FragmentTransaction) Process adding to backstack flags conditions}</li> <li>{@link #processAnimations(FragmentAnimation, android.app.FragmentTransaction) Process the state of the deserved animations if any}</li> <li>{@link #performTransaction(android.app.Fragment, int, android.app.FragmentTransaction, int) Perform the actual transaction}</li> </ul> <p/> If the fragment is not required to be readded (as in a up navigation) the fragment manager will pop all the backstack until the desired fragment and the {@link com.sefford.fraggle.interfaces.FraggleFragment#onFragmentVisible() onFragmentVisible()} method will be called instead to bring up the dormant fragment. @param frag Fragment to add @param tag Fragment tag @param flags Adds flags to manipulate the state of the backstack @param containerId Container ID where to insert the fragment """ if (frag != null) { if ((!((FraggleFragment) frag).isSingleInstance()) || peek(tag) == null) { FragmentTransaction ft = fm.beginTransaction(); processClearBackstack(flags); processAddToBackstackFlag(tag, flags, ft); processAnimations(animation, ft); performTransaction(frag, flags, ft, containerId); } else { fm.popBackStack(tag, 0); if (frag.getArguments() != null && !frag.getArguments().equals(((Fragment) peek(tag)).getArguments())) { peek(tag).onNewArgumentsReceived(frag.getArguments()); } peek(tag).onFragmentVisible(); } } }
java
public void addFragment(Fragment frag, String tag, FragmentAnimation animation, int flags, int containerId) { if (frag != null) { if ((!((FraggleFragment) frag).isSingleInstance()) || peek(tag) == null) { FragmentTransaction ft = fm.beginTransaction(); processClearBackstack(flags); processAddToBackstackFlag(tag, flags, ft); processAnimations(animation, ft); performTransaction(frag, flags, ft, containerId); } else { fm.popBackStack(tag, 0); if (frag.getArguments() != null && !frag.getArguments().equals(((Fragment) peek(tag)).getArguments())) { peek(tag).onNewArgumentsReceived(frag.getArguments()); } peek(tag).onFragmentVisible(); } } }
[ "public", "void", "addFragment", "(", "Fragment", "frag", ",", "String", "tag", ",", "FragmentAnimation", "animation", ",", "int", "flags", ",", "int", "containerId", ")", "{", "if", "(", "frag", "!=", "null", ")", "{", "if", "(", "(", "!", "(", "(", ...
Adds a fragment to the activity content viewgroup. This will typically pass by a several stages, in this order: <ul> <li>Considering if the necessity of {@link com.sefford.fraggle.interfaces.FraggleFragment#isSingleInstance() adding another instance of such fragment class}</li> <li>{@link #processClearBackstack(int) Processing clearing backstack flags conditions}</li> <li>{@link #processAddToBackstackFlag(String, int, android.app.FragmentTransaction) Process adding to backstack flags conditions}</li> <li>{@link #processAnimations(FragmentAnimation, android.app.FragmentTransaction) Process the state of the deserved animations if any}</li> <li>{@link #performTransaction(android.app.Fragment, int, android.app.FragmentTransaction, int) Perform the actual transaction}</li> </ul> <p/> If the fragment is not required to be readded (as in a up navigation) the fragment manager will pop all the backstack until the desired fragment and the {@link com.sefford.fraggle.interfaces.FraggleFragment#onFragmentVisible() onFragmentVisible()} method will be called instead to bring up the dormant fragment. @param frag Fragment to add @param tag Fragment tag @param flags Adds flags to manipulate the state of the backstack @param containerId Container ID where to insert the fragment
[ "Adds", "a", "fragment", "to", "the", "activity", "content", "viewgroup", ".", "This", "will", "typically", "pass", "by", "a", "several", "stages", "in", "this", "order", ":", "<ul", ">", "<li", ">", "Considering", "if", "the", "necessity", "of", "{", "@...
train
https://github.com/Sefford/fraggle/blob/d1b65a99ecc3c3faeef8f288ca6225bbf475c3a3/fraggle/src/main/java/com/sefford/fraggle/FraggleManager.java#L158-L174
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/ContainerMetadataUpdateTransaction.java
ContainerMetadataUpdateTransaction.getOrCreateSegmentUpdateTransaction
private SegmentMetadataUpdateTransaction getOrCreateSegmentUpdateTransaction(String segmentName, long segmentId) { """ Gets an UpdateableSegmentMetadata for the given Segment. If already registered, it returns that instance, otherwise it creates and records a new Segment metadata. """ SegmentMetadataUpdateTransaction sm = tryGetSegmentUpdateTransaction(segmentId); if (sm == null) { SegmentMetadata baseSegmentMetadata = createSegmentMetadata(segmentName, segmentId); sm = new SegmentMetadataUpdateTransaction(baseSegmentMetadata, this.recoveryMode); this.segmentUpdates.put(segmentId, sm); } return sm; }
java
private SegmentMetadataUpdateTransaction getOrCreateSegmentUpdateTransaction(String segmentName, long segmentId) { SegmentMetadataUpdateTransaction sm = tryGetSegmentUpdateTransaction(segmentId); if (sm == null) { SegmentMetadata baseSegmentMetadata = createSegmentMetadata(segmentName, segmentId); sm = new SegmentMetadataUpdateTransaction(baseSegmentMetadata, this.recoveryMode); this.segmentUpdates.put(segmentId, sm); } return sm; }
[ "private", "SegmentMetadataUpdateTransaction", "getOrCreateSegmentUpdateTransaction", "(", "String", "segmentName", ",", "long", "segmentId", ")", "{", "SegmentMetadataUpdateTransaction", "sm", "=", "tryGetSegmentUpdateTransaction", "(", "segmentId", ")", ";", "if", "(", "s...
Gets an UpdateableSegmentMetadata for the given Segment. If already registered, it returns that instance, otherwise it creates and records a new Segment metadata.
[ "Gets", "an", "UpdateableSegmentMetadata", "for", "the", "given", "Segment", ".", "If", "already", "registered", "it", "returns", "that", "instance", "otherwise", "it", "creates", "and", "records", "a", "new", "Segment", "metadata", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/ContainerMetadataUpdateTransaction.java#L525-L534
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CProductPersistenceImpl.java
CProductPersistenceImpl.findAll
@Override public List<CProduct> findAll(int start, int end) { """ Returns a range of all the c products. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CProductModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of c products @param end the upper bound of the range of c products (not inclusive) @return the range of c products """ return findAll(start, end, null); }
java
@Override public List<CProduct> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CProduct", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the c products. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CProductModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of c products @param end the upper bound of the range of c products (not inclusive) @return the range of c products
[ "Returns", "a", "range", "of", "all", "the", "c", "products", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CProductPersistenceImpl.java#L2594-L2597
OpenLiberty/open-liberty
dev/com.ibm.ws.concurrent/src/com/ibm/ws/concurrent/internal/ManagedExecutorServiceImpl.java
ManagedExecutorServiceImpl.createCallbacks
@SuppressWarnings("unchecked") private <T> Entry<Collection<? extends Callable<T>>, TaskLifeCycleCallback[]> createCallbacks(Collection<? extends Callable<T>> tasks) { """ Capture context for a list of tasks and create callbacks that apply context and notify the ManagedTaskListener, if any. Context is not re-captured for any tasks that implement the ContextualAction marker interface. @param tasks collection of tasks. @return entry consisting of a possibly modified copy of the task list (the key) and the list of callbacks (the value). """ int numTasks = tasks.size(); TaskLifeCycleCallback[] callbacks = new TaskLifeCycleCallback[numTasks]; List<Callable<T>> taskUpdates = null; if (numTasks == 1) { Callable<T> task = tasks.iterator().next(); ThreadContextDescriptor contextDescriptor; if (task instanceof ContextualAction) { ContextualAction<Callable<T>> a = (ContextualAction<Callable<T>>) task; contextDescriptor = a.getContextDescriptor(); task = a.getAction(); taskUpdates = Arrays.asList(task); } else { contextDescriptor = getContextService().captureThreadContext(getExecutionProperties(task)); } callbacks[0] = new TaskLifeCycleCallback(this, contextDescriptor); } else { // Thread context capture is expensive, so reuse callbacks when execution properties match Map<Map<String, String>, TaskLifeCycleCallback> execPropsToCallback = new HashMap<Map<String, String>, TaskLifeCycleCallback>(); WSContextService contextSvc = null; int t = 0; for (Callable<T> task : tasks) { if (task instanceof ContextualAction) { ContextualAction<Callable<T>> a = (ContextualAction<Callable<T>>) task; taskUpdates = taskUpdates == null ? new ArrayList<Callable<T>>(tasks) : taskUpdates; taskUpdates.set(t, a.getAction()); callbacks[t++] = new TaskLifeCycleCallback(this, a.getContextDescriptor()); } else { Map<String, String> execProps = getExecutionProperties(task); TaskLifeCycleCallback callback = execPropsToCallback.get(execProps); if (callback == null) { contextSvc = contextSvc == null ? getContextService() : contextSvc; execPropsToCallback.put(execProps, callback = new TaskLifeCycleCallback(this, contextSvc.captureThreadContext(execProps))); } callbacks[t++] = callback; } } } return new SimpleEntry<Collection<? extends Callable<T>>, TaskLifeCycleCallback[]>(taskUpdates == null ? tasks : taskUpdates, callbacks); }
java
@SuppressWarnings("unchecked") private <T> Entry<Collection<? extends Callable<T>>, TaskLifeCycleCallback[]> createCallbacks(Collection<? extends Callable<T>> tasks) { int numTasks = tasks.size(); TaskLifeCycleCallback[] callbacks = new TaskLifeCycleCallback[numTasks]; List<Callable<T>> taskUpdates = null; if (numTasks == 1) { Callable<T> task = tasks.iterator().next(); ThreadContextDescriptor contextDescriptor; if (task instanceof ContextualAction) { ContextualAction<Callable<T>> a = (ContextualAction<Callable<T>>) task; contextDescriptor = a.getContextDescriptor(); task = a.getAction(); taskUpdates = Arrays.asList(task); } else { contextDescriptor = getContextService().captureThreadContext(getExecutionProperties(task)); } callbacks[0] = new TaskLifeCycleCallback(this, contextDescriptor); } else { // Thread context capture is expensive, so reuse callbacks when execution properties match Map<Map<String, String>, TaskLifeCycleCallback> execPropsToCallback = new HashMap<Map<String, String>, TaskLifeCycleCallback>(); WSContextService contextSvc = null; int t = 0; for (Callable<T> task : tasks) { if (task instanceof ContextualAction) { ContextualAction<Callable<T>> a = (ContextualAction<Callable<T>>) task; taskUpdates = taskUpdates == null ? new ArrayList<Callable<T>>(tasks) : taskUpdates; taskUpdates.set(t, a.getAction()); callbacks[t++] = new TaskLifeCycleCallback(this, a.getContextDescriptor()); } else { Map<String, String> execProps = getExecutionProperties(task); TaskLifeCycleCallback callback = execPropsToCallback.get(execProps); if (callback == null) { contextSvc = contextSvc == null ? getContextService() : contextSvc; execPropsToCallback.put(execProps, callback = new TaskLifeCycleCallback(this, contextSvc.captureThreadContext(execProps))); } callbacks[t++] = callback; } } } return new SimpleEntry<Collection<? extends Callable<T>>, TaskLifeCycleCallback[]>(taskUpdates == null ? tasks : taskUpdates, callbacks); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "<", "T", ">", "Entry", "<", "Collection", "<", "?", "extends", "Callable", "<", "T", ">", ">", ",", "TaskLifeCycleCallback", "[", "]", ">", "createCallbacks", "(", "Collection", "<", "?", "ext...
Capture context for a list of tasks and create callbacks that apply context and notify the ManagedTaskListener, if any. Context is not re-captured for any tasks that implement the ContextualAction marker interface. @param tasks collection of tasks. @return entry consisting of a possibly modified copy of the task list (the key) and the list of callbacks (the value).
[ "Capture", "context", "for", "a", "list", "of", "tasks", "and", "create", "callbacks", "that", "apply", "context", "and", "notify", "the", "ManagedTaskListener", "if", "any", ".", "Context", "is", "not", "re", "-", "captured", "for", "any", "tasks", "that", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.concurrent/src/com/ibm/ws/concurrent/internal/ManagedExecutorServiceImpl.java#L276-L320
ronmamo/reflections
src/main/java/org/reflections/vfs/Vfs.java
Vfs.fromURL
public static Dir fromURL(final URL url, final List<UrlType> urlTypes) { """ tries to create a Dir from the given url, using the given urlTypes """ for (UrlType type : urlTypes) { try { if (type.matches(url)) { Dir dir = type.createDir(url); if (dir != null) return dir; } } catch (Throwable e) { if (Reflections.log != null) { Reflections.log.warn("could not create Dir using " + type + " from url " + url.toExternalForm() + ". skipping.", e); } } } throw new ReflectionsException("could not create Vfs.Dir from url, no matching UrlType was found [" + url.toExternalForm() + "]\n" + "either use fromURL(final URL url, final List<UrlType> urlTypes) or " + "use the static setDefaultURLTypes(final List<UrlType> urlTypes) or addDefaultURLTypes(UrlType urlType) " + "with your specialized UrlType."); }
java
public static Dir fromURL(final URL url, final List<UrlType> urlTypes) { for (UrlType type : urlTypes) { try { if (type.matches(url)) { Dir dir = type.createDir(url); if (dir != null) return dir; } } catch (Throwable e) { if (Reflections.log != null) { Reflections.log.warn("could not create Dir using " + type + " from url " + url.toExternalForm() + ". skipping.", e); } } } throw new ReflectionsException("could not create Vfs.Dir from url, no matching UrlType was found [" + url.toExternalForm() + "]\n" + "either use fromURL(final URL url, final List<UrlType> urlTypes) or " + "use the static setDefaultURLTypes(final List<UrlType> urlTypes) or addDefaultURLTypes(UrlType urlType) " + "with your specialized UrlType."); }
[ "public", "static", "Dir", "fromURL", "(", "final", "URL", "url", ",", "final", "List", "<", "UrlType", ">", "urlTypes", ")", "{", "for", "(", "UrlType", "type", ":", "urlTypes", ")", "{", "try", "{", "if", "(", "type", ".", "matches", "(", "url", ...
tries to create a Dir from the given url, using the given urlTypes
[ "tries", "to", "create", "a", "Dir", "from", "the", "given", "url", "using", "the", "given", "urlTypes" ]
train
https://github.com/ronmamo/reflections/blob/084cf4a759a06d88e88753ac00397478c2e0ed52/src/main/java/org/reflections/vfs/Vfs.java#L97-L115
Netflix/ribbon
ribbon-loadbalancer/src/main/java/com/netflix/client/ClientFactory.java
ClientFactory.createNamedClient
public static synchronized IClient createNamedClient(String name, Class<? extends IClientConfig> configClass) throws ClientException { """ Creates a named client using a IClientConfig instance created off the configClass class object passed in as the parameter. @throws ClientException if any error occurs, or if the client with the same name already exists """ IClientConfig config = getNamedConfig(name, configClass); return registerClientFromProperties(name, config); }
java
public static synchronized IClient createNamedClient(String name, Class<? extends IClientConfig> configClass) throws ClientException { IClientConfig config = getNamedConfig(name, configClass); return registerClientFromProperties(name, config); }
[ "public", "static", "synchronized", "IClient", "createNamedClient", "(", "String", "name", ",", "Class", "<", "?", "extends", "IClientConfig", ">", "configClass", ")", "throws", "ClientException", "{", "IClientConfig", "config", "=", "getNamedConfig", "(", "name", ...
Creates a named client using a IClientConfig instance created off the configClass class object passed in as the parameter. @throws ClientException if any error occurs, or if the client with the same name already exists
[ "Creates", "a", "named", "client", "using", "a", "IClientConfig", "instance", "created", "off", "the", "configClass", "class", "object", "passed", "in", "as", "the", "parameter", "." ]
train
https://github.com/Netflix/ribbon/blob/d15cd7715b0bf2f64ae6ca98c5e4d184f178e261/ribbon-loadbalancer/src/main/java/com/netflix/client/ClientFactory.java#L127-L130
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/base64/Base64.java
Base64.safeDecode
@Nullable @ReturnsMutableCopy public static byte [] safeDecode (@Nullable final byte [] aEncodedBytes, @Nonnegative final int nOfs, @Nonnegative final int nLen) { """ Decode the byte array. @param aEncodedBytes The encoded byte array. @param nOfs The offset of where to begin decoding @param nLen The number of characters to decode @return <code>null</code> if decoding failed. """ return safeDecode (aEncodedBytes, nOfs, nLen, DONT_GUNZIP); }
java
@Nullable @ReturnsMutableCopy public static byte [] safeDecode (@Nullable final byte [] aEncodedBytes, @Nonnegative final int nOfs, @Nonnegative final int nLen) { return safeDecode (aEncodedBytes, nOfs, nLen, DONT_GUNZIP); }
[ "@", "Nullable", "@", "ReturnsMutableCopy", "public", "static", "byte", "[", "]", "safeDecode", "(", "@", "Nullable", "final", "byte", "[", "]", "aEncodedBytes", ",", "@", "Nonnegative", "final", "int", "nOfs", ",", "@", "Nonnegative", "final", "int", "nLen"...
Decode the byte array. @param aEncodedBytes The encoded byte array. @param nOfs The offset of where to begin decoding @param nLen The number of characters to decode @return <code>null</code> if decoding failed.
[ "Decode", "the", "byte", "array", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/base64/Base64.java#L2614-L2621
Samsung/GearVRf
GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/Widget.java
Widget.addChild
protected boolean addChild(final Widget child, final GVRSceneObject childRootSceneObject, final int index) { """ Add another {@link Widget} as a child of this one. Convenience method for {@link #addChild(Widget, GVRSceneObject, int, boolean) addChild(child, childRootSceneObject, index, false)}. @param child The {@code Widget} to add as a child. @param childRootSceneObject The root {@link GVRSceneObject} of the child. @param index Position at which to add the child. Pass -1 to add at end. @return {@code True} if {@code child} was added; {@code false} if {@code child} was previously added to this instance. """ return addChild(child, childRootSceneObject, index, false); }
java
protected boolean addChild(final Widget child, final GVRSceneObject childRootSceneObject, final int index) { return addChild(child, childRootSceneObject, index, false); }
[ "protected", "boolean", "addChild", "(", "final", "Widget", "child", ",", "final", "GVRSceneObject", "childRootSceneObject", ",", "final", "int", "index", ")", "{", "return", "addChild", "(", "child", ",", "childRootSceneObject", ",", "index", ",", "false", ")",...
Add another {@link Widget} as a child of this one. Convenience method for {@link #addChild(Widget, GVRSceneObject, int, boolean) addChild(child, childRootSceneObject, index, false)}. @param child The {@code Widget} to add as a child. @param childRootSceneObject The root {@link GVRSceneObject} of the child. @param index Position at which to add the child. Pass -1 to add at end. @return {@code True} if {@code child} was added; {@code false} if {@code child} was previously added to this instance.
[ "Add", "another", "{", "@link", "Widget", "}", "as", "a", "child", "of", "this", "one", ".", "Convenience", "method", "for", "{", "@link", "#addChild", "(", "Widget", "GVRSceneObject", "int", "boolean", ")", "addChild", "(", "child", "childRootSceneObject", ...
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/Widget.java#L2954-L2957
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/schema/SchemaService.java
SchemaService.initializeApplication
private void initializeApplication(ApplicationDefinition currAppDef, ApplicationDefinition appDef) { """ Initialize storage and store the given schema for the given new or updated application. """ getStorageService(appDef).initializeApplication(currAppDef, appDef); storeApplicationSchema(appDef); }
java
private void initializeApplication(ApplicationDefinition currAppDef, ApplicationDefinition appDef) { getStorageService(appDef).initializeApplication(currAppDef, appDef); storeApplicationSchema(appDef); }
[ "private", "void", "initializeApplication", "(", "ApplicationDefinition", "currAppDef", ",", "ApplicationDefinition", "appDef", ")", "{", "getStorageService", "(", "appDef", ")", ".", "initializeApplication", "(", "currAppDef", ",", "appDef", ")", ";", "storeApplication...
Initialize storage and store the given schema for the given new or updated application.
[ "Initialize", "storage", "and", "store", "the", "given", "schema", "for", "the", "given", "new", "or", "updated", "application", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/schema/SchemaService.java#L336-L339
lessthanoptimal/ddogleg
src/org/ddogleg/optimization/trustregion/TrustRegionUpdateDogleg_F64.java
TrustRegionUpdateDogleg_F64.cauchyStep
protected void cauchyStep(double regionRadius, DMatrixRMaj step) { """ Computes the Cauchy step, This is only called if the Cauchy point lies after or on the trust region @param regionRadius (Input) Trust region size @param step (Output) The step """ CommonOps_DDRM.scale(-regionRadius, direction, step); stepLength = regionRadius; // it touches the trust region predictedReduction = regionRadius*(owner.gradientNorm - 0.5*regionRadius*gBg); }
java
protected void cauchyStep(double regionRadius, DMatrixRMaj step) { CommonOps_DDRM.scale(-regionRadius, direction, step); stepLength = regionRadius; // it touches the trust region predictedReduction = regionRadius*(owner.gradientNorm - 0.5*regionRadius*gBg); }
[ "protected", "void", "cauchyStep", "(", "double", "regionRadius", ",", "DMatrixRMaj", "step", ")", "{", "CommonOps_DDRM", ".", "scale", "(", "-", "regionRadius", ",", "direction", ",", "step", ")", ";", "stepLength", "=", "regionRadius", ";", "// it touches the ...
Computes the Cauchy step, This is only called if the Cauchy point lies after or on the trust region @param regionRadius (Input) Trust region size @param step (Output) The step
[ "Computes", "the", "Cauchy", "step", "This", "is", "only", "called", "if", "the", "Cauchy", "point", "lies", "after", "or", "on", "the", "trust", "region" ]
train
https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/optimization/trustregion/TrustRegionUpdateDogleg_F64.java#L184-L189
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.createImagesFromPredictionsAsync
public Observable<ImageCreateSummary> createImagesFromPredictionsAsync(UUID projectId, ImageIdCreateBatch batch) { """ Add the specified predicted images to the set of training images. This API creates a batch of images from predicted images specified. There is a limit of 64 images and 20 tags. @param projectId The project id @param batch Image and tag ids. Limted to 64 images and 20 tags per batch @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ImageCreateSummary object """ return createImagesFromPredictionsWithServiceResponseAsync(projectId, batch).map(new Func1<ServiceResponse<ImageCreateSummary>, ImageCreateSummary>() { @Override public ImageCreateSummary call(ServiceResponse<ImageCreateSummary> response) { return response.body(); } }); }
java
public Observable<ImageCreateSummary> createImagesFromPredictionsAsync(UUID projectId, ImageIdCreateBatch batch) { return createImagesFromPredictionsWithServiceResponseAsync(projectId, batch).map(new Func1<ServiceResponse<ImageCreateSummary>, ImageCreateSummary>() { @Override public ImageCreateSummary call(ServiceResponse<ImageCreateSummary> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ImageCreateSummary", ">", "createImagesFromPredictionsAsync", "(", "UUID", "projectId", ",", "ImageIdCreateBatch", "batch", ")", "{", "return", "createImagesFromPredictionsWithServiceResponseAsync", "(", "projectId", ",", "batch", ")", ".", "...
Add the specified predicted images to the set of training images. This API creates a batch of images from predicted images specified. There is a limit of 64 images and 20 tags. @param projectId The project id @param batch Image and tag ids. Limted to 64 images and 20 tags per batch @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ImageCreateSummary object
[ "Add", "the", "specified", "predicted", "images", "to", "the", "set", "of", "training", "images", ".", "This", "API", "creates", "a", "batch", "of", "images", "from", "predicted", "images", "specified", ".", "There", "is", "a", "limit", "of", "64", "images...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L3779-L3786
googleapis/google-cloud-java
google-cloud-clients/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2beta1/IntentsClient.java
IntentsClient.updateIntent
public final Intent updateIntent(Intent intent, String languageCode) { """ Updates the specified intent. <p>Sample code: <pre><code> try (IntentsClient intentsClient = IntentsClient.create()) { Intent intent = Intent.newBuilder().build(); String languageCode = ""; Intent response = intentsClient.updateIntent(intent, languageCode); } </code></pre> @param intent Required. The intent to update. @param languageCode Optional. The language of training phrases, parameters and rich messages defined in `intent`. If not specified, the agent's default language is used. [Many languages](https://cloud.google.com/dialogflow-enterprise/docs/reference/language) are supported. Note: languages must be enabled in the agent before they can be used. @throws com.google.api.gax.rpc.ApiException if the remote call fails """ UpdateIntentRequest request = UpdateIntentRequest.newBuilder().setIntent(intent).setLanguageCode(languageCode).build(); return updateIntent(request); }
java
public final Intent updateIntent(Intent intent, String languageCode) { UpdateIntentRequest request = UpdateIntentRequest.newBuilder().setIntent(intent).setLanguageCode(languageCode).build(); return updateIntent(request); }
[ "public", "final", "Intent", "updateIntent", "(", "Intent", "intent", ",", "String", "languageCode", ")", "{", "UpdateIntentRequest", "request", "=", "UpdateIntentRequest", ".", "newBuilder", "(", ")", ".", "setIntent", "(", "intent", ")", ".", "setLanguageCode", ...
Updates the specified intent. <p>Sample code: <pre><code> try (IntentsClient intentsClient = IntentsClient.create()) { Intent intent = Intent.newBuilder().build(); String languageCode = ""; Intent response = intentsClient.updateIntent(intent, languageCode); } </code></pre> @param intent Required. The intent to update. @param languageCode Optional. The language of training phrases, parameters and rich messages defined in `intent`. If not specified, the agent's default language is used. [Many languages](https://cloud.google.com/dialogflow-enterprise/docs/reference/language) are supported. Note: languages must be enabled in the agent before they can be used. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Updates", "the", "specified", "intent", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2beta1/IntentsClient.java#L743-L748
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/xml/importing/BaseXmlImporter.java
BaseXmlImporter.checkReferenceable
protected void checkReferenceable(ImportNodeData currentNodeInfo, String olUuid) throws RepositoryException { """ Check uuid collision. If collision happen reload path information. @param currentNodeInfo @param olUuid @throws RepositoryException """ // if node is in version storage - do not assign new id from jcr:uuid // property if (Constants.JCR_VERSION_STORAGE_PATH.getDepth() + 3 <= currentNodeInfo.getQPath().getDepth() && currentNodeInfo.getQPath().getEntries()[Constants.JCR_VERSION_STORAGE_PATH.getDepth() + 3] .equals(Constants.JCR_FROZENNODE) && currentNodeInfo.getQPath().isDescendantOf(Constants.JCR_VERSION_STORAGE_PATH)) { return; } String identifier = validateUuidCollision(olUuid); if (identifier != null) { reloadChangesInfoAfterUC(currentNodeInfo, identifier); } else { currentNodeInfo.setIsNewIdentifer(true); } if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING) { NodeData parentNode = getParent(); currentNodeInfo.setParentIdentifer(parentNode.getIdentifier()); if (parentNode instanceof ImportNodeData && ((ImportNodeData)parentNode).isTemporary()) { // remove the temporary parent tree.pop(); } } }
java
protected void checkReferenceable(ImportNodeData currentNodeInfo, String olUuid) throws RepositoryException { // if node is in version storage - do not assign new id from jcr:uuid // property if (Constants.JCR_VERSION_STORAGE_PATH.getDepth() + 3 <= currentNodeInfo.getQPath().getDepth() && currentNodeInfo.getQPath().getEntries()[Constants.JCR_VERSION_STORAGE_PATH.getDepth() + 3] .equals(Constants.JCR_FROZENNODE) && currentNodeInfo.getQPath().isDescendantOf(Constants.JCR_VERSION_STORAGE_PATH)) { return; } String identifier = validateUuidCollision(olUuid); if (identifier != null) { reloadChangesInfoAfterUC(currentNodeInfo, identifier); } else { currentNodeInfo.setIsNewIdentifer(true); } if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING) { NodeData parentNode = getParent(); currentNodeInfo.setParentIdentifer(parentNode.getIdentifier()); if (parentNode instanceof ImportNodeData && ((ImportNodeData)parentNode).isTemporary()) { // remove the temporary parent tree.pop(); } } }
[ "protected", "void", "checkReferenceable", "(", "ImportNodeData", "currentNodeInfo", ",", "String", "olUuid", ")", "throws", "RepositoryException", "{", "// if node is in version storage - do not assign new id from jcr:uuid", "// property", "if", "(", "Constants", ".", "JCR_VER...
Check uuid collision. If collision happen reload path information. @param currentNodeInfo @param olUuid @throws RepositoryException
[ "Check", "uuid", "collision", ".", "If", "collision", "happen", "reload", "path", "information", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/xml/importing/BaseXmlImporter.java#L400-L432
marklogic/marklogic-sesame
marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/TripleCache.java
TripleCache.forceRun
public synchronized void forceRun() throws MarkLogicSesameException { """ min forces the cache to flush if there is anything in it @throws MarkLogicSesameException """ log.debug(String.valueOf(cache.size())); if( !cache.isEmpty()) { try { flush(); } catch (RepositoryException e) { throw new MarkLogicSesameException("Could not flush write cache, encountered repository issue.",e); } catch (MalformedQueryException e) { throw new MarkLogicSesameException("Could not flush write cache, query was malformed.",e); } catch (UpdateExecutionException e) { throw new MarkLogicSesameException("Could not flush write cache, query update failed.",e); } catch (IOException e) { throw new MarkLogicSesameException("Could not flush write cache, encountered IO issue.",e); } } }
java
public synchronized void forceRun() throws MarkLogicSesameException { log.debug(String.valueOf(cache.size())); if( !cache.isEmpty()) { try { flush(); } catch (RepositoryException e) { throw new MarkLogicSesameException("Could not flush write cache, encountered repository issue.",e); } catch (MalformedQueryException e) { throw new MarkLogicSesameException("Could not flush write cache, query was malformed.",e); } catch (UpdateExecutionException e) { throw new MarkLogicSesameException("Could not flush write cache, query update failed.",e); } catch (IOException e) { throw new MarkLogicSesameException("Could not flush write cache, encountered IO issue.",e); } } }
[ "public", "synchronized", "void", "forceRun", "(", ")", "throws", "MarkLogicSesameException", "{", "log", ".", "debug", "(", "String", ".", "valueOf", "(", "cache", ".", "size", "(", ")", ")", ")", ";", "if", "(", "!", "cache", ".", "isEmpty", "(", ")"...
min forces the cache to flush if there is anything in it @throws MarkLogicSesameException
[ "min", "forces", "the", "cache", "to", "flush", "if", "there", "is", "anything", "in", "it" ]
train
https://github.com/marklogic/marklogic-sesame/blob/d5b668ed2b3d5e90c9f1d5096012813c272062a2/marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/TripleCache.java#L160-L175
dyu/protostuff-1.0.x
protostuff-benchmark/src/main/java/com/google/protobuf/JsonFormat.java
JsonFormat.print
public static void print(UnknownFieldSet fields, Appendable output) throws IOException { """ Outputs a textual representation of {@code fields} to {@code output}. """ JsonGenerator generator = new JsonGenerator(output); generator.print("{"); printUnknownFields(fields, generator); generator.print("}"); }
java
public static void print(UnknownFieldSet fields, Appendable output) throws IOException { JsonGenerator generator = new JsonGenerator(output); generator.print("{"); printUnknownFields(fields, generator); generator.print("}"); }
[ "public", "static", "void", "print", "(", "UnknownFieldSet", "fields", ",", "Appendable", "output", ")", "throws", "IOException", "{", "JsonGenerator", "generator", "=", "new", "JsonGenerator", "(", "output", ")", ";", "generator", ".", "print", "(", "\"{\"", ...
Outputs a textual representation of {@code fields} to {@code output}.
[ "Outputs", "a", "textual", "representation", "of", "{" ]
train
https://github.com/dyu/protostuff-1.0.x/blob/d7c964ec20da3fe44699d86ee95c2677ddffde96/protostuff-benchmark/src/main/java/com/google/protobuf/JsonFormat.java#L81-L86
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java
TheMovieDbApi.createImageUrl
public URL createImageUrl(String imagePath, String requiredSize) throws MovieDbException { """ Generate the full image URL from the size and image path @param imagePath imagePath @param requiredSize requiredSize @return @throws MovieDbException exception """ return tmdbConfiguration.getConfig().createImageUrl(imagePath, requiredSize); }
java
public URL createImageUrl(String imagePath, String requiredSize) throws MovieDbException { return tmdbConfiguration.getConfig().createImageUrl(imagePath, requiredSize); }
[ "public", "URL", "createImageUrl", "(", "String", "imagePath", ",", "String", "requiredSize", ")", "throws", "MovieDbException", "{", "return", "tmdbConfiguration", ".", "getConfig", "(", ")", ".", "createImageUrl", "(", "imagePath", ",", "requiredSize", ")", ";",...
Generate the full image URL from the size and image path @param imagePath imagePath @param requiredSize requiredSize @return @throws MovieDbException exception
[ "Generate", "the", "full", "image", "URL", "from", "the", "size", "and", "image", "path" ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java#L578-L580
jbundle/jbundle
base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/HScreenField.java
HScreenField.printInputControl
public void printInputControl(PrintWriter out, String strFieldDesc, String strFieldName, String strSize, String strMaxSize, String strValue, String strControlType, int iHtmlAttributes) { """ Display this field in html input format. @param out The html out stream. @param strFieldDesc The field description. @param strFieldName The field name. @param strSize The control size. @param strMaxSize The string max size. @param strValue The default value. @param strControlType The control type. @param iHtmlAttribures The attributes. """ out.println("<td><input type=\"" + strControlType + "\" name=\"" + strFieldName + "\" size=\"" + strSize + "\" maxlength=\"" + strMaxSize + "\" value=\"" + strValue + "\"/></td>"); }
java
public void printInputControl(PrintWriter out, String strFieldDesc, String strFieldName, String strSize, String strMaxSize, String strValue, String strControlType, int iHtmlAttributes) { out.println("<td><input type=\"" + strControlType + "\" name=\"" + strFieldName + "\" size=\"" + strSize + "\" maxlength=\"" + strMaxSize + "\" value=\"" + strValue + "\"/></td>"); }
[ "public", "void", "printInputControl", "(", "PrintWriter", "out", ",", "String", "strFieldDesc", ",", "String", "strFieldName", ",", "String", "strSize", ",", "String", "strMaxSize", ",", "String", "strValue", ",", "String", "strControlType", ",", "int", "iHtmlAtt...
Display this field in html input format. @param out The html out stream. @param strFieldDesc The field description. @param strFieldName The field name. @param strSize The control size. @param strMaxSize The string max size. @param strValue The default value. @param strControlType The control type. @param iHtmlAttribures The attributes.
[ "Display", "this", "field", "in", "html", "input", "format", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/HScreenField.java#L92-L96
netty/netty
buffer/src/main/java/io/netty/buffer/Unpooled.java
Unpooled.wrappedBuffer
public static ByteBuf wrappedBuffer(byte[] array) { """ Creates a new big-endian buffer which wraps the specified {@code array}. A modification on the specified array's content will be visible to the returned buffer. """ if (array.length == 0) { return EMPTY_BUFFER; } return new UnpooledHeapByteBuf(ALLOC, array, array.length); }
java
public static ByteBuf wrappedBuffer(byte[] array) { if (array.length == 0) { return EMPTY_BUFFER; } return new UnpooledHeapByteBuf(ALLOC, array, array.length); }
[ "public", "static", "ByteBuf", "wrappedBuffer", "(", "byte", "[", "]", "array", ")", "{", "if", "(", "array", ".", "length", "==", "0", ")", "{", "return", "EMPTY_BUFFER", ";", "}", "return", "new", "UnpooledHeapByteBuf", "(", "ALLOC", ",", "array", ",",...
Creates a new big-endian buffer which wraps the specified {@code array}. A modification on the specified array's content will be visible to the returned buffer.
[ "Creates", "a", "new", "big", "-", "endian", "buffer", "which", "wraps", "the", "specified", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/buffer/src/main/java/io/netty/buffer/Unpooled.java#L153-L158
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/plugins/configuration/Validator.java
Validator.mapProperties
public static Map<String, String> mapProperties(final Map<String, String> input, final Description desc) { """ Converts a set of input configuration keys using the description's configuration to property mapping, or the same input if the description has no mapping @param input input map @param desc plugin description @return mapped values """ final Map<String, String> mapping = desc.getPropertiesMapping(); if (null == mapping) { return input; } return performMapping(input, mapping, false); }
java
public static Map<String, String> mapProperties(final Map<String, String> input, final Description desc) { final Map<String, String> mapping = desc.getPropertiesMapping(); if (null == mapping) { return input; } return performMapping(input, mapping, false); }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "mapProperties", "(", "final", "Map", "<", "String", ",", "String", ">", "input", ",", "final", "Description", "desc", ")", "{", "final", "Map", "<", "String", ",", "String", ">", "mapping", ...
Converts a set of input configuration keys using the description's configuration to property mapping, or the same input if the description has no mapping @param input input map @param desc plugin description @return mapped values
[ "Converts", "a", "set", "of", "input", "configuration", "keys", "using", "the", "description", "s", "configuration", "to", "property", "mapping", "or", "the", "same", "input", "if", "the", "description", "has", "no", "mapping" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/plugins/configuration/Validator.java#L240-L246
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java
DebugUtil.printClassDetails
public static void printClassDetails(final Object pObject, final String pObjectName) { """ Prints javadoc-like, the top wrapped class fields and methods of a {@code java.lang.Object} to {@code System.out}. <p> @param pObject the {@code java.lang.Object} to be analysed. @param pObjectName the name of the object instance, for identification purposes. @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/lang/Class.html">{@code java.lang.Class}</a> @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/lang/reflect/Modifier.html">{@code java.lang.reflect.Modifier}</a> @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/lang/reflect/Field.html">{@code java.lang.reflect.Field}</a> @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/lang/reflect/Constructor.html">{@code java.lang.reflect.Constructor}</a> @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/lang/reflect/Method.html">{@code java.lang.reflect.Method}</a> """ printClassDetails(pObject, pObjectName, System.out); }
java
public static void printClassDetails(final Object pObject, final String pObjectName) { printClassDetails(pObject, pObjectName, System.out); }
[ "public", "static", "void", "printClassDetails", "(", "final", "Object", "pObject", ",", "final", "String", "pObjectName", ")", "{", "printClassDetails", "(", "pObject", ",", "pObjectName", ",", "System", ".", "out", ")", ";", "}" ]
Prints javadoc-like, the top wrapped class fields and methods of a {@code java.lang.Object} to {@code System.out}. <p> @param pObject the {@code java.lang.Object} to be analysed. @param pObjectName the name of the object instance, for identification purposes. @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/lang/Class.html">{@code java.lang.Class}</a> @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/lang/reflect/Modifier.html">{@code java.lang.reflect.Modifier}</a> @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/lang/reflect/Field.html">{@code java.lang.reflect.Field}</a> @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/lang/reflect/Constructor.html">{@code java.lang.reflect.Constructor}</a> @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/lang/reflect/Method.html">{@code java.lang.reflect.Method}</a>
[ "Prints", "javadoc", "-", "like", "the", "top", "wrapped", "class", "fields", "and", "methods", "of", "a", "{" ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java#L1334-L1336
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendClose
public static <T> void sendClose(final int code, String reason, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context) { """ Sends a complete close message, invoking the callback when complete @param code The close code @param wsChannel The web socket channel @param callback The callback to invoke on completion @param context The context object that will be passed to the callback on completion """ sendClose(new CloseMessage(code, reason), wsChannel, callback, context); }
java
public static <T> void sendClose(final int code, String reason, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context) { sendClose(new CloseMessage(code, reason), wsChannel, callback, context); }
[ "public", "static", "<", "T", ">", "void", "sendClose", "(", "final", "int", "code", ",", "String", "reason", ",", "final", "WebSocketChannel", "wsChannel", ",", "final", "WebSocketCallback", "<", "T", ">", "callback", ",", "T", "context", ")", "{", "sendC...
Sends a complete close message, invoking the callback when complete @param code The close code @param wsChannel The web socket channel @param callback The callback to invoke on completion @param context The context object that will be passed to the callback on completion
[ "Sends", "a", "complete", "close", "message", "invoking", "the", "callback", "when", "complete" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L830-L832
jbundle/jbundle
thin/base/db/base/src/main/java/org/jbundle/thin/base/db/mem/MemoryFieldTable.java
MemoryFieldTable.init
public void init(Rec record, PTable tableRemote, PhysicalDatabaseParent dbOwner) { """ Constructor. @param record The record to handle. @param tableRemote The remote table. @param server The remote server (only used for synchronization). """ super.init(record); this.setPTableRef(tableRemote, dbOwner); }
java
public void init(Rec record, PTable tableRemote, PhysicalDatabaseParent dbOwner) { super.init(record); this.setPTableRef(tableRemote, dbOwner); }
[ "public", "void", "init", "(", "Rec", "record", ",", "PTable", "tableRemote", ",", "PhysicalDatabaseParent", "dbOwner", ")", "{", "super", ".", "init", "(", "record", ")", ";", "this", ".", "setPTableRef", "(", "tableRemote", ",", "dbOwner", ")", ";", "}" ...
Constructor. @param record The record to handle. @param tableRemote The remote table. @param server The remote server (only used for synchronization).
[ "Constructor", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/db/base/src/main/java/org/jbundle/thin/base/db/mem/MemoryFieldTable.java#L64-L68
undertow-io/undertow
core/src/main/java/io/undertow/server/ServerConnection.java
ServerConnection.pushResource
public boolean pushResource(final String path, final HttpString method, final HeaderMap requestHeaders, HttpHandler handler) { """ Attempts to push a resource if this connection supports server push. Otherwise the request is ignored. Note that push is always done on a best effort basis, even if this method returns true it is possible that the remote endpoint will reset the stream. The {@link io.undertow.server.HttpHandler} passed in will be used to generate the pushed response @param path The path of the resource @param method The request method @param requestHeaders The request headers @return <code>true</code> if the server attempted the push, false otherwise """ return false; }
java
public boolean pushResource(final String path, final HttpString method, final HeaderMap requestHeaders, HttpHandler handler) { return false; }
[ "public", "boolean", "pushResource", "(", "final", "String", "path", ",", "final", "HttpString", "method", ",", "final", "HeaderMap", "requestHeaders", ",", "HttpHandler", "handler", ")", "{", "return", "false", ";", "}" ]
Attempts to push a resource if this connection supports server push. Otherwise the request is ignored. Note that push is always done on a best effort basis, even if this method returns true it is possible that the remote endpoint will reset the stream. The {@link io.undertow.server.HttpHandler} passed in will be used to generate the pushed response @param path The path of the resource @param method The request method @param requestHeaders The request headers @return <code>true</code> if the server attempted the push, false otherwise
[ "Attempts", "to", "push", "a", "resource", "if", "this", "connection", "supports", "server", "push", ".", "Otherwise", "the", "request", "is", "ignored", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/ServerConnection.java#L276-L278
kiswanij/jk-util
src/main/java/com/jk/util/JKObjectUtil.java
JKObjectUtil.jsonToObject
public static <T> Object jsonToObject(String json, Class<T> clas) { """ Json to object. @param <T> the generic type @param json the json @param clas the clas @return the object """ ObjectMapper mapper = new ObjectMapper(); try { return mapper.readValue(json, clas); } catch (IOException e) { JK.throww(e); return null; } }
java
public static <T> Object jsonToObject(String json, Class<T> clas) { ObjectMapper mapper = new ObjectMapper(); try { return mapper.readValue(json, clas); } catch (IOException e) { JK.throww(e); return null; } }
[ "public", "static", "<", "T", ">", "Object", "jsonToObject", "(", "String", "json", ",", "Class", "<", "T", ">", "clas", ")", "{", "ObjectMapper", "mapper", "=", "new", "ObjectMapper", "(", ")", ";", "try", "{", "return", "mapper", ".", "readValue", "(...
Json to object. @param <T> the generic type @param json the json @param clas the clas @return the object
[ "Json", "to", "object", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKObjectUtil.java#L690-L698
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UPropertyAliases.java
UPropertyAliases.getPropertyValueEnum
public int getPropertyValueEnum(int property, CharSequence alias) { """ Returns a value enum given a property enum and one of its value names. """ int valueMapIndex=findProperty(property); if(valueMapIndex==0) { throw new IllegalArgumentException( "Invalid property enum "+property+" (0x"+Integer.toHexString(property)+")"); } valueMapIndex=valueMaps[valueMapIndex+1]; if(valueMapIndex==0) { throw new IllegalArgumentException( "Property "+property+" (0x"+Integer.toHexString(property)+ ") does not have named values"); } // valueMapIndex is the start of the property's valueMap, // where the first word is the BytesTrie offset. return getPropertyOrValueEnum(valueMaps[valueMapIndex], alias); }
java
public int getPropertyValueEnum(int property, CharSequence alias) { int valueMapIndex=findProperty(property); if(valueMapIndex==0) { throw new IllegalArgumentException( "Invalid property enum "+property+" (0x"+Integer.toHexString(property)+")"); } valueMapIndex=valueMaps[valueMapIndex+1]; if(valueMapIndex==0) { throw new IllegalArgumentException( "Property "+property+" (0x"+Integer.toHexString(property)+ ") does not have named values"); } // valueMapIndex is the start of the property's valueMap, // where the first word is the BytesTrie offset. return getPropertyOrValueEnum(valueMaps[valueMapIndex], alias); }
[ "public", "int", "getPropertyValueEnum", "(", "int", "property", ",", "CharSequence", "alias", ")", "{", "int", "valueMapIndex", "=", "findProperty", "(", "property", ")", ";", "if", "(", "valueMapIndex", "==", "0", ")", "{", "throw", "new", "IllegalArgumentEx...
Returns a value enum given a property enum and one of its value names.
[ "Returns", "a", "value", "enum", "given", "a", "property", "enum", "and", "one", "of", "its", "value", "names", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UPropertyAliases.java#L293-L308
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java
JBBPBitOutputStream.writeBits
public void writeBits(final int value, final JBBPBitNumber bitNumber) throws IOException { """ Write bits into the output stream. @param value the value which bits will be written in the output stream @param bitNumber number of bits from the value to be written, must be in 1..8 @throws IOException it will be thrown for transport errors @throws IllegalArgumentException it will be thrown for wrong bit number """ if (this.bitBufferCount == 0 && bitNumber == JBBPBitNumber.BITS_8) { write(value); } else { final int initialMask; int mask; initialMask = 1; mask = initialMask << this.bitBufferCount; int accum = value; int i = bitNumber.getBitNumber(); while (i > 0) { this.bitBuffer = this.bitBuffer | ((accum & 1) == 0 ? 0 : mask); accum >>= 1; mask = mask << 1; i--; this.bitBufferCount++; if (this.bitBufferCount == 8) { this.bitBufferCount = 0; writeByte(this.bitBuffer); mask = initialMask; this.bitBuffer = 0; } } } }
java
public void writeBits(final int value, final JBBPBitNumber bitNumber) throws IOException { if (this.bitBufferCount == 0 && bitNumber == JBBPBitNumber.BITS_8) { write(value); } else { final int initialMask; int mask; initialMask = 1; mask = initialMask << this.bitBufferCount; int accum = value; int i = bitNumber.getBitNumber(); while (i > 0) { this.bitBuffer = this.bitBuffer | ((accum & 1) == 0 ? 0 : mask); accum >>= 1; mask = mask << 1; i--; this.bitBufferCount++; if (this.bitBufferCount == 8) { this.bitBufferCount = 0; writeByte(this.bitBuffer); mask = initialMask; this.bitBuffer = 0; } } } }
[ "public", "void", "writeBits", "(", "final", "int", "value", ",", "final", "JBBPBitNumber", "bitNumber", ")", "throws", "IOException", "{", "if", "(", "this", ".", "bitBufferCount", "==", "0", "&&", "bitNumber", "==", "JBBPBitNumber", ".", "BITS_8", ")", "{"...
Write bits into the output stream. @param value the value which bits will be written in the output stream @param bitNumber number of bits from the value to be written, must be in 1..8 @throws IOException it will be thrown for transport errors @throws IllegalArgumentException it will be thrown for wrong bit number
[ "Write", "bits", "into", "the", "output", "stream", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java#L260-L288
onelogin/onelogin-java-sdk
src/main/java/com/onelogin/sdk/conn/Client.java
Client.createSessionLoginToken
public Object createSessionLoginToken(Map<String, Object> queryParams, String allowedOrigin) throws OAuthSystemException, OAuthProblemException, URISyntaxException { """ Generates a session login token in scenarios in which MFA may or may not be required. A session login token expires two minutes after creation. @param queryParams Query Parameters (username_or_email, password, subdomain, return_to_url, ip_address, browser_id) @param allowedOrigin Custom-Allowed-Origin-Header. Required for CORS requests only. Set to the Origin URI from which you are allowed to send a request using CORS. @return SessionTokenInfo or SessionTokenMFAInfo object if success @throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection @throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled @throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor @see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/users/create-session-login-token">Create Session Login Token documentation</a> """ cleanError(); prepareToken(); OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient(); OAuthClient oAuthClient = new OAuthClient(httpClient); URIBuilder url = new URIBuilder(settings.getURL(Constants.SESSION_LOGIN_TOKEN_URL)); OAuthClientRequest bearerRequest = new OAuthBearerClientRequest(url.toString()) .buildHeaderMessage(); Map<String, String> headers = getAuthorizedHeader(); if (allowedOrigin != null) { headers.put("Custom-Allowed-Origin-Header-1", allowedOrigin); } bearerRequest.setHeaders(headers); String body = JSONUtils.buildJSON(queryParams); bearerRequest.setBody(body); Object sessionToken = null; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient.resource(bearerRequest, OAuth.HttpMethod.POST, OneloginOAuthJSONResourceResponse.class); if (oAuthResponse.getResponseCode() == 200) { if (oAuthResponse.getType().equals("success")) { JSONObject data = oAuthResponse.getData(); if (oAuthResponse.getMessage().equals("Success")) { sessionToken = new SessionTokenInfo(data); } else if (oAuthResponse.getMessage().equals("MFA is required for this user")) { sessionToken = new SessionTokenMFAInfo(data); } } } else { error = oAuthResponse.getError(); errorDescription = oAuthResponse.getErrorDescription(); } return sessionToken; }
java
public Object createSessionLoginToken(Map<String, Object> queryParams, String allowedOrigin) throws OAuthSystemException, OAuthProblemException, URISyntaxException { cleanError(); prepareToken(); OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient(); OAuthClient oAuthClient = new OAuthClient(httpClient); URIBuilder url = new URIBuilder(settings.getURL(Constants.SESSION_LOGIN_TOKEN_URL)); OAuthClientRequest bearerRequest = new OAuthBearerClientRequest(url.toString()) .buildHeaderMessage(); Map<String, String> headers = getAuthorizedHeader(); if (allowedOrigin != null) { headers.put("Custom-Allowed-Origin-Header-1", allowedOrigin); } bearerRequest.setHeaders(headers); String body = JSONUtils.buildJSON(queryParams); bearerRequest.setBody(body); Object sessionToken = null; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient.resource(bearerRequest, OAuth.HttpMethod.POST, OneloginOAuthJSONResourceResponse.class); if (oAuthResponse.getResponseCode() == 200) { if (oAuthResponse.getType().equals("success")) { JSONObject data = oAuthResponse.getData(); if (oAuthResponse.getMessage().equals("Success")) { sessionToken = new SessionTokenInfo(data); } else if (oAuthResponse.getMessage().equals("MFA is required for this user")) { sessionToken = new SessionTokenMFAInfo(data); } } } else { error = oAuthResponse.getError(); errorDescription = oAuthResponse.getErrorDescription(); } return sessionToken; }
[ "public", "Object", "createSessionLoginToken", "(", "Map", "<", "String", ",", "Object", ">", "queryParams", ",", "String", "allowedOrigin", ")", "throws", "OAuthSystemException", ",", "OAuthProblemException", ",", "URISyntaxException", "{", "cleanError", "(", ")", ...
Generates a session login token in scenarios in which MFA may or may not be required. A session login token expires two minutes after creation. @param queryParams Query Parameters (username_or_email, password, subdomain, return_to_url, ip_address, browser_id) @param allowedOrigin Custom-Allowed-Origin-Header. Required for CORS requests only. Set to the Origin URI from which you are allowed to send a request using CORS. @return SessionTokenInfo or SessionTokenMFAInfo object if success @throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection @throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled @throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor @see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/users/create-session-login-token">Create Session Login Token documentation</a>
[ "Generates", "a", "session", "login", "token", "in", "scenarios", "in", "which", "MFA", "may", "or", "may", "not", "be", "required", ".", "A", "session", "login", "token", "expires", "two", "minutes", "after", "creation", "." ]
train
https://github.com/onelogin/onelogin-java-sdk/blob/1570b78033dcc1c7387099e77fe41b6b0638df8c/src/main/java/com/onelogin/sdk/conn/Client.java#L816-L853
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkManager.java
BookmarkManager.addBookmarkedURL
public void addBookmarkedURL(String URL, String name, boolean isRSS) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { """ Adds a new url or updates an already existing url in the bookmarks. @param URL the url of the bookmark @param name the name of the bookmark @param isRSS whether or not the url is an rss feed @throws XMPPErrorException thrown when there is an error retriving or saving bookmarks from or to the server @throws NoResponseException if there was no response from the server. @throws NotConnectedException @throws InterruptedException """ retrieveBookmarks(); BookmarkedURL bookmark = new BookmarkedURL(URL, name, isRSS); List<BookmarkedURL> urls = bookmarks.getBookmarkedURLS(); if (urls.contains(bookmark)) { BookmarkedURL oldURL = urls.get(urls.indexOf(bookmark)); if (oldURL.isShared()) { throw new IllegalArgumentException("Cannot modify shared bookmarks"); } oldURL.setName(name); oldURL.setRss(isRSS); } else { bookmarks.addBookmarkedURL(bookmark); } privateDataManager.setPrivateData(bookmarks); }
java
public void addBookmarkedURL(String URL, String name, boolean isRSS) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { retrieveBookmarks(); BookmarkedURL bookmark = new BookmarkedURL(URL, name, isRSS); List<BookmarkedURL> urls = bookmarks.getBookmarkedURLS(); if (urls.contains(bookmark)) { BookmarkedURL oldURL = urls.get(urls.indexOf(bookmark)); if (oldURL.isShared()) { throw new IllegalArgumentException("Cannot modify shared bookmarks"); } oldURL.setName(name); oldURL.setRss(isRSS); } else { bookmarks.addBookmarkedURL(bookmark); } privateDataManager.setPrivateData(bookmarks); }
[ "public", "void", "addBookmarkedURL", "(", "String", "URL", ",", "String", "name", ",", "boolean", "isRSS", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "retrieveBookmarks", "(", ")", ...
Adds a new url or updates an already existing url in the bookmarks. @param URL the url of the bookmark @param name the name of the bookmark @param isRSS whether or not the url is an rss feed @throws XMPPErrorException thrown when there is an error retriving or saving bookmarks from or to the server @throws NoResponseException if there was no response from the server. @throws NotConnectedException @throws InterruptedException
[ "Adds", "a", "new", "url", "or", "updates", "an", "already", "existing", "url", "in", "the", "bookmarks", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/bookmarks/BookmarkManager.java#L191-L207
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.clickLongOnView
public void clickLongOnView(View view, int time) { """ Long clicks the specified View for a specified amount of time. @param view the {@link View} to long click @param time the amount of time to long click """ if(config.commandLogging){ Log.d(config.commandLoggingTag, "clickLongOnView("+view+", "+time+")"); } clicker.clickOnScreen(view, true, time); }
java
public void clickLongOnView(View view, int time) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "clickLongOnView("+view+", "+time+")"); } clicker.clickOnScreen(view, true, time); }
[ "public", "void", "clickLongOnView", "(", "View", "view", ",", "int", "time", ")", "{", "if", "(", "config", ".", "commandLogging", ")", "{", "Log", ".", "d", "(", "config", ".", "commandLoggingTag", ",", "\"clickLongOnView(\"", "+", "view", "+", "\", \"",...
Long clicks the specified View for a specified amount of time. @param view the {@link View} to long click @param time the amount of time to long click
[ "Long", "clicks", "the", "specified", "View", "for", "a", "specified", "amount", "of", "time", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L1491-L1498
jbundle/jbundle
base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/html/HAppletHtmlScreen.java
HAppletHtmlScreen.printHtmlMenuStart
public void printHtmlMenuStart(PrintWriter out, ResourceBundle reg) throws DBException { """ Print the top nav menu. @exception DBException File exception. """ this.printHtmlBanner(out, reg); this.printHtmlLogo(out, reg); this.printHtmlMenubar(out, reg); // Don't print the table start portion or the nav menus }
java
public void printHtmlMenuStart(PrintWriter out, ResourceBundle reg) throws DBException { this.printHtmlBanner(out, reg); this.printHtmlLogo(out, reg); this.printHtmlMenubar(out, reg); // Don't print the table start portion or the nav menus }
[ "public", "void", "printHtmlMenuStart", "(", "PrintWriter", "out", ",", "ResourceBundle", "reg", ")", "throws", "DBException", "{", "this", ".", "printHtmlBanner", "(", "out", ",", "reg", ")", ";", "this", ".", "printHtmlLogo", "(", "out", ",", "reg", ")", ...
Print the top nav menu. @exception DBException File exception.
[ "Print", "the", "top", "nav", "menu", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/html/HAppletHtmlScreen.java#L113-L120
stickfigure/batchfb
src/main/java/com/googlecode/batchfb/FacebookBatcher.java
FacebookBatcher.getBatchForGraph
private Batch getBatchForGraph() { """ Get an appropriate Batch for issuing a new graph call. Will construct a new one if all existing batches are full. """ Batch lastValidBatch = this.batches.isEmpty() ? null : this.batches.get(this.batches.size()-1); if (lastValidBatch != null && lastValidBatch.graphSize() < this.maxBatchSize) return lastValidBatch; else { Batch next = new Batch(this, this.mapper, this.accessToken, this.apiVersion, this.timeout, this.retries); this.batches.add(next); return next; } }
java
private Batch getBatchForGraph() { Batch lastValidBatch = this.batches.isEmpty() ? null : this.batches.get(this.batches.size()-1); if (lastValidBatch != null && lastValidBatch.graphSize() < this.maxBatchSize) return lastValidBatch; else { Batch next = new Batch(this, this.mapper, this.accessToken, this.apiVersion, this.timeout, this.retries); this.batches.add(next); return next; } }
[ "private", "Batch", "getBatchForGraph", "(", ")", "{", "Batch", "lastValidBatch", "=", "this", ".", "batches", ".", "isEmpty", "(", ")", "?", "null", ":", "this", ".", "batches", ".", "get", "(", "this", ".", "batches", ".", "size", "(", ")", "-", "1...
Get an appropriate Batch for issuing a new graph call. Will construct a new one if all existing batches are full.
[ "Get", "an", "appropriate", "Batch", "for", "issuing", "a", "new", "graph", "call", ".", "Will", "construct", "a", "new", "one", "if", "all", "existing", "batches", "are", "full", "." ]
train
https://github.com/stickfigure/batchfb/blob/ceeda78aa6d8397eec032ab1d8997adb7378e9e2/src/main/java/com/googlecode/batchfb/FacebookBatcher.java#L390-L400
apache/incubator-gobblin
gobblin-modules/gobblin-parquet/src/main/java/org/apache/gobblin/converter/parquet/ParquetGroup.java
ParquetGroup.addGroup
private void addGroup(String key, Group object) { """ Add a {@link Group} given a String key. @param key @param object """ int fieldIndex = getIndex(key); this.schema.getType(fieldIndex).asGroupType(); this.data[fieldIndex].add(object); }
java
private void addGroup(String key, Group object) { int fieldIndex = getIndex(key); this.schema.getType(fieldIndex).asGroupType(); this.data[fieldIndex].add(object); }
[ "private", "void", "addGroup", "(", "String", "key", ",", "Group", "object", ")", "{", "int", "fieldIndex", "=", "getIndex", "(", "key", ")", ";", "this", ".", "schema", ".", "getType", "(", "fieldIndex", ")", ".", "asGroupType", "(", ")", ";", "this",...
Add a {@link Group} given a String key. @param key @param object
[ "Add", "a", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-parquet/src/main/java/org/apache/gobblin/converter/parquet/ParquetGroup.java#L227-L231
TakahikoKawasaki/nv-websocket-client
src/main/java/com/neovisionaries/ws/client/HandshakeReader.java
HandshakeReader.validateStatusLine
private void validateStatusLine(StatusLine statusLine, Map<String, List<String>> headers, WebSocketInputStream input) throws WebSocketException { """ Validate the status line. {@code "101 Switching Protocols"} is expected. """ // If the status code is 101 (Switching Protocols). if (statusLine.getStatusCode() == 101) { // OK. The server can speak the WebSocket protocol. return; } // Read the response body. byte[] body = readBody(headers, input); // The status code of the opening handshake response is not Switching Protocols. throw new OpeningHandshakeException( WebSocketError.NOT_SWITCHING_PROTOCOLS, "The status code of the opening handshake response is not '101 Switching Protocols'. The status line is: " + statusLine, statusLine, headers, body); }
java
private void validateStatusLine(StatusLine statusLine, Map<String, List<String>> headers, WebSocketInputStream input) throws WebSocketException { // If the status code is 101 (Switching Protocols). if (statusLine.getStatusCode() == 101) { // OK. The server can speak the WebSocket protocol. return; } // Read the response body. byte[] body = readBody(headers, input); // The status code of the opening handshake response is not Switching Protocols. throw new OpeningHandshakeException( WebSocketError.NOT_SWITCHING_PROTOCOLS, "The status code of the opening handshake response is not '101 Switching Protocols'. The status line is: " + statusLine, statusLine, headers, body); }
[ "private", "void", "validateStatusLine", "(", "StatusLine", "statusLine", ",", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "headers", ",", "WebSocketInputStream", "input", ")", "throws", "WebSocketException", "{", "// If the status code is 101 (Switchi...
Validate the status line. {@code "101 Switching Protocols"} is expected.
[ "Validate", "the", "status", "line", ".", "{" ]
train
https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/HandshakeReader.java#L219-L236
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/lang/gosuc/cli/CommandLineCompiler.java
CommandLineCompiler.summarize
private static boolean summarize( List<String> warnings, List<String> errors, boolean isNoWarn ) { """ @param warnings List of warnings @param errors List of errors @param isNoWarn true if warnings are disabled @return true if compilation resulted in errors, false otherwise """ if( isNoWarn ) { System.out.printf( "\ngosuc completed with %d errors. Warnings were disabled.\n", errors.size() ); } else { System.out.printf( "\ngosuc completed with %d warnings and %d errors.\n", warnings.size(), errors.size() ); } return errors.size() > 0; }
java
private static boolean summarize( List<String> warnings, List<String> errors, boolean isNoWarn ) { if( isNoWarn ) { System.out.printf( "\ngosuc completed with %d errors. Warnings were disabled.\n", errors.size() ); } else { System.out.printf( "\ngosuc completed with %d warnings and %d errors.\n", warnings.size(), errors.size() ); } return errors.size() > 0; }
[ "private", "static", "boolean", "summarize", "(", "List", "<", "String", ">", "warnings", ",", "List", "<", "String", ">", "errors", ",", "boolean", "isNoWarn", ")", "{", "if", "(", "isNoWarn", ")", "{", "System", ".", "out", ".", "printf", "(", "\"\\n...
@param warnings List of warnings @param errors List of errors @param isNoWarn true if warnings are disabled @return true if compilation resulted in errors, false otherwise
[ "@param", "warnings", "List", "of", "warnings", "@param", "errors", "List", "of", "errors", "@param", "isNoWarn", "true", "if", "warnings", "are", "disabled" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/lang/gosuc/cli/CommandLineCompiler.java#L95-L107
netty/netty
codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java
MqttDecoder.decodeFixedHeader
private static MqttFixedHeader decodeFixedHeader(ByteBuf buffer) { """ Decodes the fixed header. It's one byte for the flags and then variable bytes for the remaining length. @param buffer the buffer to decode from @return the fixed header """ short b1 = buffer.readUnsignedByte(); MqttMessageType messageType = MqttMessageType.valueOf(b1 >> 4); boolean dupFlag = (b1 & 0x08) == 0x08; int qosLevel = (b1 & 0x06) >> 1; boolean retain = (b1 & 0x01) != 0; int remainingLength = 0; int multiplier = 1; short digit; int loops = 0; do { digit = buffer.readUnsignedByte(); remainingLength += (digit & 127) * multiplier; multiplier *= 128; loops++; } while ((digit & 128) != 0 && loops < 4); // MQTT protocol limits Remaining Length to 4 bytes if (loops == 4 && (digit & 128) != 0) { throw new DecoderException("remaining length exceeds 4 digits (" + messageType + ')'); } MqttFixedHeader decodedFixedHeader = new MqttFixedHeader(messageType, dupFlag, MqttQoS.valueOf(qosLevel), retain, remainingLength); return validateFixedHeader(resetUnusedFields(decodedFixedHeader)); }
java
private static MqttFixedHeader decodeFixedHeader(ByteBuf buffer) { short b1 = buffer.readUnsignedByte(); MqttMessageType messageType = MqttMessageType.valueOf(b1 >> 4); boolean dupFlag = (b1 & 0x08) == 0x08; int qosLevel = (b1 & 0x06) >> 1; boolean retain = (b1 & 0x01) != 0; int remainingLength = 0; int multiplier = 1; short digit; int loops = 0; do { digit = buffer.readUnsignedByte(); remainingLength += (digit & 127) * multiplier; multiplier *= 128; loops++; } while ((digit & 128) != 0 && loops < 4); // MQTT protocol limits Remaining Length to 4 bytes if (loops == 4 && (digit & 128) != 0) { throw new DecoderException("remaining length exceeds 4 digits (" + messageType + ')'); } MqttFixedHeader decodedFixedHeader = new MqttFixedHeader(messageType, dupFlag, MqttQoS.valueOf(qosLevel), retain, remainingLength); return validateFixedHeader(resetUnusedFields(decodedFixedHeader)); }
[ "private", "static", "MqttFixedHeader", "decodeFixedHeader", "(", "ByteBuf", "buffer", ")", "{", "short", "b1", "=", "buffer", ".", "readUnsignedByte", "(", ")", ";", "MqttMessageType", "messageType", "=", "MqttMessageType", ".", "valueOf", "(", "b1", ">>", "4",...
Decodes the fixed header. It's one byte for the flags and then variable bytes for the remaining length. @param buffer the buffer to decode from @return the fixed header
[ "Decodes", "the", "fixed", "header", ".", "It", "s", "one", "byte", "for", "the", "flags", "and", "then", "variable", "bytes", "for", "the", "remaining", "length", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java#L145-L171
jasminb/jsonapi-converter
src/main/java/com/github/jasminb/jsonapi/ResourceConverter.java
ResourceConverter.setTypeResolver
public void setTypeResolver(RelationshipResolver resolver, Class<?> type) { """ Registers relationship resolver for given type. Resolver will be used if relationship resolution is enabled trough relationship annotation. @param resolver resolver instance @param type type """ if (resolver != null) { String typeName = ReflectionUtils.getTypeName(type); if (typeName != null) { typedResolvers.put(type, resolver); } } }
java
public void setTypeResolver(RelationshipResolver resolver, Class<?> type) { if (resolver != null) { String typeName = ReflectionUtils.getTypeName(type); if (typeName != null) { typedResolvers.put(type, resolver); } } }
[ "public", "void", "setTypeResolver", "(", "RelationshipResolver", "resolver", ",", "Class", "<", "?", ">", "type", ")", "{", "if", "(", "resolver", "!=", "null", ")", "{", "String", "typeName", "=", "ReflectionUtils", ".", "getTypeName", "(", "type", ")", ...
Registers relationship resolver for given type. Resolver will be used if relationship resolution is enabled trough relationship annotation. @param resolver resolver instance @param type type
[ "Registers", "relationship", "resolver", "for", "given", "type", ".", "Resolver", "will", "be", "used", "if", "relationship", "resolution", "is", "enabled", "trough", "relationship", "annotation", "." ]
train
https://github.com/jasminb/jsonapi-converter/blob/73b41c3b9274e70e62b3425071ca8afdc7bddaf6/src/main/java/com/github/jasminb/jsonapi/ResourceConverter.java#L131-L139
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/internal/instantiation/InstantiatorProvider.java
InstantiatorProvider.getConversionFromDbValue
public @NotNull TypeConversion getConversionFromDbValue(@NotNull Type source, @NotNull Type target) { """ Returns conversion for converting value of source-type to target-type, or throws exception if there's no such conversion. """ TypeConversion conversion = findConversionFromDbValue(source, target).orElse(null); if (conversion != null) return conversion; else throw new InstantiationFailureException("could not find a conversion from " + source.getTypeName() + " to " + target.getTypeName()); }
java
public @NotNull TypeConversion getConversionFromDbValue(@NotNull Type source, @NotNull Type target) { TypeConversion conversion = findConversionFromDbValue(source, target).orElse(null); if (conversion != null) return conversion; else throw new InstantiationFailureException("could not find a conversion from " + source.getTypeName() + " to " + target.getTypeName()); }
[ "public", "@", "NotNull", "TypeConversion", "getConversionFromDbValue", "(", "@", "NotNull", "Type", "source", ",", "@", "NotNull", "Type", "target", ")", "{", "TypeConversion", "conversion", "=", "findConversionFromDbValue", "(", "source", ",", "target", ")", "."...
Returns conversion for converting value of source-type to target-type, or throws exception if there's no such conversion.
[ "Returns", "conversion", "for", "converting", "value", "of", "source", "-", "type", "to", "target", "-", "type", "or", "throws", "exception", "if", "there", "s", "no", "such", "conversion", "." ]
train
https://github.com/EvidentSolutions/dalesbred/blob/713f5b6e152d97e1672ca68b9ff9c7c6c288ceb1/dalesbred/src/main/java/org/dalesbred/internal/instantiation/InstantiatorProvider.java#L239-L245
ttddyy/datasource-proxy
src/main/java/net/ttddyy/dsproxy/listener/logging/DefaultQueryLogEntryCreator.java
DefaultQueryLogEntryCreator.writeConnectionIdEntry
protected void writeConnectionIdEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { """ Write connection ID when enabled. <p>default: Connection: 1, @param sb StringBuilder to write @param execInfo execution info @param queryInfoList query info list @since 1.4.2 """ sb.append("Connection:"); sb.append(execInfo.getConnectionId()); sb.append(", "); }
java
protected void writeConnectionIdEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { sb.append("Connection:"); sb.append(execInfo.getConnectionId()); sb.append(", "); }
[ "protected", "void", "writeConnectionIdEntry", "(", "StringBuilder", "sb", ",", "ExecutionInfo", "execInfo", ",", "List", "<", "QueryInfo", ">", "queryInfoList", ")", "{", "sb", ".", "append", "(", "\"Connection:\"", ")", ";", "sb", ".", "append", "(", "execIn...
Write connection ID when enabled. <p>default: Connection: 1, @param sb StringBuilder to write @param execInfo execution info @param queryInfoList query info list @since 1.4.2
[ "Write", "connection", "ID", "when", "enabled", "." ]
train
https://github.com/ttddyy/datasource-proxy/blob/62163ccf9a569a99aa3ad9f9151a32567447a62e/src/main/java/net/ttddyy/dsproxy/listener/logging/DefaultQueryLogEntryCreator.java#L107-L111
OpenFeign/feign
core/src/main/java/feign/Util.java
Util.resolveLastTypeParameter
public static Type resolveLastTypeParameter(Type genericContext, Class<?> supertype) throws IllegalStateException { """ Resolves the last type parameter of the parameterized {@code supertype}, based on the {@code genericContext}, into its upper bounds. <p/> Implementation copied from {@code retrofit.RestMethodInfo}. @param genericContext Ex. {@link java.lang.reflect.Field#getGenericType()} @param supertype Ex. {@code Decoder.class} @return in the example above, the type parameter of {@code Decoder}. @throws IllegalStateException if {@code supertype} cannot be resolved into a parameterized type using {@code context}. """ Type resolvedSuperType = Types.getSupertype(genericContext, Types.getRawType(genericContext), supertype); checkState(resolvedSuperType instanceof ParameterizedType, "could not resolve %s into a parameterized type %s", genericContext, supertype); Type[] types = ParameterizedType.class.cast(resolvedSuperType).getActualTypeArguments(); for (int i = 0; i < types.length; i++) { Type type = types[i]; if (type instanceof WildcardType) { types[i] = ((WildcardType) type).getUpperBounds()[0]; } } return types[types.length - 1]; }
java
public static Type resolveLastTypeParameter(Type genericContext, Class<?> supertype) throws IllegalStateException { Type resolvedSuperType = Types.getSupertype(genericContext, Types.getRawType(genericContext), supertype); checkState(resolvedSuperType instanceof ParameterizedType, "could not resolve %s into a parameterized type %s", genericContext, supertype); Type[] types = ParameterizedType.class.cast(resolvedSuperType).getActualTypeArguments(); for (int i = 0; i < types.length; i++) { Type type = types[i]; if (type instanceof WildcardType) { types[i] = ((WildcardType) type).getUpperBounds()[0]; } } return types[types.length - 1]; }
[ "public", "static", "Type", "resolveLastTypeParameter", "(", "Type", "genericContext", ",", "Class", "<", "?", ">", "supertype", ")", "throws", "IllegalStateException", "{", "Type", "resolvedSuperType", "=", "Types", ".", "getSupertype", "(", "genericContext", ",", ...
Resolves the last type parameter of the parameterized {@code supertype}, based on the {@code genericContext}, into its upper bounds. <p/> Implementation copied from {@code retrofit.RestMethodInfo}. @param genericContext Ex. {@link java.lang.reflect.Field#getGenericType()} @param supertype Ex. {@code Decoder.class} @return in the example above, the type parameter of {@code Decoder}. @throws IllegalStateException if {@code supertype} cannot be resolved into a parameterized type using {@code context}.
[ "Resolves", "the", "last", "type", "parameter", "of", "the", "parameterized", "{", "@code", "supertype", "}", "based", "on", "the", "{", "@code", "genericContext", "}", "into", "its", "upper", "bounds", ".", "<p", "/", ">", "Implementation", "copied", "from"...
train
https://github.com/OpenFeign/feign/blob/318fb0e955b8cfcf64f70d6aeea0ba5795f8a7eb/core/src/main/java/feign/Util.java#L219-L234
apereo/cas
support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/validator/token/BaseOAuth20TokenRequestValidator.java
BaseOAuth20TokenRequestValidator.isGrantTypeSupported
private static boolean isGrantTypeSupported(final String type, final OAuth20GrantTypes... expectedTypes) { """ Check the grant type against expected grant types. @param type the current grant type @param expectedTypes the expected grant types @return whether the grant type is supported """ LOGGER.debug("Grant type received: [{}]", type); for (val expectedType : expectedTypes) { if (OAuth20Utils.isGrantType(type, expectedType)) { return true; } } LOGGER.error("Unsupported grant type: [{}]", type); return false; }
java
private static boolean isGrantTypeSupported(final String type, final OAuth20GrantTypes... expectedTypes) { LOGGER.debug("Grant type received: [{}]", type); for (val expectedType : expectedTypes) { if (OAuth20Utils.isGrantType(type, expectedType)) { return true; } } LOGGER.error("Unsupported grant type: [{}]", type); return false; }
[ "private", "static", "boolean", "isGrantTypeSupported", "(", "final", "String", "type", ",", "final", "OAuth20GrantTypes", "...", "expectedTypes", ")", "{", "LOGGER", ".", "debug", "(", "\"Grant type received: [{}]\"", ",", "type", ")", ";", "for", "(", "val", "...
Check the grant type against expected grant types. @param type the current grant type @param expectedTypes the expected grant types @return whether the grant type is supported
[ "Check", "the", "grant", "type", "against", "expected", "grant", "types", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/validator/token/BaseOAuth20TokenRequestValidator.java#L41-L50
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.startsWith
public static boolean startsWith(byte[] bytes, byte[] prefix) { """ Return true if the byte array on the right is a prefix of the byte array on the left. """ return bytes != null && prefix != null && bytes.length >= prefix.length && LexicographicalComparerHolder.BEST_COMPARER. compareTo(bytes, 0, prefix.length, prefix, 0, prefix.length) == 0; }
java
public static boolean startsWith(byte[] bytes, byte[] prefix) { return bytes != null && prefix != null && bytes.length >= prefix.length && LexicographicalComparerHolder.BEST_COMPARER. compareTo(bytes, 0, prefix.length, prefix, 0, prefix.length) == 0; }
[ "public", "static", "boolean", "startsWith", "(", "byte", "[", "]", "bytes", ",", "byte", "[", "]", "prefix", ")", "{", "return", "bytes", "!=", "null", "&&", "prefix", "!=", "null", "&&", "bytes", ".", "length", ">=", "prefix", ".", "length", "&&", ...
Return true if the byte array on the right is a prefix of the byte array on the left.
[ "Return", "true", "if", "the", "byte", "array", "on", "the", "right", "is", "a", "prefix", "of", "the", "byte", "array", "on", "the", "left", "." ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L912-L917
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SynchronizationGenerators.java
SynchronizationGenerators.createMonitorContainer
public static InsnList createMonitorContainer(MarkerType markerType, LockVariables lockVars) { """ Generates instruction to that creates a new {@link LockState} object and saves it to the lockstate variable. @param markerType debug marker type @param lockVars variables for lock/synchpoint functionality @return instructions to push a new {@link LockState} object @throws NullPointerException if any argument is {@code null} @throws IllegalArgumentException if lock variables aren't set (the method doesn't contain any monitorenter/monitorexit instructions) """ Validate.notNull(markerType); Validate.notNull(lockVars); Variable lockStateVar = lockVars.getLockStateVar(); Validate.isTrue(lockStateVar != null); // extra sanity check, if no synch points this should be null return merge( debugMarker(markerType, "Creating lockstate"), construct(LOCKSTATE_INIT_METHOD), saveVar(lockStateVar) ); }
java
public static InsnList createMonitorContainer(MarkerType markerType, LockVariables lockVars) { Validate.notNull(markerType); Validate.notNull(lockVars); Variable lockStateVar = lockVars.getLockStateVar(); Validate.isTrue(lockStateVar != null); // extra sanity check, if no synch points this should be null return merge( debugMarker(markerType, "Creating lockstate"), construct(LOCKSTATE_INIT_METHOD), saveVar(lockStateVar) ); }
[ "public", "static", "InsnList", "createMonitorContainer", "(", "MarkerType", "markerType", ",", "LockVariables", "lockVars", ")", "{", "Validate", ".", "notNull", "(", "markerType", ")", ";", "Validate", ".", "notNull", "(", "lockVars", ")", ";", "Variable", "lo...
Generates instruction to that creates a new {@link LockState} object and saves it to the lockstate variable. @param markerType debug marker type @param lockVars variables for lock/synchpoint functionality @return instructions to push a new {@link LockState} object @throws NullPointerException if any argument is {@code null} @throws IllegalArgumentException if lock variables aren't set (the method doesn't contain any monitorenter/monitorexit instructions)
[ "Generates", "instruction", "to", "that", "creates", "a", "new", "{" ]
train
https://github.com/offbynull/coroutines/blob/b1b83c293945f53a2f63fca8f15a53e88b796bf5/instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/SynchronizationGenerators.java#L64-L76