repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
hibernate/hibernate-ogm
core/src/main/java/org/hibernate/ogm/loader/impl/OgmLoader.java
OgmLoader.loadCollection
public final void loadCollection( final SharedSessionContractImplementor session, final Serializable id, final Type type) throws HibernateException { if ( log.isDebugEnabled() ) { log.debug( "loading collection: " + MessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() ) ); } Serializable[] ids = new Serializable[]{id}; QueryParameters qp = new QueryParameters( new Type[]{type}, ids, ids ); doQueryAndInitializeNonLazyCollections( session, qp, OgmLoadingContext.EMPTY_CONTEXT, true ); log.debug( "done loading collection" ); }
java
public final void loadCollection( final SharedSessionContractImplementor session, final Serializable id, final Type type) throws HibernateException { if ( log.isDebugEnabled() ) { log.debug( "loading collection: " + MessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() ) ); } Serializable[] ids = new Serializable[]{id}; QueryParameters qp = new QueryParameters( new Type[]{type}, ids, ids ); doQueryAndInitializeNonLazyCollections( session, qp, OgmLoadingContext.EMPTY_CONTEXT, true ); log.debug( "done loading collection" ); }
[ "public", "final", "void", "loadCollection", "(", "final", "SharedSessionContractImplementor", "session", ",", "final", "Serializable", "id", ",", "final", "Type", "type", ")", "throws", "HibernateException", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")",...
Called by subclasses that initialize collections @param session the session @param id the collection identifier @param type collection type @throws HibernateException if an error occurs
[ "Called", "by", "subclasses", "that", "initialize", "collections" ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/loader/impl/OgmLoader.java#L232-L255
wcm-io/wcm-io-tooling
maven/skins/reflow-velocity-tools/src/main/java/io/wcm/maven/skins/reflow/velocity/URITool.java
URITool.relativizeLink
public static String relativizeLink(final String baseDirUri, final String link) { // taken from org.apache.maven.doxia.site.decoration.inheritance.DecorationModelInheritanceAssembler if (link == null || baseDirUri == null) { return link; } // this shouldn't be necessary, just to swallow malformed hrefs try { final URIPathDescriptor path = new URIPathDescriptor(baseDirUri, link); return path.relativizeLink().toString(); } catch (IllegalArgumentException e) { return link; } }
java
public static String relativizeLink(final String baseDirUri, final String link) { // taken from org.apache.maven.doxia.site.decoration.inheritance.DecorationModelInheritanceAssembler if (link == null || baseDirUri == null) { return link; } // this shouldn't be necessary, just to swallow malformed hrefs try { final URIPathDescriptor path = new URIPathDescriptor(baseDirUri, link); return path.relativizeLink().toString(); } catch (IllegalArgumentException e) { return link; } }
[ "public", "static", "String", "relativizeLink", "(", "final", "String", "baseDirUri", ",", "final", "String", "link", ")", "{", "// taken from org.apache.maven.doxia.site.decoration.inheritance.DecorationModelInheritanceAssembler", "if", "(", "link", "==", "null", "||", "ba...
Resolves the link as relative to the base dir URI. <p> Relativizes only absolute links, if the link has the same scheme, host and port as the base, it is made into a relative link as viewed from the base. </p> <p> This is the same method that's used to relativize project links in Maven site. </p> @param baseDirUri URI that will serve as the base to calculate the relative one @param link The link to relativize (make it relative to the base URI if possible) @return the relative link, if calculated, or the original link if not. @since 1.0
[ "Resolves", "the", "link", "as", "relative", "to", "the", "base", "dir", "URI", ".", "<p", ">", "Relativizes", "only", "absolute", "links", "if", "the", "link", "has", "the", "same", "scheme", "host", "and", "port", "as", "the", "base", "it", "is", "ma...
train
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/skins/reflow-velocity-tools/src/main/java/io/wcm/maven/skins/reflow/velocity/URITool.java#L67-L84
Stratio/bdt
src/main/java/com/stratio/qa/specs/DcosSpec.java
DcosSpec.serviceStatusCheck
@Then("^service '(.+?)' status in cluster '(.+?)' is '(suspended|running|deploying)'( in less than '(\\d+?)' seconds checking every '(\\d+?)' seconds)?") public void serviceStatusCheck(String service, String cluster, String status, String foo, Integer totalWait, Integer interval) throws Exception { String response; Integer i = 0; boolean matched; response = commonspec.retrieveServiceStatus(service, cluster); if (foo != null) { matched = status.matches(response); while (!matched && i < totalWait) { this.commonspec.getLogger().info("Service status not found yet after " + i + " seconds"); i = i + interval; response = commonspec.retrieveServiceStatus(service, cluster); matched = status.matches(response); } } assertThat(status).as("Expected status: " + status + " doesn't match obtained one: " + response).matches(response); }
java
@Then("^service '(.+?)' status in cluster '(.+?)' is '(suspended|running|deploying)'( in less than '(\\d+?)' seconds checking every '(\\d+?)' seconds)?") public void serviceStatusCheck(String service, String cluster, String status, String foo, Integer totalWait, Integer interval) throws Exception { String response; Integer i = 0; boolean matched; response = commonspec.retrieveServiceStatus(service, cluster); if (foo != null) { matched = status.matches(response); while (!matched && i < totalWait) { this.commonspec.getLogger().info("Service status not found yet after " + i + " seconds"); i = i + interval; response = commonspec.retrieveServiceStatus(service, cluster); matched = status.matches(response); } } assertThat(status).as("Expected status: " + status + " doesn't match obtained one: " + response).matches(response); }
[ "@", "Then", "(", "\"^service '(.+?)' status in cluster '(.+?)' is '(suspended|running|deploying)'( in less than '(\\\\d+?)' seconds checking every '(\\\\d+?)' seconds)?\"", ")", "public", "void", "serviceStatusCheck", "(", "String", "service", ",", "String", "cluster", ",", "String", ...
Check service status has value specified @param service name of the service to be checked @param cluster URI of the cluster @param status status expected @throws Exception exception *
[ "Check", "service", "status", "has", "value", "specified" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DcosSpec.java#L459-L479
goldmansachs/gs-collections
gs-collections-forkjoin/src/main/java/com/gs/collections/impl/forkjoin/FJIterate.java
FJIterate.forEach
public static <T> void forEach(Iterable<T> iterable, Procedure<? super T> procedure) { FJIterate.forEach(iterable, procedure, FJIterate.FORK_JOIN_POOL); }
java
public static <T> void forEach(Iterable<T> iterable, Procedure<? super T> procedure) { FJIterate.forEach(iterable, procedure, FJIterate.FORK_JOIN_POOL); }
[ "public", "static", "<", "T", ">", "void", "forEach", "(", "Iterable", "<", "T", ">", "iterable", ",", "Procedure", "<", "?", "super", "T", ">", "procedure", ")", "{", "FJIterate", ".", "forEach", "(", "iterable", ",", "procedure", ",", "FJIterate", "....
Iterate over the collection specified in parallel batches using default runtime parameter values. The {@code Procedure} used must be stateless, or use concurrent aware objects if they are to be shared. <p> e.g. <pre> {@code final ConcurrentMutableMap<Object, Boolean> chm = new ConcurrentHashMap<Object, Boolean>();} FJIterate.<b>forEach</b>(collection, new Procedure() { public void value(Object object) { chm.put(object, Boolean.TRUE); } }); </pre>
[ "Iterate", "over", "the", "collection", "specified", "in", "parallel", "batches", "using", "default", "runtime", "parameter", "values", ".", "The", "{" ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/gs-collections-forkjoin/src/main/java/com/gs/collections/impl/forkjoin/FJIterate.java#L259-L262
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/Expression.java
Expression.checkedCast
public Expression checkedCast(final Type target) { checkArgument( target.getSort() == Type.OBJECT, "cast targets must be reference types. (%s)", target.getClassName()); checkArgument( resultType().getSort() == Type.OBJECT, "you may only cast from reference types. (%s)", resultType().getClassName()); if (BytecodeUtils.isDefinitelyAssignableFrom(target, resultType())) { return this; } return new Expression(target, features()) { @Override protected void doGen(CodeBuilder adapter) { Expression.this.gen(adapter); // TODO(b/191662001) Remove this once we have fully switched the type // system over. Normally, we should just cast this result over, but in // the case of SoyString, there are temporarily two states (SanitizedContent == SoyString) // and (SanitizedContent != SoyString). This branch bails out to a runtime function that // effectively does the below but also optionally logs a warning. if (resultType().equals(BytecodeUtils.SOY_STRING_TYPE)) { MethodRef.RUNTIME_CHECK_SOY_STRING.invokeUnchecked(adapter); } else { adapter.checkCast(resultType()); } } }; }
java
public Expression checkedCast(final Type target) { checkArgument( target.getSort() == Type.OBJECT, "cast targets must be reference types. (%s)", target.getClassName()); checkArgument( resultType().getSort() == Type.OBJECT, "you may only cast from reference types. (%s)", resultType().getClassName()); if (BytecodeUtils.isDefinitelyAssignableFrom(target, resultType())) { return this; } return new Expression(target, features()) { @Override protected void doGen(CodeBuilder adapter) { Expression.this.gen(adapter); // TODO(b/191662001) Remove this once we have fully switched the type // system over. Normally, we should just cast this result over, but in // the case of SoyString, there are temporarily two states (SanitizedContent == SoyString) // and (SanitizedContent != SoyString). This branch bails out to a runtime function that // effectively does the below but also optionally logs a warning. if (resultType().equals(BytecodeUtils.SOY_STRING_TYPE)) { MethodRef.RUNTIME_CHECK_SOY_STRING.invokeUnchecked(adapter); } else { adapter.checkCast(resultType()); } } }; }
[ "public", "Expression", "checkedCast", "(", "final", "Type", "target", ")", "{", "checkArgument", "(", "target", ".", "getSort", "(", ")", "==", "Type", ".", "OBJECT", ",", "\"cast targets must be reference types. (%s)\"", ",", "target", ".", "getClassName", "(", ...
Returns an expression that performs a checked cast from the current type to the target type. @throws IllegalArgumentException if either type is not a reference type.
[ "Returns", "an", "expression", "that", "performs", "a", "checked", "cast", "from", "the", "current", "type", "to", "the", "target", "type", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Expression.java#L341-L369
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java
ElementsExceptionsFactory.newConfigurationException
public static ConfigurationException newConfigurationException(String message, Object... args) { return newConfigurationException(null, message, args); }
java
public static ConfigurationException newConfigurationException(String message, Object... args) { return newConfigurationException(null, message, args); }
[ "public", "static", "ConfigurationException", "newConfigurationException", "(", "String", "message", ",", "Object", "...", "args", ")", "{", "return", "newConfigurationException", "(", "null", ",", "message", ",", "args", ")", ";", "}" ]
Constructs and initializes a new {@link ConfigurationException} with the given {@link String message} formatted with the given {@link Object[] arguments}. @param message {@link String} describing the {@link ConfigurationException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link ConfigurationException} with the given {@link String message}. @see #newConfigurationException(Throwable, String, Object...) @see org.cp.elements.context.configure.ConfigurationException
[ "Constructs", "and", "initializes", "a", "new", "{", "@link", "ConfigurationException", "}", "with", "the", "given", "{", "@link", "String", "message", "}", "formatted", "with", "the", "given", "{", "@link", "Object", "[]", "arguments", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L123-L125
EdwardRaff/JSAT
JSAT/src/jsat/classifiers/linear/LinearBatch.java
LinearBatch.setLambda0
public void setLambda0(double lambda0) { if(lambda0 < 0 || Double.isNaN(lambda0) || Double.isInfinite(lambda0)) throw new IllegalArgumentException("Lambda0 must be non-negative, not " + lambda0); this.lambda0 = lambda0; }
java
public void setLambda0(double lambda0) { if(lambda0 < 0 || Double.isNaN(lambda0) || Double.isInfinite(lambda0)) throw new IllegalArgumentException("Lambda0 must be non-negative, not " + lambda0); this.lambda0 = lambda0; }
[ "public", "void", "setLambda0", "(", "double", "lambda0", ")", "{", "if", "(", "lambda0", "<", "0", "||", "Double", ".", "isNaN", "(", "lambda0", ")", "||", "Double", ".", "isInfinite", "(", "lambda0", ")", ")", "throw", "new", "IllegalArgumentException", ...
&lambda;<sub>0</sub> controls the L<sub>2</sub> regularization penalty. @param lambda0 the L<sub>2</sub> regularization penalty to use
[ "&lambda", ";", "<sub", ">", "0<", "/", "sub", ">", "controls", "the", "L<sub", ">", "2<", "/", "sub", ">", "regularization", "penalty", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/LinearBatch.java#L144-L149
pf4j/pf4j
pf4j/src/main/java/org/pf4j/util/StringUtils.java
StringUtils.addStart
public static String addStart(String str, String add) { if (isNullOrEmpty(add)) { return str; } if (isNullOrEmpty(str)) { return add; } if (!str.startsWith(add)) { return add + str; } return str; }
java
public static String addStart(String str, String add) { if (isNullOrEmpty(add)) { return str; } if (isNullOrEmpty(str)) { return add; } if (!str.startsWith(add)) { return add + str; } return str; }
[ "public", "static", "String", "addStart", "(", "String", "str", ",", "String", "add", ")", "{", "if", "(", "isNullOrEmpty", "(", "add", ")", ")", "{", "return", "str", ";", "}", "if", "(", "isNullOrEmpty", "(", "str", ")", ")", "{", "return", "add", ...
<p>Adds a substring only if the source string does not already start with the substring, otherwise returns the source string.</p> <p/> <p>A {@code null} source string will return {@code null}. An empty ("") source string will return the empty string. A {@code null} search string will return the source string.</p> <p/> <pre> StringUtils.addStart(null, *) = * StringUtils.addStart("", *) = * StringUtils.addStart(*, null) = * StringUtils.addStart("domain.com", "www.") = "www.domain.com" StringUtils.addStart("abc123", "abc") = "abc123" </pre> @param str the source String to search, may be null @param add the String to search for and add, may be null @return the substring with the string added if required
[ "<p", ">", "Adds", "a", "substring", "only", "if", "the", "source", "string", "does", "not", "already", "start", "with", "the", "substring", "otherwise", "returns", "the", "source", "string", ".", "<", "/", "p", ">", "<p", "/", ">", "<p", ">", "A", "...
train
https://github.com/pf4j/pf4j/blob/6dd7a6069f0e2fbd842c81e2c8c388918b88ea81/pf4j/src/main/java/org/pf4j/util/StringUtils.java#L60-L74
BioPAX/Paxtools
normalizer/src/main/java/org/biopax/paxtools/normalizer/MiriamLink.java
MiriamLink.checkRegExp
public static boolean checkRegExp(String identifier, String datatype) { Datatype dt = getDatatype(datatype); return Pattern.compile(dt.getPattern()).matcher(identifier).find(); }
java
public static boolean checkRegExp(String identifier, String datatype) { Datatype dt = getDatatype(datatype); return Pattern.compile(dt.getPattern()).matcher(identifier).find(); }
[ "public", "static", "boolean", "checkRegExp", "(", "String", "identifier", ",", "String", "datatype", ")", "{", "Datatype", "dt", "=", "getDatatype", "(", "datatype", ")", ";", "return", "Pattern", ".", "compile", "(", "dt", ".", "getPattern", "(", ")", ")...
Checks if the identifier given follows the regular expression of its data type (also provided). @param identifier internal identifier used by the data type @param datatype name, synonym or URI of a data type @return "true" if the identifier follows the regular expression, "false" otherwise @throws IllegalArgumentException when datatype not found
[ "Checks", "if", "the", "identifier", "given", "follows", "the", "regular", "expression", "of", "its", "data", "type", "(", "also", "provided", ")", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/normalizer/src/main/java/org/biopax/paxtools/normalizer/MiriamLink.java#L389-L393
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/util/type/TypeUtils.java
TypeUtils.convertToObject
public static Object convertToObject(String value, Class type, Locale locale) { BaseTypeConverter converter = lookupTypeConverter(type); assert converter != null; return converter.convertToObject(type, value, locale); }
java
public static Object convertToObject(String value, Class type, Locale locale) { BaseTypeConverter converter = lookupTypeConverter(type); assert converter != null; return converter.convertToObject(type, value, locale); }
[ "public", "static", "Object", "convertToObject", "(", "String", "value", ",", "Class", "type", ",", "Locale", "locale", ")", "{", "BaseTypeConverter", "converter", "=", "lookupTypeConverter", "(", "type", ")", ";", "assert", "converter", "!=", "null", ";", "re...
Convert an object from a String to the given type using the specified {@link java.util.Locale}. <p/> The locale is optionally used depending on the implementation of the {@link TypeConverter} that is used. @param value the String to convert @param type the type to which to convert the String @param locale the locale to use during conversion @return the Object result of converting the String to the type. @throws TypeConverterNotFoundException if a TypeConverter for the target type can not be found.
[ "Convert", "an", "object", "from", "a", "String", "to", "the", "given", "type", "using", "the", "specified", "{", "@link", "java", ".", "util", ".", "Locale", "}", ".", "<p", "/", ">", "The", "locale", "is", "optionally", "used", "depending", "on", "th...
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/util/type/TypeUtils.java#L96-L100
Alluxio/alluxio
core/base/src/main/java/alluxio/util/io/PathUtils.java
PathUtils.temporaryFileName
public static String temporaryFileName(long nonce, String path) { return path + String.format(TEMPORARY_SUFFIX_FORMAT, nonce); }
java
public static String temporaryFileName(long nonce, String path) { return path + String.format(TEMPORARY_SUFFIX_FORMAT, nonce); }
[ "public", "static", "String", "temporaryFileName", "(", "long", "nonce", ",", "String", "path", ")", "{", "return", "path", "+", "String", ".", "format", "(", "TEMPORARY_SUFFIX_FORMAT", ",", "nonce", ")", ";", "}" ]
Generates a deterministic temporary file name for the a path and a file id and a nonce. @param nonce a nonce token @param path a file path @return a deterministic temporary file name
[ "Generates", "a", "deterministic", "temporary", "file", "name", "for", "the", "a", "path", "and", "a", "file", "id", "and", "a", "nonce", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/base/src/main/java/alluxio/util/io/PathUtils.java#L245-L247
inkstand-io/scribble
scribble-jcr/src/main/java/io/inkstand/scribble/jcr/rules/ContentRepository.java
ContentRepository.getAccessControlList
protected AccessControlList getAccessControlList(Session session, final String path) throws RepositoryException { final AccessControlManager acm = session.getAccessControlManager(); AccessControlList acl; try { // get first applicable policy (for nodes w/o a policy) acl = (AccessControlList) acm.getApplicablePolicies(path).nextAccessControlPolicy(); } catch (NoSuchElementException e) { LOG.debug("no applicable policy found", e); // else node already has a policy, get that one acl = (AccessControlList) acm.getPolicies(path)[0]; } return acl; }
java
protected AccessControlList getAccessControlList(Session session, final String path) throws RepositoryException { final AccessControlManager acm = session.getAccessControlManager(); AccessControlList acl; try { // get first applicable policy (for nodes w/o a policy) acl = (AccessControlList) acm.getApplicablePolicies(path).nextAccessControlPolicy(); } catch (NoSuchElementException e) { LOG.debug("no applicable policy found", e); // else node already has a policy, get that one acl = (AccessControlList) acm.getPolicies(path)[0]; } return acl; }
[ "protected", "AccessControlList", "getAccessControlList", "(", "Session", "session", ",", "final", "String", "path", ")", "throws", "RepositoryException", "{", "final", "AccessControlManager", "acm", "=", "session", ".", "getAccessControlManager", "(", ")", ";", "Acce...
Retrieves the {@link AccessControlList} for a given path. If there is no ACL present, a new one will be created. @param session the current session that provides the {@link AccessControlManager} @param path the path for which the ACL should be retrieved. @return the access control list for the path @throws RepositoryException when the access control manager could not be retrieved or the ACLs of the specified path could not be obtained.
[ "Retrieves", "the", "{", "@link", "AccessControlList", "}", "for", "a", "given", "path", ".", "If", "there", "is", "no", "ACL", "present", "a", "new", "one", "will", "be", "created", "." ]
train
https://github.com/inkstand-io/scribble/blob/66e67553bad4b1ff817e1715fd1d3dd833406744/scribble-jcr/src/main/java/io/inkstand/scribble/jcr/rules/ContentRepository.java#L355-L369
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java
CommerceWarehousePersistenceImpl.findByG_A_P
@Override public List<CommerceWarehouse> findByG_A_P(long groupId, boolean active, boolean primary, int start, int end) { return findByG_A_P(groupId, active, primary, start, end, null); }
java
@Override public List<CommerceWarehouse> findByG_A_P(long groupId, boolean active, boolean primary, int start, int end) { return findByG_A_P(groupId, active, primary, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceWarehouse", ">", "findByG_A_P", "(", "long", "groupId", ",", "boolean", "active", ",", "boolean", "primary", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByG_A_P", "(", "groupId", ",", "a...
Returns a range of all the commerce warehouses where groupId = &#63; and active = &#63; and primary = &#63;. <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 CommerceWarehouseModelImpl}. 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 groupId the group ID @param active the active @param primary the primary @param start the lower bound of the range of commerce warehouses @param end the upper bound of the range of commerce warehouses (not inclusive) @return the range of matching commerce warehouses
[ "Returns", "a", "range", "of", "all", "the", "commerce", "warehouses", "where", "groupId", "=", "&#63", ";", "and", "active", "=", "&#63", ";", "and", "primary", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java#L2902-L2906
openengsb/openengsb
components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/performer/TransformationPerformer.java
TransformationPerformer.checkNeededValues
private void checkNeededValues(TransformationDescription description) { String message = "The TransformationDescription doesn't contain a %s. Description loading aborted"; if (description.getSourceModel().getModelClassName() == null) { throw new IllegalArgumentException(String.format(message, "source class")); } if (description.getTargetModel().getModelClassName() == null) { throw new IllegalArgumentException(String.format(message, "target class")); } String message2 = "The version string of the %s is not a correct version string. Description loading aborted"; try { Version.parseVersion(description.getSourceModel().getVersionString()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format(message2, "source class"), e); } try { Version.parseVersion(description.getTargetModel().getVersionString()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format(message2, "target class"), e); } }
java
private void checkNeededValues(TransformationDescription description) { String message = "The TransformationDescription doesn't contain a %s. Description loading aborted"; if (description.getSourceModel().getModelClassName() == null) { throw new IllegalArgumentException(String.format(message, "source class")); } if (description.getTargetModel().getModelClassName() == null) { throw new IllegalArgumentException(String.format(message, "target class")); } String message2 = "The version string of the %s is not a correct version string. Description loading aborted"; try { Version.parseVersion(description.getSourceModel().getVersionString()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format(message2, "source class"), e); } try { Version.parseVersion(description.getTargetModel().getVersionString()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format(message2, "target class"), e); } }
[ "private", "void", "checkNeededValues", "(", "TransformationDescription", "description", ")", "{", "String", "message", "=", "\"The TransformationDescription doesn't contain a %s. Description loading aborted\"", ";", "if", "(", "description", ".", "getSourceModel", "(", ")", ...
Does the checking of all necessary values of the TransformationDescription which are needed to process the description
[ "Does", "the", "checking", "of", "all", "necessary", "values", "of", "the", "TransformationDescription", "which", "are", "needed", "to", "process", "the", "description" ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/performer/TransformationPerformer.java#L57-L76
taskadapter/redmine-java-api
src/main/java/com/taskadapter/redmineapi/internal/Transport.java
Transport.getObjectsList
public <T> List<T> getObjectsList(Class<T> objectClass, Collection<? extends NameValuePair> params) throws RedmineException { final List<T> result = new ArrayList<>(); int offset = 0; Integer totalObjectsFoundOnServer; do { final List<NameValuePair> newParams = new ArrayList<>(params); newParams.add(new BasicNameValuePair("limit", String.valueOf(objectsPerPage))); newParams.add(new BasicNameValuePair("offset", String.valueOf(offset))); final ResultsWrapper<T> wrapper = getObjectsListNoPaging(objectClass, newParams); result.addAll(wrapper.getResults()); totalObjectsFoundOnServer = wrapper.getTotalFoundOnServer(); // Necessary for trackers. // TODO Alexey: is this still necessary for Redmine 2.x? if (totalObjectsFoundOnServer == null) { break; } if (!wrapper.hasSomeResults()) { break; } offset += wrapper.getResultsNumber(); } while (offset < totalObjectsFoundOnServer); return result; }
java
public <T> List<T> getObjectsList(Class<T> objectClass, Collection<? extends NameValuePair> params) throws RedmineException { final List<T> result = new ArrayList<>(); int offset = 0; Integer totalObjectsFoundOnServer; do { final List<NameValuePair> newParams = new ArrayList<>(params); newParams.add(new BasicNameValuePair("limit", String.valueOf(objectsPerPage))); newParams.add(new BasicNameValuePair("offset", String.valueOf(offset))); final ResultsWrapper<T> wrapper = getObjectsListNoPaging(objectClass, newParams); result.addAll(wrapper.getResults()); totalObjectsFoundOnServer = wrapper.getTotalFoundOnServer(); // Necessary for trackers. // TODO Alexey: is this still necessary for Redmine 2.x? if (totalObjectsFoundOnServer == null) { break; } if (!wrapper.hasSomeResults()) { break; } offset += wrapper.getResultsNumber(); } while (offset < totalObjectsFoundOnServer); return result; }
[ "public", "<", "T", ">", "List", "<", "T", ">", "getObjectsList", "(", "Class", "<", "T", ">", "objectClass", ",", "Collection", "<", "?", "extends", "NameValuePair", ">", "params", ")", "throws", "RedmineException", "{", "final", "List", "<", "T", ">", ...
Returns all objects found using the provided parameters. This method IGNORES "limit" and "offset" parameters and handles paging AUTOMATICALLY for you. Please use getObjectsListNoPaging() method if you want to control paging yourself with "limit" and "offset" parameters. @return objects list, never NULL @see #getObjectsListNoPaging(Class, Collection)
[ "Returns", "all", "objects", "found", "using", "the", "provided", "parameters", ".", "This", "method", "IGNORES", "limit", "and", "offset", "parameters", "and", "handles", "paging", "AUTOMATICALLY", "for", "you", ".", "Please", "use", "getObjectsListNoPaging", "()...
train
https://github.com/taskadapter/redmine-java-api/blob/0bb65f27ee806ec3bd4007e1641f3e996261a04e/src/main/java/com/taskadapter/redmineapi/internal/Transport.java#L448-L474
Harium/keel
src/main/java/com/harium/keel/catalano/math/distance/Distance.java
Distance.Chessboard
public static double Chessboard(double x1, double y1, double x2, double y2) { double dx = Math.abs(x1 - x2); double dy = Math.abs(y1 - y2); return Math.max(dx, dy); }
java
public static double Chessboard(double x1, double y1, double x2, double y2) { double dx = Math.abs(x1 - x2); double dy = Math.abs(y1 - y2); return Math.max(dx, dy); }
[ "public", "static", "double", "Chessboard", "(", "double", "x1", ",", "double", "y1", ",", "double", "x2", ",", "double", "y2", ")", "{", "double", "dx", "=", "Math", ".", "abs", "(", "x1", "-", "x2", ")", ";", "double", "dy", "=", "Math", ".", "...
Gets the Chessboard distance between two points. @param x1 X1 axis coordinate. @param y1 Y1 axis coordinate. @param x2 X2 axis coordinate. @param y2 Y2 axis coordinate. @return The Chessboard distance between x and y.
[ "Gets", "the", "Chessboard", "distance", "between", "two", "points", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L240-L245
phax/ph-pdf-layout
src/main/java/com/helger/pdflayout4/element/table/PLTable.java
PLTable.addRow
@Nonnull public PLTable addRow (@Nonnull final Iterable <? extends PLTableCell> aCells, @Nonnull final HeightSpec aHeight) { addAndReturnRow (aCells, aHeight); return this; }
java
@Nonnull public PLTable addRow (@Nonnull final Iterable <? extends PLTableCell> aCells, @Nonnull final HeightSpec aHeight) { addAndReturnRow (aCells, aHeight); return this; }
[ "@", "Nonnull", "public", "PLTable", "addRow", "(", "@", "Nonnull", "final", "Iterable", "<", "?", "extends", "PLTableCell", ">", "aCells", ",", "@", "Nonnull", "final", "HeightSpec", "aHeight", ")", "{", "addAndReturnRow", "(", "aCells", ",", "aHeight", ")"...
Add a new table row. All contained elements are added with the specified width in the constructor. <code>null</code> elements are represented as empty cells. @param aCells The cells to add. May not be <code>null</code>. @param aHeight Row height to be used. @return this
[ "Add", "a", "new", "table", "row", ".", "All", "contained", "elements", "are", "added", "with", "the", "specified", "width", "in", "the", "constructor", ".", "<code", ">", "null<", "/", "code", ">", "elements", "are", "represented", "as", "empty", "cells",...
train
https://github.com/phax/ph-pdf-layout/blob/777d9f3a131cbe8f592c0de1cf554084e541bb54/src/main/java/com/helger/pdflayout4/element/table/PLTable.java#L329-L334
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LoadBalancersInner.java
LoadBalancersInner.getByResourceGroupAsync
public Observable<LoadBalancerInner> getByResourceGroupAsync(String resourceGroupName, String loadBalancerName, String expand) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, loadBalancerName, expand).map(new Func1<ServiceResponse<LoadBalancerInner>, LoadBalancerInner>() { @Override public LoadBalancerInner call(ServiceResponse<LoadBalancerInner> response) { return response.body(); } }); }
java
public Observable<LoadBalancerInner> getByResourceGroupAsync(String resourceGroupName, String loadBalancerName, String expand) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, loadBalancerName, expand).map(new Func1<ServiceResponse<LoadBalancerInner>, LoadBalancerInner>() { @Override public LoadBalancerInner call(ServiceResponse<LoadBalancerInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "LoadBalancerInner", ">", "getByResourceGroupAsync", "(", "String", "resourceGroupName", ",", "String", "loadBalancerName", ",", "String", "expand", ")", "{", "return", "getByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",",...
Gets the specified load balancer. @param resourceGroupName The name of the resource group. @param loadBalancerName The name of the load balancer. @param expand Expands referenced resources. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the LoadBalancerInner object
[ "Gets", "the", "specified", "load", "balancer", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LoadBalancersInner.java#L383-L390
alibaba/jstorm
jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java
YarnRegistryViewForProviders.deleteChildren
public void deleteChildren(String path, boolean recursive) throws IOException { List<String> childNames = null; try { childNames = registryOperations.list(path); } catch (PathNotFoundException e) { return; } for (String childName : childNames) { String child = join(path, childName); registryOperations.delete(child, recursive); } }
java
public void deleteChildren(String path, boolean recursive) throws IOException { List<String> childNames = null; try { childNames = registryOperations.list(path); } catch (PathNotFoundException e) { return; } for (String childName : childNames) { String child = join(path, childName); registryOperations.delete(child, recursive); } }
[ "public", "void", "deleteChildren", "(", "String", "path", ",", "boolean", "recursive", ")", "throws", "IOException", "{", "List", "<", "String", ">", "childNames", "=", "null", ";", "try", "{", "childNames", "=", "registryOperations", ".", "list", "(", "pat...
Delete the children of a path -but not the path itself. It is not an error if the path does not exist @param path path to delete @param recursive flag to request recursive deletes @throws IOException IO problems
[ "Delete", "the", "children", "of", "a", "path", "-", "but", "not", "the", "path", "itself", ".", "It", "is", "not", "an", "error", "if", "the", "path", "does", "not", "exist" ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/registry/YarnRegistryViewForProviders.java#L254-L265
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/cdn/CdnClient.java
CdnClient.setDomainCacheFullUrl
public SetDomainCacheFullUrlResponse setDomainCacheFullUrl(SetDomainCacheFullUrlRequest request) { checkNotNull(request, "The parameter request should NOT be null."); InternalRequest internalRequest = createRequest(request, HttpMethodName.PUT, DOMAIN, request.getDomain(), "config"); internalRequest.addParameter("cacheFullUrl",""); this.attachRequestToBody(request, internalRequest); return invokeHttpClient(internalRequest, SetDomainCacheFullUrlResponse.class); }
java
public SetDomainCacheFullUrlResponse setDomainCacheFullUrl(SetDomainCacheFullUrlRequest request) { checkNotNull(request, "The parameter request should NOT be null."); InternalRequest internalRequest = createRequest(request, HttpMethodName.PUT, DOMAIN, request.getDomain(), "config"); internalRequest.addParameter("cacheFullUrl",""); this.attachRequestToBody(request, internalRequest); return invokeHttpClient(internalRequest, SetDomainCacheFullUrlResponse.class); }
[ "public", "SetDomainCacheFullUrlResponse", "setDomainCacheFullUrl", "(", "SetDomainCacheFullUrlRequest", "request", ")", "{", "checkNotNull", "(", "request", ",", "\"The parameter request should NOT be null.\"", ")", ";", "InternalRequest", "internalRequest", "=", "createRequest"...
Update cache policy of specified domain acceleration. @param request The request containing all of the options related to the update request. @return Result of the setDomainCacheFullUrl operation returned by the service.
[ "Update", "cache", "policy", "of", "specified", "domain", "acceleration", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/cdn/CdnClient.java#L384-L390
looly/hulu
src/main/java/com/xiaoleilu/hulu/Request.java
Request.getBean
public static <T> T getBean(Class<T> clazz, final boolean isIgnoreError) { final T bean = ServletUtil.toBean(getServletRequest(), clazz, isIgnoreError); //注入MultipartFormData 中的参数 final MultipartFormData multipart = getMultipart(); if(null != multipart){ final String beanName = StrUtil.lowerFirst(bean.getClass().getSimpleName()); BeanUtil.fillBean(bean, new ValueProvider<String>(){ @Override public Object value(String key, Type valueType) { String value = multipart.getParam(key); if (StrUtil.isEmpty(value)) { //使用类名前缀尝试查找值 value = multipart.getParam(beanName + StrUtil.DOT + key); if(StrUtil.isEmpty(value)){ //此处取得的值为空时跳过,包括null和"" value = null; } } return value; } @Override public boolean containsKey(String key) { return null != multipart.getParam(key); } }, CopyOptions.create().setIgnoreError(isIgnoreError)); } return bean; }
java
public static <T> T getBean(Class<T> clazz, final boolean isIgnoreError) { final T bean = ServletUtil.toBean(getServletRequest(), clazz, isIgnoreError); //注入MultipartFormData 中的参数 final MultipartFormData multipart = getMultipart(); if(null != multipart){ final String beanName = StrUtil.lowerFirst(bean.getClass().getSimpleName()); BeanUtil.fillBean(bean, new ValueProvider<String>(){ @Override public Object value(String key, Type valueType) { String value = multipart.getParam(key); if (StrUtil.isEmpty(value)) { //使用类名前缀尝试查找值 value = multipart.getParam(beanName + StrUtil.DOT + key); if(StrUtil.isEmpty(value)){ //此处取得的值为空时跳过,包括null和"" value = null; } } return value; } @Override public boolean containsKey(String key) { return null != multipart.getParam(key); } }, CopyOptions.create().setIgnoreError(isIgnoreError)); } return bean; }
[ "public", "static", "<", "T", ">", "T", "getBean", "(", "Class", "<", "T", ">", "clazz", ",", "final", "boolean", "isIgnoreError", ")", "{", "final", "T", "bean", "=", "ServletUtil", ".", "toBean", "(", "getServletRequest", "(", ")", ",", "clazz", ",",...
从Request中获得Bean对象 @param clazz Bean类,必须包含默认造方法 @param isIgnoreError 是否忽略注入错误 @return value Object
[ "从Request中获得Bean对象" ]
train
https://github.com/looly/hulu/blob/4072de684e2e2f28ac8a3a44c0d5a690b289ef28/src/main/java/com/xiaoleilu/hulu/Request.java#L447-L477
zaproxy/zaproxy
src/org/zaproxy/zap/extension/httpsessions/ExtensionHttpSessions.java
ExtensionHttpSessions.removeHttpSessionToken
public void removeHttpSessionToken(String site, String token) { // Add a default port if (!site.contains(":")) { site = site + (":80"); } HttpSessionTokensSet siteTokens = sessionTokens.get(site); if (siteTokens != null) { // Remove the token from the tokens associated with the site siteTokens.removeToken(token); if (siteTokens.isEmpty()) sessionTokens.remove(site); // Cleanup the existing sessions this.getHttpSessionsSite(site).cleanupSessionToken(token); } // If the token is a default session token, mark it as removed for the Site, so it will not // be detected again and added as a session token if (isDefaultSessionToken(token)) markRemovedDefaultSessionToken(site, token); if (log.isDebugEnabled()) { log.debug("Removed session token for site '" + site + "': " + token); } }
java
public void removeHttpSessionToken(String site, String token) { // Add a default port if (!site.contains(":")) { site = site + (":80"); } HttpSessionTokensSet siteTokens = sessionTokens.get(site); if (siteTokens != null) { // Remove the token from the tokens associated with the site siteTokens.removeToken(token); if (siteTokens.isEmpty()) sessionTokens.remove(site); // Cleanup the existing sessions this.getHttpSessionsSite(site).cleanupSessionToken(token); } // If the token is a default session token, mark it as removed for the Site, so it will not // be detected again and added as a session token if (isDefaultSessionToken(token)) markRemovedDefaultSessionToken(site, token); if (log.isDebugEnabled()) { log.debug("Removed session token for site '" + site + "': " + token); } }
[ "public", "void", "removeHttpSessionToken", "(", "String", "site", ",", "String", "token", ")", "{", "// Add a default port", "if", "(", "!", "site", ".", "contains", "(", "\":\"", ")", ")", "{", "site", "=", "site", "+", "(", "\":80\"", ")", ";", "}", ...
Removes a particular session token for a site. <p> All the existing sessions are cleaned up: <ul> <li>if there are no more session tokens, all session are deleted</li> <li>in every existing session, the value for the deleted token is removed</li> <li>if there is a session with no values for the remaining session tokens, it is deleted</li> <li>if, after deletion, there are duplicate sessions, they are merged</li> </ul> </p> @param site the site. This parameter has to be formed as defined in the {@link ExtensionHttpSessions} class documentation. However, if the protocol is missing, a default protocol of 80 is used. @param token the token
[ "Removes", "a", "particular", "session", "token", "for", "a", "site", ".", "<p", ">", "All", "the", "existing", "sessions", "are", "cleaned", "up", ":", "<ul", ">", "<li", ">", "if", "there", "are", "no", "more", "session", "tokens", "all", "session", ...
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/httpsessions/ExtensionHttpSessions.java#L417-L439
apache/reef
lang/java/reef-common/src/main/java/org/apache/reef/util/logging/LoggingScopeFactory.java
LoggingScopeFactory.getNewLoggingScope
public static LoggingScope getNewLoggingScope(final Level logLevel, final String msg) { return new LoggingScopeImpl(LOG, logLevel, msg); }
java
public static LoggingScope getNewLoggingScope(final Level logLevel, final String msg) { return new LoggingScopeImpl(LOG, logLevel, msg); }
[ "public", "static", "LoggingScope", "getNewLoggingScope", "(", "final", "Level", "logLevel", ",", "final", "String", "msg", ")", "{", "return", "new", "LoggingScopeImpl", "(", "LOG", ",", "logLevel", ",", "msg", ")", ";", "}" ]
Get a new instance of LoggingScope with specified log level. @param logLevel @param msg @return
[ "Get", "a", "new", "instance", "of", "LoggingScope", "with", "specified", "log", "level", "." ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-common/src/main/java/org/apache/reef/util/logging/LoggingScopeFactory.java#L82-L84
osglworks/java-tool
src/main/java/org/osgl/util/E.java
E.unexpectedIfNot
public static void unexpectedIfNot(boolean tester, String msg, Object... args) { unexpectedIf(!tester, msg, args); }
java
public static void unexpectedIfNot(boolean tester, String msg, Object... args) { unexpectedIf(!tester, msg, args); }
[ "public", "static", "void", "unexpectedIfNot", "(", "boolean", "tester", ",", "String", "msg", ",", "Object", "...", "args", ")", "{", "unexpectedIf", "(", "!", "tester", ",", "msg", ",", "args", ")", ";", "}" ]
Throws out a {@link UnexpectedException} with message and cause specified when `tester` is **not** evaluated to `true`. @param tester when `false` then throw out the exception. @param msg the error message format pattern. @param args the error message format arguments.
[ "Throws", "out", "a", "{", "@link", "UnexpectedException", "}", "with", "message", "and", "cause", "specified", "when", "tester", "is", "**", "not", "**", "evaluated", "to", "true", "." ]
train
https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/util/E.java#L240-L242
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/utils/BoUtils.java
BoUtils.fromJson
public static BaseBo fromJson(String json, ClassLoader classLoader) { return fromJson(json, BaseBo.class, classLoader); }
java
public static BaseBo fromJson(String json, ClassLoader classLoader) { return fromJson(json, BaseBo.class, classLoader); }
[ "public", "static", "BaseBo", "fromJson", "(", "String", "json", ",", "ClassLoader", "classLoader", ")", "{", "return", "fromJson", "(", "json", ",", "BaseBo", ".", "class", ",", "classLoader", ")", ";", "}" ]
De-serialize a BO from JSON string. @param json the JSON string obtained from {@link #toJson(BaseBo)} @param classLoader @return @since 0.6.0.3
[ "De", "-", "serialize", "a", "BO", "from", "JSON", "string", "." ]
train
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/utils/BoUtils.java#L95-L97
hibernate/hibernate-ogm
mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/MongoDBDialect.java
MongoDBDialect.getAssociationRows
private static Object getAssociationRows(Association association, AssociationKey key, AssociationContext associationContext) { boolean organizeByRowKey = DotPatternMapHelpers.organizeAssociationMapByRowKey( association, key, associationContext ); // transform map entries such as ( addressType='home', address_id=123) into the more // natural ( { 'home'=123 } if ( organizeByRowKey ) { String rowKeyColumn = organizeByRowKey ? key.getMetadata().getRowKeyIndexColumnNames()[0] : null; Document rows = new Document(); for ( RowKey rowKey : association.getKeys() ) { Document row = (Document) getAssociationRow( association.get( rowKey ), key ); String rowKeyValue = (String) row.remove( rowKeyColumn ); // if there is a single column on the value side left, unwrap it if ( row.keySet().size() == 1 ) { rows.put( rowKeyValue, DocumentUtil.toMap( row ).values().iterator().next() ); } else { rows.put( rowKeyValue, row ); } } return rows; } // non-map rows can be taken as is else { List<Object> rows = new ArrayList<>(); for ( RowKey rowKey : association.getKeys() ) { rows.add( getAssociationRow( association.get( rowKey ), key ) ); } return rows; } }
java
private static Object getAssociationRows(Association association, AssociationKey key, AssociationContext associationContext) { boolean organizeByRowKey = DotPatternMapHelpers.organizeAssociationMapByRowKey( association, key, associationContext ); // transform map entries such as ( addressType='home', address_id=123) into the more // natural ( { 'home'=123 } if ( organizeByRowKey ) { String rowKeyColumn = organizeByRowKey ? key.getMetadata().getRowKeyIndexColumnNames()[0] : null; Document rows = new Document(); for ( RowKey rowKey : association.getKeys() ) { Document row = (Document) getAssociationRow( association.get( rowKey ), key ); String rowKeyValue = (String) row.remove( rowKeyColumn ); // if there is a single column on the value side left, unwrap it if ( row.keySet().size() == 1 ) { rows.put( rowKeyValue, DocumentUtil.toMap( row ).values().iterator().next() ); } else { rows.put( rowKeyValue, row ); } } return rows; } // non-map rows can be taken as is else { List<Object> rows = new ArrayList<>(); for ( RowKey rowKey : association.getKeys() ) { rows.add( getAssociationRow( association.get( rowKey ), key ) ); } return rows; } }
[ "private", "static", "Object", "getAssociationRows", "(", "Association", "association", ",", "AssociationKey", "key", ",", "AssociationContext", "associationContext", ")", "{", "boolean", "organizeByRowKey", "=", "DotPatternMapHelpers", ".", "organizeAssociationMapByRowKey", ...
Returns the rows of the given association as to be stored in the database. The return value is one of the following: <ul> <li>A list of plain values such as {@code String}s, {@code int}s etc. in case there is exactly one row key column which is not part of the association key (in this case we don't need to persist the key name as it can be restored from the association key upon loading) or</li> <li>A list of {@code Document}s with keys/values for all row key columns which are not part of the association key</li> <li>A {@link Document} with a key for each entry in case the given association has exactly one row key column which is of type {@code String} (e.g. a hash map) and {@link DocumentStoreProperties#MAP_STORAGE} is not set to {@link MapStorageType#AS_LIST}. The map values will either be plain values (in case it's single values) or another {@code Document}. </ul>
[ "Returns", "the", "rows", "of", "the", "given", "association", "as", "to", "be", "stored", "in", "the", "database", ".", "The", "return", "value", "is", "one", "of", "the", "following", ":", "<ul", ">", "<li", ">", "A", "list", "of", "plain", "values",...
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/MongoDBDialect.java#L736-L771
keenon/loglinear
src/main/java/com/github/keenon/loglinear/model/GraphicalModel.java
GraphicalModel.addStaticFactor
public StaticFactor addStaticFactor(NDArrayDoubles staticFeatureTable, int[] neighborIndices) { assert (staticFeatureTable.getDimensions().length == neighborIndices.length); StaticFactor factor = new StaticFactor(staticFeatureTable, neighborIndices); factors.add(factor); return factor; }
java
public StaticFactor addStaticFactor(NDArrayDoubles staticFeatureTable, int[] neighborIndices) { assert (staticFeatureTable.getDimensions().length == neighborIndices.length); StaticFactor factor = new StaticFactor(staticFeatureTable, neighborIndices); factors.add(factor); return factor; }
[ "public", "StaticFactor", "addStaticFactor", "(", "NDArrayDoubles", "staticFeatureTable", ",", "int", "[", "]", "neighborIndices", ")", "{", "assert", "(", "staticFeatureTable", ".", "getDimensions", "(", ")", ".", "length", "==", "neighborIndices", ".", "length", ...
Creates an instantiated factor in this graph, with neighborIndices representing the neighbor variables by integer index. @param staticFeatureTable the feature table holding constant values for this factor @param neighborIndices the indices of the neighboring variables, in order @return a reference to the created factor. This can be safely ignored, as the factor is already saved in the model
[ "Creates", "an", "instantiated", "factor", "in", "this", "graph", "with", "neighborIndices", "representing", "the", "neighbor", "variables", "by", "integer", "index", "." ]
train
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/model/GraphicalModel.java#L535-L540
markhobson/hamcrest-compose
main/src/main/java/org/hobsoft/hamcrest/compose/ComposeMatchers.java
ComposeMatchers.hasFeatureValue
public static <T, U> Matcher<T> hasFeatureValue(Function<T, U> featureFunction, U featureValue) { return hasFeature(featureFunction, equalTo(featureValue)); }
java
public static <T, U> Matcher<T> hasFeatureValue(Function<T, U> featureFunction, U featureValue) { return hasFeature(featureFunction, equalTo(featureValue)); }
[ "public", "static", "<", "T", ",", "U", ">", "Matcher", "<", "T", ">", "hasFeatureValue", "(", "Function", "<", "T", ",", "U", ">", "featureFunction", ",", "U", "featureValue", ")", "{", "return", "hasFeature", "(", "featureFunction", ",", "equalTo", "("...
Returns a matcher that matches the specified feature value of an object. <p> For example: <pre> assertThat("ham", hasFeatureValue(String::length, 3)); </pre> <p> This is equivalent to {@code hasFeature(featureFunction, equalTo(featureValue))}. @param featureFunction a function to extract the feature from the object. The string representation of this function is used as the feature name for {@code describeTo} and {@code describeMismatch}. @param featureValue the feature value to match @param <T> the type of the object to be matched @param <U> the type of the feature to be matched @return the feature matcher
[ "Returns", "a", "matcher", "that", "matches", "the", "specified", "feature", "value", "of", "an", "object", ".", "<p", ">", "For", "example", ":", "<pre", ">", "assertThat", "(", "ham", "hasFeatureValue", "(", "String", "::", "length", "3", "))", ";", "<...
train
https://github.com/markhobson/hamcrest-compose/blob/83ca6a6bdee08340a73cb39c3d7a30ca9d37bce5/main/src/main/java/org/hobsoft/hamcrest/compose/ComposeMatchers.java#L236-L239
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/constraint/ChocoMapper.java
ChocoMapper.mapConstraint
public void mapConstraint(Class<? extends Constraint> c, Class<? extends ChocoConstraint> cc) { constraints.put(c, cc); }
java
public void mapConstraint(Class<? extends Constraint> c, Class<? extends ChocoConstraint> cc) { constraints.put(c, cc); }
[ "public", "void", "mapConstraint", "(", "Class", "<", "?", "extends", "Constraint", ">", "c", ",", "Class", "<", "?", "extends", "ChocoConstraint", ">", "cc", ")", "{", "constraints", ".", "put", "(", "c", ",", "cc", ")", ";", "}" ]
Register a mapping between an api-side constraint and its choco implementation. It is expected from the implementation to exhibit a constructor that takes the api-side constraint as argument. @param c the api-side constraint @param cc the choco implementation @throws IllegalArgumentException if there is no suitable constructor for the choco implementation
[ "Register", "a", "mapping", "between", "an", "api", "-", "side", "constraint", "and", "its", "choco", "implementation", ".", "It", "is", "expected", "from", "the", "implementation", "to", "exhibit", "a", "constructor", "that", "takes", "the", "api", "-", "si...
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/constraint/ChocoMapper.java#L140-L142
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/FileSystem.java
FileSystem.listLocatedStatus
@Deprecated public RemoteIterator<LocatedFileStatus> listLocatedStatus(final Path f, final PathFilter filter) throws FileNotFoundException, IOException { return new RemoteIterator<LocatedFileStatus>() { private final FileStatus[] stats; private int i = 0; { // initializer stats = listStatus(f, filter); if (stats == null) { throw new FileNotFoundException( "File " + f + " does not exist."); } } @Override public boolean hasNext() { return i<stats.length; } @Override public LocatedFileStatus next() throws IOException { if (!hasNext()) { throw new NoSuchElementException("No more entry in " + f); } FileStatus result = stats[i++]; BlockLocation[] locs = result.isDir() ? null : getFileBlockLocations(result, 0, result.getLen()); return new LocatedFileStatus(result, locs); } }; }
java
@Deprecated public RemoteIterator<LocatedFileStatus> listLocatedStatus(final Path f, final PathFilter filter) throws FileNotFoundException, IOException { return new RemoteIterator<LocatedFileStatus>() { private final FileStatus[] stats; private int i = 0; { // initializer stats = listStatus(f, filter); if (stats == null) { throw new FileNotFoundException( "File " + f + " does not exist."); } } @Override public boolean hasNext() { return i<stats.length; } @Override public LocatedFileStatus next() throws IOException { if (!hasNext()) { throw new NoSuchElementException("No more entry in " + f); } FileStatus result = stats[i++]; BlockLocation[] locs = result.isDir() ? null : getFileBlockLocations(result, 0, result.getLen()); return new LocatedFileStatus(result, locs); } }; }
[ "@", "Deprecated", "public", "RemoteIterator", "<", "LocatedFileStatus", ">", "listLocatedStatus", "(", "final", "Path", "f", ",", "final", "PathFilter", "filter", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "return", "new", "RemoteIterator", "<...
Listing a directory The returned results include its block location if it is a file The results are filtered by the given path filter @param f a path @param filter a path filter @return an iterator that traverses statuses of the files/directories in the given path @throws FileNotFoundException if <code>f</code> does not exist @throws IOException if any I/O error occurred
[ "Listing", "a", "directory", "The", "returned", "results", "include", "its", "block", "location", "if", "it", "is", "a", "file", "The", "results", "are", "filtered", "by", "the", "given", "path", "filter" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FileSystem.java#L1059-L1090
paypal/SeLion
client/src/main/java/com/paypal/selion/internal/platform/grid/AbstractBaseLocalServerComponent.java
AbstractBaseLocalServerComponent.waitForComponentToComeUp
private void waitForComponentToComeUp() { LOGGER.entering(); for (int i = 0; i < 60; i++) { try { // Sleep for 3 seconds. Thread.sleep(1000); } catch (InterruptedException e) { throw new IllegalStateException(e.getMessage(), e); } if (getLauncher().isRunning()) { LOGGER.exiting(); return; } } throw new IllegalStateException(String.format("%s can not be contacted.", getLocalServerComponent().getClass() .getSimpleName())); }
java
private void waitForComponentToComeUp() { LOGGER.entering(); for (int i = 0; i < 60; i++) { try { // Sleep for 3 seconds. Thread.sleep(1000); } catch (InterruptedException e) { throw new IllegalStateException(e.getMessage(), e); } if (getLauncher().isRunning()) { LOGGER.exiting(); return; } } throw new IllegalStateException(String.format("%s can not be contacted.", getLocalServerComponent().getClass() .getSimpleName())); }
[ "private", "void", "waitForComponentToComeUp", "(", ")", "{", "LOGGER", ".", "entering", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "60", ";", "i", "++", ")", "{", "try", "{", "// Sleep for 3 seconds.", "Thread", ".", "sleep", "(...
Checks component has come up every 3 seconds. Waits for the component for a maximum of 60 seconds. Throws an {@link IllegalStateException} if the component can not be contacted
[ "Checks", "component", "has", "come", "up", "every", "3", "seconds", ".", "Waits", "for", "the", "component", "for", "a", "maximum", "of", "60", "seconds", ".", "Throws", "an", "{" ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/client/src/main/java/com/paypal/selion/internal/platform/grid/AbstractBaseLocalServerComponent.java#L157-L173
apptentive/apptentive-android
apptentive/src/main/java/com/apptentive/android/sdk/notifications/ApptentiveNotificationCenter.java
ApptentiveNotificationCenter.postNotification
public synchronized void postNotification(final String name, Object... args) { postNotification(name, ObjectUtils.toMap(args)); }
java
public synchronized void postNotification(final String name, Object... args) { postNotification(name, ObjectUtils.toMap(args)); }
[ "public", "synchronized", "void", "postNotification", "(", "final", "String", "name", ",", "Object", "...", "args", ")", "{", "postNotification", "(", "name", ",", "ObjectUtils", ".", "toMap", "(", "args", ")", ")", ";", "}" ]
Creates a notification with a given name and user info and posts it to the receiver.
[ "Creates", "a", "notification", "with", "a", "given", "name", "and", "user", "info", "and", "posts", "it", "to", "the", "receiver", "." ]
train
https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/notifications/ApptentiveNotificationCenter.java#L93-L95
Jasig/uPortal
uPortal-tools/src/main/java/org/apereo/portal/version/VersionUtils.java
VersionUtils.getMostSpecificMatchingField
public static Version.Field getMostSpecificMatchingField(Version v1, Version v2) { if (v1.getMajor() != v2.getMajor()) { return null; } if (v1.getMinor() != v2.getMinor()) { return Version.Field.MAJOR; } if (v1.getPatch() != v2.getPatch()) { return Version.Field.MINOR; } final Integer l1 = v1.getLocal(); final Integer l2 = v2.getLocal(); if (l1 != l2 && (l1 == null || l2 == null || !l1.equals(l2))) { return Version.Field.PATCH; } return Version.Field.LOCAL; }
java
public static Version.Field getMostSpecificMatchingField(Version v1, Version v2) { if (v1.getMajor() != v2.getMajor()) { return null; } if (v1.getMinor() != v2.getMinor()) { return Version.Field.MAJOR; } if (v1.getPatch() != v2.getPatch()) { return Version.Field.MINOR; } final Integer l1 = v1.getLocal(); final Integer l2 = v2.getLocal(); if (l1 != l2 && (l1 == null || l2 == null || !l1.equals(l2))) { return Version.Field.PATCH; } return Version.Field.LOCAL; }
[ "public", "static", "Version", ".", "Field", "getMostSpecificMatchingField", "(", "Version", "v1", ",", "Version", "v2", ")", "{", "if", "(", "v1", ".", "getMajor", "(", ")", "!=", "v2", ".", "getMajor", "(", ")", ")", "{", "return", "null", ";", "}", ...
Determine how much of two versions match. Returns null if the versions do not match at all. @return null for no match or the name of the most specific field that matches.
[ "Determine", "how", "much", "of", "two", "versions", "match", ".", "Returns", "null", "if", "the", "versions", "do", "not", "match", "at", "all", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-tools/src/main/java/org/apereo/portal/version/VersionUtils.java#L68-L88
undertow-io/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
HttpServerExchange.setRequestURI
public HttpServerExchange setRequestURI(final String requestURI, boolean containsHost) { this.requestURI = requestURI; if (containsHost) { this.state |= FLAG_URI_CONTAINS_HOST; } else { this.state &= ~FLAG_URI_CONTAINS_HOST; } return this; }
java
public HttpServerExchange setRequestURI(final String requestURI, boolean containsHost) { this.requestURI = requestURI; if (containsHost) { this.state |= FLAG_URI_CONTAINS_HOST; } else { this.state &= ~FLAG_URI_CONTAINS_HOST; } return this; }
[ "public", "HttpServerExchange", "setRequestURI", "(", "final", "String", "requestURI", ",", "boolean", "containsHost", ")", "{", "this", ".", "requestURI", "=", "requestURI", ";", "if", "(", "containsHost", ")", "{", "this", ".", "state", "|=", "FLAG_URI_CONTAIN...
Sets the request URI @param requestURI The new request URI @param containsHost If this is true the request URI contains the host part
[ "Sets", "the", "request", "URI" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L466-L474
Azure/azure-sdk-for-java
network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/LoadBalancerProbesInner.java
LoadBalancerProbesInner.listAsync
public Observable<Page<ProbeInner>> listAsync(final String resourceGroupName, final String loadBalancerName) { return listWithServiceResponseAsync(resourceGroupName, loadBalancerName) .map(new Func1<ServiceResponse<Page<ProbeInner>>, Page<ProbeInner>>() { @Override public Page<ProbeInner> call(ServiceResponse<Page<ProbeInner>> response) { return response.body(); } }); }
java
public Observable<Page<ProbeInner>> listAsync(final String resourceGroupName, final String loadBalancerName) { return listWithServiceResponseAsync(resourceGroupName, loadBalancerName) .map(new Func1<ServiceResponse<Page<ProbeInner>>, Page<ProbeInner>>() { @Override public Page<ProbeInner> call(ServiceResponse<Page<ProbeInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "ProbeInner", ">", ">", "listAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "loadBalancerName", ")", "{", "return", "listWithServiceResponseAsync", "(", "resourceGroupName", ",", "loadBalancerName...
Gets all the load balancer probes. @param resourceGroupName The name of the resource group. @param loadBalancerName The name of the load balancer. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ProbeInner&gt; object
[ "Gets", "all", "the", "load", "balancer", "probes", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/LoadBalancerProbesInner.java#L123-L131
RuedigerMoeller/kontraktor
src/main/java/org/nustaq/kontraktor/remoting/base/RemoteRefPolling.java
RemoteRefPolling.run
public void run() { pollThread = Thread.currentThread(); if ( underway ) return; underway = true; try { int count = 1; while( count > 0 ) { // as long there are messages, keep sending them count = onePoll(); if ( sendJobs.size() > 0 ) { if ( count > 0 ) { int debug =1; } else { if ( remoteRefCounter == 0 ) // no remote actors registered { Actor.current().delayed(100, this); // backoff massively } else { Actor.current().delayed(1, this); // backoff a bit (remoteactors present, no messages) } } } else { // no schedule entries (== no clients) Actor.current().delayed(100, this ); } } } finally { underway = false; } }
java
public void run() { pollThread = Thread.currentThread(); if ( underway ) return; underway = true; try { int count = 1; while( count > 0 ) { // as long there are messages, keep sending them count = onePoll(); if ( sendJobs.size() > 0 ) { if ( count > 0 ) { int debug =1; } else { if ( remoteRefCounter == 0 ) // no remote actors registered { Actor.current().delayed(100, this); // backoff massively } else { Actor.current().delayed(1, this); // backoff a bit (remoteactors present, no messages) } } } else { // no schedule entries (== no clients) Actor.current().delayed(100, this ); } } } finally { underway = false; } }
[ "public", "void", "run", "(", ")", "{", "pollThread", "=", "Thread", ".", "currentThread", "(", ")", ";", "if", "(", "underway", ")", "return", ";", "underway", "=", "true", ";", "try", "{", "int", "count", "=", "1", ";", "while", "(", "count", ">"...
counts active remote refs, if none backoff remoteref polling massively eats cpu
[ "counts", "active", "remote", "refs", "if", "none", "backoff", "remoteref", "polling", "massively", "eats", "cpu" ]
train
https://github.com/RuedigerMoeller/kontraktor/blob/d5f3817f9476f3786187b8ef00400b7a4f25a404/src/main/java/org/nustaq/kontraktor/remoting/base/RemoteRefPolling.java#L83-L112
hibernate/hibernate-ogm
neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/remote/http/dialect/impl/HttpNeo4jSequenceGenerator.java
HttpNeo4jSequenceGenerator.createSequencesConstraintsStatements
private void createSequencesConstraintsStatements(Statements statements, Iterable<Sequence> sequences) { Statement statement = createUniqueConstraintStatement( SEQUENCE_NAME_PROPERTY, NodeLabel.SEQUENCE.name() ); statements.addStatement( statement ); }
java
private void createSequencesConstraintsStatements(Statements statements, Iterable<Sequence> sequences) { Statement statement = createUniqueConstraintStatement( SEQUENCE_NAME_PROPERTY, NodeLabel.SEQUENCE.name() ); statements.addStatement( statement ); }
[ "private", "void", "createSequencesConstraintsStatements", "(", "Statements", "statements", ",", "Iterable", "<", "Sequence", ">", "sequences", ")", "{", "Statement", "statement", "=", "createUniqueConstraintStatement", "(", "SEQUENCE_NAME_PROPERTY", ",", "NodeLabel", "."...
Create the sequence nodes setting the initial value if the node does not exist already. <p> All nodes are created inside the same transaction.
[ "Create", "the", "sequence", "nodes", "setting", "the", "initial", "value", "if", "the", "node", "does", "not", "exist", "already", ".", "<p", ">", "All", "nodes", "are", "created", "inside", "the", "same", "transaction", "." ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/remote/http/dialect/impl/HttpNeo4jSequenceGenerator.java#L74-L77
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/storage/DefaultDOManager.java
DefaultDOManager.populateDC
private static void populateDC(Context ctx, DigitalObject obj, DOWriter w, Date nowUTC) throws IOException, ServerException { logger.debug("Adding/Checking default DC datastream"); Datastream dc = w.GetDatastream("DC", null); DCFields dcf; XMLDatastreamProcessor dcxml = null; if (dc == null) { dcxml = new XMLDatastreamProcessor("DC"); dc = dcxml.getDatastream(); //dc.DSMDClass=DatastreamXMLMetadata.DESCRIPTIVE; dc.DatastreamID = "DC"; dc.DSVersionID = "DC1.0"; //dc.DSControlGrp = "X"; set by XMLDatastreamProcessor instead dc.DSCreateDT = nowUTC; dc.DSLabel = "Dublin Core Record for this object"; dc.DSMIME = "text/xml"; dc.DSFormatURI = OAI_DC2_0.uri; dc.DSSize = 0; dc.DSState = "A"; dc.DSVersionable = true; dcf = new DCFields(); if (obj.getLabel() != null && !obj.getLabel().isEmpty()) { dcf.titles().add(new DCField(obj.getLabel())); } w.addDatastream(dc, dc.DSVersionable); } else { dcxml = new XMLDatastreamProcessor(dc); // note: context may be required to get through authz as content // could be filesystem file (or URL) dcf = new DCFields(dc.getContentStream(ctx)); } // set the value of the dc datastream according to what's in the // DCFields object // ensure one of the dc:identifiers is the pid ByteArrayOutputStream bytes = new ByteArrayOutputStream(512); PrintWriter out = new PrintWriter(new OutputStreamWriter(bytes, Charset.forName("UTF-8"))); dcf.getAsXML(obj.getPid(), out); out.close(); dcxml.setXMLContent(bytes.toByteArray()); }
java
private static void populateDC(Context ctx, DigitalObject obj, DOWriter w, Date nowUTC) throws IOException, ServerException { logger.debug("Adding/Checking default DC datastream"); Datastream dc = w.GetDatastream("DC", null); DCFields dcf; XMLDatastreamProcessor dcxml = null; if (dc == null) { dcxml = new XMLDatastreamProcessor("DC"); dc = dcxml.getDatastream(); //dc.DSMDClass=DatastreamXMLMetadata.DESCRIPTIVE; dc.DatastreamID = "DC"; dc.DSVersionID = "DC1.0"; //dc.DSControlGrp = "X"; set by XMLDatastreamProcessor instead dc.DSCreateDT = nowUTC; dc.DSLabel = "Dublin Core Record for this object"; dc.DSMIME = "text/xml"; dc.DSFormatURI = OAI_DC2_0.uri; dc.DSSize = 0; dc.DSState = "A"; dc.DSVersionable = true; dcf = new DCFields(); if (obj.getLabel() != null && !obj.getLabel().isEmpty()) { dcf.titles().add(new DCField(obj.getLabel())); } w.addDatastream(dc, dc.DSVersionable); } else { dcxml = new XMLDatastreamProcessor(dc); // note: context may be required to get through authz as content // could be filesystem file (or URL) dcf = new DCFields(dc.getContentStream(ctx)); } // set the value of the dc datastream according to what's in the // DCFields object // ensure one of the dc:identifiers is the pid ByteArrayOutputStream bytes = new ByteArrayOutputStream(512); PrintWriter out = new PrintWriter(new OutputStreamWriter(bytes, Charset.forName("UTF-8"))); dcf.getAsXML(obj.getPid(), out); out.close(); dcxml.setXMLContent(bytes.toByteArray()); }
[ "private", "static", "void", "populateDC", "(", "Context", "ctx", ",", "DigitalObject", "obj", ",", "DOWriter", "w", ",", "Date", "nowUTC", ")", "throws", "IOException", ",", "ServerException", "{", "logger", ".", "debug", "(", "\"Adding/Checking default DC datast...
Adds a minimal DC datastream if one isn't already present. If there is already a DC datastream, ensure one of the dc:identifier values is the PID of the object.
[ "Adds", "a", "minimal", "DC", "datastream", "if", "one", "isn", "t", "already", "present", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/storage/DefaultDOManager.java#L1060-L1100
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/transform/description/AttributeTransformationDescription.java
AttributeTransformationDescription.rejectAttributes
void rejectAttributes(RejectedAttributesLogContext rejectedAttributes, ModelNode attributeValue) { for (RejectAttributeChecker checker : checks) { rejectedAttributes.checkAttribute(checker, name, attributeValue); } }
java
void rejectAttributes(RejectedAttributesLogContext rejectedAttributes, ModelNode attributeValue) { for (RejectAttributeChecker checker : checks) { rejectedAttributes.checkAttribute(checker, name, attributeValue); } }
[ "void", "rejectAttributes", "(", "RejectedAttributesLogContext", "rejectedAttributes", ",", "ModelNode", "attributeValue", ")", "{", "for", "(", "RejectAttributeChecker", "checker", ":", "checks", ")", "{", "rejectedAttributes", ".", "checkAttribute", "(", "checker", ",...
Checks attributes for rejection @param rejectedAttributes gathers information about failed attributes @param attributeValue the attribute value
[ "Checks", "attributes", "for", "rejection" ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/transform/description/AttributeTransformationDescription.java#L90-L94
buschmais/jqa-javaee6-plugin
src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java
WebXmlScannerPlugin.createParamValue
private ParamValueDescriptor createParamValue(ParamValueType paramValueType, Store store) { ParamValueDescriptor paramValueDescriptor = store.create(ParamValueDescriptor.class); for (DescriptionType descriptionType : paramValueType.getDescription()) { DescriptionDescriptor descriptionDescriptor = XmlDescriptorHelper.createDescription(descriptionType, store); paramValueDescriptor.getDescriptions().add(descriptionDescriptor); } paramValueDescriptor.setName(paramValueType.getParamName().getValue()); XsdStringType paramValue = paramValueType.getParamValue(); if (paramValue != null) { paramValueDescriptor.setValue(paramValue.getValue()); } return paramValueDescriptor; }
java
private ParamValueDescriptor createParamValue(ParamValueType paramValueType, Store store) { ParamValueDescriptor paramValueDescriptor = store.create(ParamValueDescriptor.class); for (DescriptionType descriptionType : paramValueType.getDescription()) { DescriptionDescriptor descriptionDescriptor = XmlDescriptorHelper.createDescription(descriptionType, store); paramValueDescriptor.getDescriptions().add(descriptionDescriptor); } paramValueDescriptor.setName(paramValueType.getParamName().getValue()); XsdStringType paramValue = paramValueType.getParamValue(); if (paramValue != null) { paramValueDescriptor.setValue(paramValue.getValue()); } return paramValueDescriptor; }
[ "private", "ParamValueDescriptor", "createParamValue", "(", "ParamValueType", "paramValueType", ",", "Store", "store", ")", "{", "ParamValueDescriptor", "paramValueDescriptor", "=", "store", ".", "create", "(", "ParamValueDescriptor", ".", "class", ")", ";", "for", "(...
Create a param value descriptor. @param paramValueType The XML param value type. @param store The store. @return The param value descriptor.
[ "Create", "a", "param", "value", "descriptor", "." ]
train
https://github.com/buschmais/jqa-javaee6-plugin/blob/f5776604d9255206807e5aca90b8767bde494e14/src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java#L458-L470
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/core/QueryReferenceBroker.java
QueryReferenceBroker.getFKQueryMtoN
private QueryByCriteria getFKQueryMtoN(Object obj, ClassDescriptor cld, CollectionDescriptor cod) { ValueContainer[] values = pb.serviceBrokerHelper().getKeyValues(cld, obj); Object[] thisClassFks = cod.getFksToThisClass(); Object[] itemClassFks = cod.getFksToItemClass(); ClassDescriptor refCld = pb.getClassDescriptor(cod.getItemClass()); Criteria criteria = new Criteria(); for (int i = 0; i < thisClassFks.length; i++) { criteria.addEqualTo(cod.getIndirectionTable() + "." + thisClassFks[i], values[i].getValue()); } for (int i = 0; i < itemClassFks.length; i++) { criteria.addEqualToField(cod.getIndirectionTable() + "." + itemClassFks[i], refCld.getPkFields()[i].getAttributeName()); } return QueryFactory.newQuery(refCld.getClassOfObject(), cod.getIndirectionTable(), criteria); }
java
private QueryByCriteria getFKQueryMtoN(Object obj, ClassDescriptor cld, CollectionDescriptor cod) { ValueContainer[] values = pb.serviceBrokerHelper().getKeyValues(cld, obj); Object[] thisClassFks = cod.getFksToThisClass(); Object[] itemClassFks = cod.getFksToItemClass(); ClassDescriptor refCld = pb.getClassDescriptor(cod.getItemClass()); Criteria criteria = new Criteria(); for (int i = 0; i < thisClassFks.length; i++) { criteria.addEqualTo(cod.getIndirectionTable() + "." + thisClassFks[i], values[i].getValue()); } for (int i = 0; i < itemClassFks.length; i++) { criteria.addEqualToField(cod.getIndirectionTable() + "." + itemClassFks[i], refCld.getPkFields()[i].getAttributeName()); } return QueryFactory.newQuery(refCld.getClassOfObject(), cod.getIndirectionTable(), criteria); }
[ "private", "QueryByCriteria", "getFKQueryMtoN", "(", "Object", "obj", ",", "ClassDescriptor", "cld", ",", "CollectionDescriptor", "cod", ")", "{", "ValueContainer", "[", "]", "values", "=", "pb", ".", "serviceBrokerHelper", "(", ")", ".", "getKeyValues", "(", "c...
Get Foreign key query for m:n <br> supports UNIDIRECTIONAL m:n using QueryByMtoNCriteria @return org.apache.ojb.broker.query.QueryByCriteria @param obj the owner of the relationship @param cld the ClassDescriptor for the owner @param cod the CollectionDescriptor
[ "Get", "Foreign", "key", "query", "for", "m", ":", "n", "<br", ">", "supports", "UNIDIRECTIONAL", "m", ":", "n", "using", "QueryByMtoNCriteria" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/QueryReferenceBroker.java#L865-L884
Metatavu/edelphi
edelphi/src/main/java/fi/metatavu/edelphi/utils/MaterialUtils.java
MaterialUtils.findLocalDocumentByParentAndUrlName
public static LocalDocument findLocalDocumentByParentAndUrlName(Folder parentFolder, String urlName) { ResourceDAO resourceDAO = new ResourceDAO(); Resource resource = resourceDAO.findByUrlNameAndParentFolder(urlName, parentFolder); if (resource instanceof LocalDocument) { return (LocalDocument) resource; } return null; }
java
public static LocalDocument findLocalDocumentByParentAndUrlName(Folder parentFolder, String urlName) { ResourceDAO resourceDAO = new ResourceDAO(); Resource resource = resourceDAO.findByUrlNameAndParentFolder(urlName, parentFolder); if (resource instanceof LocalDocument) { return (LocalDocument) resource; } return null; }
[ "public", "static", "LocalDocument", "findLocalDocumentByParentAndUrlName", "(", "Folder", "parentFolder", ",", "String", "urlName", ")", "{", "ResourceDAO", "resourceDAO", "=", "new", "ResourceDAO", "(", ")", ";", "Resource", "resource", "=", "resourceDAO", ".", "f...
Returns local document by parent folder and URL name @param parentFolder parent folder @param urlName URL name @return Document or null if not found
[ "Returns", "local", "document", "by", "parent", "folder", "and", "URL", "name" ]
train
https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/utils/MaterialUtils.java#L109-L118
jayantk/jklol
src/com/jayantkrish/jklol/models/parametric/ParametricFactorGraphBuilder.java
ParametricFactorGraphBuilder.addUnreplicatedFactor
public void addUnreplicatedFactor(String factorName, ParametricFactor factor) { super.addUnreplicatedFactor(factorName, factor, factor.getVars()); }
java
public void addUnreplicatedFactor(String factorName, ParametricFactor factor) { super.addUnreplicatedFactor(factorName, factor, factor.getVars()); }
[ "public", "void", "addUnreplicatedFactor", "(", "String", "factorName", ",", "ParametricFactor", "factor", ")", "{", "super", ".", "addUnreplicatedFactor", "(", "factorName", ",", "factor", ",", "factor", ".", "getVars", "(", ")", ")", ";", "}" ]
Adds a parameterized, unreplicated factor to the model being constructed. The factor will match only the variables which it is defined over. @param factor
[ "Adds", "a", "parameterized", "unreplicated", "factor", "to", "the", "model", "being", "constructed", ".", "The", "factor", "will", "match", "only", "the", "variables", "which", "it", "is", "defined", "over", "." ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/parametric/ParametricFactorGraphBuilder.java#L36-L38
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java
PoolOperations.resizePool
public void resizePool(String poolId, Integer targetDedicatedNodes, Integer targetLowPriorityNodes) throws BatchErrorException, IOException { resizePool(poolId, targetDedicatedNodes, targetLowPriorityNodes, null, null, null); }
java
public void resizePool(String poolId, Integer targetDedicatedNodes, Integer targetLowPriorityNodes) throws BatchErrorException, IOException { resizePool(poolId, targetDedicatedNodes, targetLowPriorityNodes, null, null, null); }
[ "public", "void", "resizePool", "(", "String", "poolId", ",", "Integer", "targetDedicatedNodes", ",", "Integer", "targetLowPriorityNodes", ")", "throws", "BatchErrorException", ",", "IOException", "{", "resizePool", "(", "poolId", ",", "targetDedicatedNodes", ",", "ta...
Resizes the specified pool. @param poolId The ID of the pool. @param targetDedicatedNodes The desired number of dedicated compute nodes in the pool. @param targetLowPriorityNodes The desired number of low-priority compute nodes in the pool. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Resizes", "the", "specified", "pool", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java#L514-L517
mgormley/pacaya
src/main/java/edu/jhu/pacaya/autodiff/TensorUtils.java
TensorUtils.getVectorFromReals
public static Tensor getVectorFromReals(Algebra s, double... values) { Tensor t0 = getVectorFromValues(RealAlgebra.getInstance(), values); return t0.copyAndConvertAlgebra(s); }
java
public static Tensor getVectorFromReals(Algebra s, double... values) { Tensor t0 = getVectorFromValues(RealAlgebra.getInstance(), values); return t0.copyAndConvertAlgebra(s); }
[ "public", "static", "Tensor", "getVectorFromReals", "(", "Algebra", "s", ",", "double", "...", "values", ")", "{", "Tensor", "t0", "=", "getVectorFromValues", "(", "RealAlgebra", ".", "getInstance", "(", ")", ",", "values", ")", ";", "return", "t0", ".", "...
Gets a tensor in the s semiring, where the input values are assumed to be in the reals.
[ "Gets", "a", "tensor", "in", "the", "s", "semiring", "where", "the", "input", "values", "are", "assumed", "to", "be", "in", "the", "reals", "." ]
train
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/autodiff/TensorUtils.java#L57-L60
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java
CmsContainerpageController.saveInheritContainer
public void saveInheritContainer( final CmsInheritanceContainer inheritanceContainer, final CmsGroupContainerElementPanel groupContainerElement) { if (getGroupcontainer() != null) { CmsRpcAction<Map<String, CmsContainerElementData>> action = new CmsRpcAction<Map<String, CmsContainerElementData>>() { /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute() */ @Override public void execute() { start(0, true); getContainerpageService().saveInheritanceContainer( CmsCoreProvider.get().getStructureId(), getData().getDetailId(), inheritanceContainer, getPageState(), getLocale(), this); } /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object) */ @Override protected void onResponse(Map<String, CmsContainerElementData> result) { stop(false); m_elements.putAll(result); try { replaceContainerElement(groupContainerElement, result.get(groupContainerElement.getId())); } catch (Exception e) { CmsDebugLog.getInstance().printLine("Error replacing group container element"); } addToRecentList(groupContainerElement.getId(), null); CmsNotification.get().send( Type.NORMAL, Messages.get().key(Messages.GUI_NOTIFICATION_INHERITANCE_CONTAINER_SAVED_0)); } }; action.execute(); } }
java
public void saveInheritContainer( final CmsInheritanceContainer inheritanceContainer, final CmsGroupContainerElementPanel groupContainerElement) { if (getGroupcontainer() != null) { CmsRpcAction<Map<String, CmsContainerElementData>> action = new CmsRpcAction<Map<String, CmsContainerElementData>>() { /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute() */ @Override public void execute() { start(0, true); getContainerpageService().saveInheritanceContainer( CmsCoreProvider.get().getStructureId(), getData().getDetailId(), inheritanceContainer, getPageState(), getLocale(), this); } /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object) */ @Override protected void onResponse(Map<String, CmsContainerElementData> result) { stop(false); m_elements.putAll(result); try { replaceContainerElement(groupContainerElement, result.get(groupContainerElement.getId())); } catch (Exception e) { CmsDebugLog.getInstance().printLine("Error replacing group container element"); } addToRecentList(groupContainerElement.getId(), null); CmsNotification.get().send( Type.NORMAL, Messages.get().key(Messages.GUI_NOTIFICATION_INHERITANCE_CONTAINER_SAVED_0)); } }; action.execute(); } }
[ "public", "void", "saveInheritContainer", "(", "final", "CmsInheritanceContainer", "inheritanceContainer", ",", "final", "CmsGroupContainerElementPanel", "groupContainerElement", ")", "{", "if", "(", "getGroupcontainer", "(", ")", "!=", "null", ")", "{", "CmsRpcAction", ...
Saves the inheritance container.<p> @param inheritanceContainer the inheritance container data to save @param groupContainerElement the group container widget
[ "Saves", "the", "inheritance", "container", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java#L3151-L3197
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/EncryptUtil.java
EncryptUtil.decrypt
public static String decrypt(String key, String source) { try { // Get our secret key Key key0 = getKey(key); // Create the cipher Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); //byte[] b64cipherText = StringUtil.getAsciiBytes(source); // convert source string into base 64 bytes //byte[] ciphertext = Base64.decodeBase64(b64cipherText); // replaced Jakarta Base64 with custom one byte[] ciphertext = Base64Codec.decode(source); // Initialize the same cipher for decryption desCipher.init(Cipher.DECRYPT_MODE, key0); // Decrypt the ciphertext byte[] cleartext = desCipher.doFinal(ciphertext); // Return the clear text return new String(cleartext); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }
java
public static String decrypt(String key, String source) { try { // Get our secret key Key key0 = getKey(key); // Create the cipher Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); //byte[] b64cipherText = StringUtil.getAsciiBytes(source); // convert source string into base 64 bytes //byte[] ciphertext = Base64.decodeBase64(b64cipherText); // replaced Jakarta Base64 with custom one byte[] ciphertext = Base64Codec.decode(source); // Initialize the same cipher for decryption desCipher.init(Cipher.DECRYPT_MODE, key0); // Decrypt the ciphertext byte[] cleartext = desCipher.doFinal(ciphertext); // Return the clear text return new String(cleartext); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }
[ "public", "static", "String", "decrypt", "(", "String", "key", ",", "String", "source", ")", "{", "try", "{", "// Get our secret key", "Key", "key0", "=", "getKey", "(", "key", ")", ";", "// Create the cipher", "Cipher", "desCipher", "=", "Cipher", ".", "get...
Decodes a base-64 encoded string using the key with the DES/ECB/PKCS5Padding cipher. @param key The key to use for encryption. Must be at least 8 characters in length. @param source The Base-64 encoded encypted string. @return The plain text
[ "Decodes", "a", "base", "-", "64", "encoded", "string", "using", "the", "key", "with", "the", "DES", "/", "ECB", "/", "PKCS5Padding", "cipher", "." ]
train
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/EncryptUtil.java#L93-L115
netty/netty
codec-http/src/main/java/io/netty/handler/codec/http/HttpUtil.java
HttpUtil.set100ContinueExpected
public static void set100ContinueExpected(HttpMessage message, boolean expected) { if (expected) { message.headers().set(HttpHeaderNames.EXPECT, HttpHeaderValues.CONTINUE); } else { message.headers().remove(HttpHeaderNames.EXPECT); } }
java
public static void set100ContinueExpected(HttpMessage message, boolean expected) { if (expected) { message.headers().set(HttpHeaderNames.EXPECT, HttpHeaderValues.CONTINUE); } else { message.headers().remove(HttpHeaderNames.EXPECT); } }
[ "public", "static", "void", "set100ContinueExpected", "(", "HttpMessage", "message", ",", "boolean", "expected", ")", "{", "if", "(", "expected", ")", "{", "message", ".", "headers", "(", ")", ".", "set", "(", "HttpHeaderNames", ".", "EXPECT", ",", "HttpHead...
Sets or removes the {@code "Expect: 100-continue"} header to / from the specified message. If {@code expected} is {@code true}, the {@code "Expect: 100-continue"} header is set and all other previous {@code "Expect"} headers are removed. Otherwise, all {@code "Expect"} headers are removed completely.
[ "Sets", "or", "removes", "the", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpUtil.java#L286-L292
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Main.java
Main.execute
public static int execute(String[] args, PrintWriter outWriter, PrintWriter errWriter) { Start jdoc = new Start(outWriter, errWriter); return jdoc.begin(args).exitCode; }
java
public static int execute(String[] args, PrintWriter outWriter, PrintWriter errWriter) { Start jdoc = new Start(outWriter, errWriter); return jdoc.begin(args).exitCode; }
[ "public", "static", "int", "execute", "(", "String", "[", "]", "args", ",", "PrintWriter", "outWriter", ",", "PrintWriter", "errWriter", ")", "{", "Start", "jdoc", "=", "new", "Start", "(", "outWriter", ",", "errWriter", ")", ";", "return", "jdoc", ".", ...
Programmatic interface. @param outWriter a stream for expected output @param errWriter a stream for diagnostic output @param args The command line parameters. @return The return code.
[ "Programmatic", "interface", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Main.java#L86-L89
dlemmermann/PreferencesFX
preferencesfx/src/main/java/com/dlsc/preferencesfx/history/History.java
History.attachChangeListener
public void attachChangeListener(Setting setting) { ChangeListener changeEvent = (observable, oldValue, newValue) -> { if (isListenerActive() && oldValue != newValue) { LOGGER.trace("Change detected, old: " + oldValue + " new: " + newValue); addChange(new Change(setting, oldValue, newValue)); } }; ChangeListener listChangeEvent = (observable, oldValue, newValue) -> { if (isListenerActive()) { LOGGER.trace("List Change detected: " + oldValue); addChange(new Change(setting, (ObservableList) oldValue, (ObservableList) newValue)); } }; if (setting.valueProperty() instanceof SimpleListProperty) { setting.valueProperty().addListener(listChangeEvent); } else { setting.valueProperty().addListener(changeEvent); } }
java
public void attachChangeListener(Setting setting) { ChangeListener changeEvent = (observable, oldValue, newValue) -> { if (isListenerActive() && oldValue != newValue) { LOGGER.trace("Change detected, old: " + oldValue + " new: " + newValue); addChange(new Change(setting, oldValue, newValue)); } }; ChangeListener listChangeEvent = (observable, oldValue, newValue) -> { if (isListenerActive()) { LOGGER.trace("List Change detected: " + oldValue); addChange(new Change(setting, (ObservableList) oldValue, (ObservableList) newValue)); } }; if (setting.valueProperty() instanceof SimpleListProperty) { setting.valueProperty().addListener(listChangeEvent); } else { setting.valueProperty().addListener(changeEvent); } }
[ "public", "void", "attachChangeListener", "(", "Setting", "setting", ")", "{", "ChangeListener", "changeEvent", "=", "(", "observable", ",", "oldValue", ",", "newValue", ")", "->", "{", "if", "(", "isListenerActive", "(", ")", "&&", "oldValue", "!=", "newValue...
Adds a listener to the {@code setting}, so every time the value of the {@code setting} changes, a new {@link Change} will be created and added to the list of changes. @param setting the setting to observe for changes
[ "Adds", "a", "listener", "to", "the", "{", "@code", "setting", "}", "so", "every", "time", "the", "value", "of", "the", "{", "@code", "setting", "}", "changes", "a", "new", "{", "@link", "Change", "}", "will", "be", "created", "and", "added", "to", "...
train
https://github.com/dlemmermann/PreferencesFX/blob/e06a49663ec949c2f7eb56e6b5952c030ed42d33/preferencesfx/src/main/java/com/dlsc/preferencesfx/history/History.java#L65-L84
FXMisc/Flowless
src/main/java/org/fxmisc/flowless/CellPositioner.java
CellPositioner.shiftCellBy
public void shiftCellBy(C cell, double delta) { double y = orientation.minY(cell) + delta; relocate(cell, 0, y); }
java
public void shiftCellBy(C cell, double delta) { double y = orientation.minY(cell) + delta; relocate(cell, 0, y); }
[ "public", "void", "shiftCellBy", "(", "C", "cell", ",", "double", "delta", ")", "{", "double", "y", "=", "orientation", ".", "minY", "(", "cell", ")", "+", "delta", ";", "relocate", "(", "cell", ",", "0", ",", "y", ")", ";", "}" ]
Moves the given cell's node's "layoutY" value by {@code delta}. See {@link OrientationHelper}'s javadoc for more explanation on what quoted terms mean.
[ "Moves", "the", "given", "cell", "s", "node", "s", "layoutY", "value", "by", "{" ]
train
https://github.com/FXMisc/Flowless/blob/dce2269ebafed8f79203d00085af41f06f3083bc/src/main/java/org/fxmisc/flowless/CellPositioner.java#L102-L105
apache/flink
flink-connectors/flink-hadoop-compatibility/src/main/java/org/apache/flink/api/java/hadoop/mapreduce/HadoopOutputFormatBase.java
HadoopOutputFormatBase.open
@Override public void open(int taskNumber, int numTasks) throws IOException { // enforce sequential open() calls synchronized (OPEN_MUTEX) { if (Integer.toString(taskNumber + 1).length() > 6) { throw new IOException("Task id too large."); } this.taskNumber = taskNumber + 1; // for hadoop 2.2 this.configuration.set("mapreduce.output.basename", "tmp"); TaskAttemptID taskAttemptID = TaskAttemptID.forName("attempt__0000_r_" + String.format("%" + (6 - Integer.toString(taskNumber + 1).length()) + "s", " ").replace(" ", "0") + Integer.toString(taskNumber + 1) + "_0"); this.configuration.set("mapred.task.id", taskAttemptID.toString()); this.configuration.setInt("mapred.task.partition", taskNumber + 1); // for hadoop 2.2 this.configuration.set("mapreduce.task.attempt.id", taskAttemptID.toString()); this.configuration.setInt("mapreduce.task.partition", taskNumber + 1); try { this.context = new TaskAttemptContextImpl(this.configuration, taskAttemptID); this.outputCommitter = this.mapreduceOutputFormat.getOutputCommitter(this.context); this.outputCommitter.setupJob(new JobContextImpl(this.configuration, new JobID())); } catch (Exception e) { throw new RuntimeException(e); } this.context.getCredentials().addAll(this.credentials); Credentials currentUserCreds = getCredentialsFromUGI(UserGroupInformation.getCurrentUser()); if (currentUserCreds != null) { this.context.getCredentials().addAll(currentUserCreds); } // compatible for hadoop 2.2.0, the temporary output directory is different from hadoop 1.2.1 if (outputCommitter instanceof FileOutputCommitter) { this.configuration.set("mapreduce.task.output.dir", ((FileOutputCommitter) this.outputCommitter).getWorkPath().toString()); } try { this.recordWriter = this.mapreduceOutputFormat.getRecordWriter(this.context); } catch (InterruptedException e) { throw new IOException("Could not create RecordWriter.", e); } } }
java
@Override public void open(int taskNumber, int numTasks) throws IOException { // enforce sequential open() calls synchronized (OPEN_MUTEX) { if (Integer.toString(taskNumber + 1).length() > 6) { throw new IOException("Task id too large."); } this.taskNumber = taskNumber + 1; // for hadoop 2.2 this.configuration.set("mapreduce.output.basename", "tmp"); TaskAttemptID taskAttemptID = TaskAttemptID.forName("attempt__0000_r_" + String.format("%" + (6 - Integer.toString(taskNumber + 1).length()) + "s", " ").replace(" ", "0") + Integer.toString(taskNumber + 1) + "_0"); this.configuration.set("mapred.task.id", taskAttemptID.toString()); this.configuration.setInt("mapred.task.partition", taskNumber + 1); // for hadoop 2.2 this.configuration.set("mapreduce.task.attempt.id", taskAttemptID.toString()); this.configuration.setInt("mapreduce.task.partition", taskNumber + 1); try { this.context = new TaskAttemptContextImpl(this.configuration, taskAttemptID); this.outputCommitter = this.mapreduceOutputFormat.getOutputCommitter(this.context); this.outputCommitter.setupJob(new JobContextImpl(this.configuration, new JobID())); } catch (Exception e) { throw new RuntimeException(e); } this.context.getCredentials().addAll(this.credentials); Credentials currentUserCreds = getCredentialsFromUGI(UserGroupInformation.getCurrentUser()); if (currentUserCreds != null) { this.context.getCredentials().addAll(currentUserCreds); } // compatible for hadoop 2.2.0, the temporary output directory is different from hadoop 1.2.1 if (outputCommitter instanceof FileOutputCommitter) { this.configuration.set("mapreduce.task.output.dir", ((FileOutputCommitter) this.outputCommitter).getWorkPath().toString()); } try { this.recordWriter = this.mapreduceOutputFormat.getRecordWriter(this.context); } catch (InterruptedException e) { throw new IOException("Could not create RecordWriter.", e); } } }
[ "@", "Override", "public", "void", "open", "(", "int", "taskNumber", ",", "int", "numTasks", ")", "throws", "IOException", "{", "// enforce sequential open() calls", "synchronized", "(", "OPEN_MUTEX", ")", "{", "if", "(", "Integer", ".", "toString", "(", "taskNu...
create the temporary output file for hadoop RecordWriter. @param taskNumber The number of the parallel instance. @param numTasks The number of parallel tasks. @throws java.io.IOException
[ "create", "the", "temporary", "output", "file", "for", "hadoop", "RecordWriter", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-hadoop-compatibility/src/main/java/org/apache/flink/api/java/hadoop/mapreduce/HadoopOutputFormatBase.java#L104-L154
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowController.java
FlowController.sendError
protected void sendError( String errText, HttpServletRequest request, HttpServletResponse response ) throws IOException { InternalUtils.sendError( "PageFlow_Custom_Error", null, request, response, new Object[]{ getDisplayName(), errText } ); }
java
protected void sendError( String errText, HttpServletRequest request, HttpServletResponse response ) throws IOException { InternalUtils.sendError( "PageFlow_Custom_Error", null, request, response, new Object[]{ getDisplayName(), errText } ); }
[ "protected", "void", "sendError", "(", "String", "errText", ",", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "IOException", "{", "InternalUtils", ".", "sendError", "(", "\"PageFlow_Custom_Error\"", ",", "null", ",", "request...
Send a Page Flow error to the browser. @param errText the error message to display. @param response the current HttpServletResponse.
[ "Send", "a", "Page", "Flow", "error", "to", "the", "browser", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowController.java#L240-L245
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/config/AbstractBucketConfig.java
AbstractBucketConfig.nodeInfoFromExtended
private List<NodeInfo> nodeInfoFromExtended(final List<PortInfo> nodesExt, final List<NodeInfo> nodeInfos) { List<NodeInfo> converted = new ArrayList<NodeInfo>(nodesExt.size()); for (int i = 0; i < nodesExt.size(); i++) { NetworkAddress hostname = nodesExt.get(i).hostname(); // Since nodeInfo and nodesExt might not be the same size, this can be null! NodeInfo nodeInfo = i >= nodeInfos.size() ? null : nodeInfos.get(i); if (hostname == null) { if (nodeInfo != null) { hostname = nodeInfo.hostname(); } else { // If hostname missing, then node configured using localhost LOGGER.debug("Hostname is for nodesExt[{}] is not available, falling back to origin.", i); hostname = origin; } } Map<ServiceType, Integer> ports = nodesExt.get(i).ports(); Map<ServiceType, Integer> sslPorts = nodesExt.get(i).sslPorts(); Map<String, AlternateAddress> aa = nodesExt.get(i).alternateAddresses(); // this is an ephemeral bucket (not supporting views), don't enable views! if (!bucketCapabilities.contains(BucketCapabilities.COUCHAPI)) { ports.remove(ServiceType.VIEW); sslPorts.remove(ServiceType.VIEW); } // make sure only kv nodes are added if they are actually also in the nodes // list and not just in nodesExt, since the kv service might be available // on the cluster but not yet enabled for this specific bucket. if (nodeInfo == null) { ports.remove(ServiceType.BINARY); sslPorts.remove(ServiceType.BINARY); } converted.add(new DefaultNodeInfo(hostname, ports, sslPorts, aa)); } return converted; }
java
private List<NodeInfo> nodeInfoFromExtended(final List<PortInfo> nodesExt, final List<NodeInfo> nodeInfos) { List<NodeInfo> converted = new ArrayList<NodeInfo>(nodesExt.size()); for (int i = 0; i < nodesExt.size(); i++) { NetworkAddress hostname = nodesExt.get(i).hostname(); // Since nodeInfo and nodesExt might not be the same size, this can be null! NodeInfo nodeInfo = i >= nodeInfos.size() ? null : nodeInfos.get(i); if (hostname == null) { if (nodeInfo != null) { hostname = nodeInfo.hostname(); } else { // If hostname missing, then node configured using localhost LOGGER.debug("Hostname is for nodesExt[{}] is not available, falling back to origin.", i); hostname = origin; } } Map<ServiceType, Integer> ports = nodesExt.get(i).ports(); Map<ServiceType, Integer> sslPorts = nodesExt.get(i).sslPorts(); Map<String, AlternateAddress> aa = nodesExt.get(i).alternateAddresses(); // this is an ephemeral bucket (not supporting views), don't enable views! if (!bucketCapabilities.contains(BucketCapabilities.COUCHAPI)) { ports.remove(ServiceType.VIEW); sslPorts.remove(ServiceType.VIEW); } // make sure only kv nodes are added if they are actually also in the nodes // list and not just in nodesExt, since the kv service might be available // on the cluster but not yet enabled for this specific bucket. if (nodeInfo == null) { ports.remove(ServiceType.BINARY); sslPorts.remove(ServiceType.BINARY); } converted.add(new DefaultNodeInfo(hostname, ports, sslPorts, aa)); } return converted; }
[ "private", "List", "<", "NodeInfo", ">", "nodeInfoFromExtended", "(", "final", "List", "<", "PortInfo", ">", "nodesExt", ",", "final", "List", "<", "NodeInfo", ">", "nodeInfos", ")", "{", "List", "<", "NodeInfo", ">", "converted", "=", "new", "ArrayList", ...
Helper method to create the {@link NodeInfo}s from from the extended node information. In older server versions (< 3.0.2) the nodesExt part does not carry a hostname, so as a fallback the hostname is loaded from the node info if needed. @param nodesExt the extended information. @return the generated node infos.
[ "Helper", "method", "to", "create", "the", "{", "@link", "NodeInfo", "}", "s", "from", "from", "the", "extended", "node", "information", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/AbstractBucketConfig.java#L75-L113
sdl/odata
odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomDataWriter.java
AtomDataWriter.writeData
public void writeData(Object entity, EntityType entityType) throws XMLStreamException, ODataRenderException { xmlWriter.writeStartElement(ODATA_CONTENT); xmlWriter.writeAttribute(TYPE, XML.toString()); xmlWriter.writeStartElement(METADATA, ODATA_PROPERTIES, ""); marshall(entity, entityType); xmlWriter.writeEndElement(); xmlWriter.writeEndElement(); }
java
public void writeData(Object entity, EntityType entityType) throws XMLStreamException, ODataRenderException { xmlWriter.writeStartElement(ODATA_CONTENT); xmlWriter.writeAttribute(TYPE, XML.toString()); xmlWriter.writeStartElement(METADATA, ODATA_PROPERTIES, ""); marshall(entity, entityType); xmlWriter.writeEndElement(); xmlWriter.writeEndElement(); }
[ "public", "void", "writeData", "(", "Object", "entity", ",", "EntityType", "entityType", ")", "throws", "XMLStreamException", ",", "ODataRenderException", "{", "xmlWriter", ".", "writeStartElement", "(", "ODATA_CONTENT", ")", ";", "xmlWriter", ".", "writeAttribute", ...
Write the data for a given entity. @param entity The given entity. @param entityType The entity type. @throws XMLStreamException if unable to render the entity @throws ODataRenderException if unable to render the entity
[ "Write", "the", "data", "for", "a", "given", "entity", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomDataWriter.java#L90-L100
Impetus/Kundera
src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java
MongoDBClient.findCommaSeparatedArgument
private String findCommaSeparatedArgument(String functionBody, int index) { int start = 0; int found = -1; int brackets = 0; int pos = 0; int length = functionBody.length(); while (found < index && pos < length) { char ch = functionBody.charAt(pos); switch (ch) { case ',': if (brackets == 0) { found++; if (found < index) { start = pos + 1; } } break; case '(': case '[': case '{': brackets++; break; case ')': case ']': case '}': brackets--; break; } pos++; } if (found == index) { return functionBody.substring(start, pos - 1); } else if (pos == length) { return functionBody.substring(start); } else { return ""; } }
java
private String findCommaSeparatedArgument(String functionBody, int index) { int start = 0; int found = -1; int brackets = 0; int pos = 0; int length = functionBody.length(); while (found < index && pos < length) { char ch = functionBody.charAt(pos); switch (ch) { case ',': if (brackets == 0) { found++; if (found < index) { start = pos + 1; } } break; case '(': case '[': case '{': brackets++; break; case ')': case ']': case '}': brackets--; break; } pos++; } if (found == index) { return functionBody.substring(start, pos - 1); } else if (pos == length) { return functionBody.substring(start); } else { return ""; } }
[ "private", "String", "findCommaSeparatedArgument", "(", "String", "functionBody", ",", "int", "index", ")", "{", "int", "start", "=", "0", ";", "int", "found", "=", "-", "1", ";", "int", "brackets", "=", "0", ";", "int", "pos", "=", "0", ";", "int", ...
Find comma separated argument. @param functionBody the function body @param index the index @return the string
[ "Find", "comma", "separated", "argument", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java#L1782-L1833
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/ch/Subtypes2.java
Subtypes2.computeFirstCommonSuperclassOfDifferentDimensionArrays
private ReferenceType computeFirstCommonSuperclassOfDifferentDimensionArrays(ArrayType aArrType, ArrayType bArrType) { assert aArrType.getDimensions() != bArrType.getDimensions(); boolean aBaseTypeIsPrimitive = (aArrType.getBasicType() instanceof BasicType); boolean bBaseTypeIsPrimitive = (bArrType.getBasicType() instanceof BasicType); if (aBaseTypeIsPrimitive || bBaseTypeIsPrimitive) { int minDimensions, maxDimensions; if (aArrType.getDimensions() < bArrType.getDimensions()) { minDimensions = aArrType.getDimensions(); maxDimensions = bArrType.getDimensions(); } else { minDimensions = bArrType.getDimensions(); maxDimensions = aArrType.getDimensions(); } if (minDimensions == 1) { // One of the types was something like int[]. // The only possible common supertype is Object. return Type.OBJECT; } else { // Weird case: e.g., // - first common supertype of int[][] and char[][][] is // Object[] // because f.c.s. of int[] and char[][] is Object // - first common supertype of int[][][] and char[][][][][] is // Object[][] // because f.c.s. of int[] and char[][][] is Object return new ArrayType(Type.OBJECT, maxDimensions - minDimensions); } } else { // Both a and b have base types which are ObjectTypes. // Since the arrays have different numbers of dimensions, the // f.c.s. will have Object as its base type. // E.g., f.c.s. of Cat[] and Dog[][] is Object[] return new ArrayType(Type.OBJECT, Math.min(aArrType.getDimensions(), bArrType.getDimensions())); } }
java
private ReferenceType computeFirstCommonSuperclassOfDifferentDimensionArrays(ArrayType aArrType, ArrayType bArrType) { assert aArrType.getDimensions() != bArrType.getDimensions(); boolean aBaseTypeIsPrimitive = (aArrType.getBasicType() instanceof BasicType); boolean bBaseTypeIsPrimitive = (bArrType.getBasicType() instanceof BasicType); if (aBaseTypeIsPrimitive || bBaseTypeIsPrimitive) { int minDimensions, maxDimensions; if (aArrType.getDimensions() < bArrType.getDimensions()) { minDimensions = aArrType.getDimensions(); maxDimensions = bArrType.getDimensions(); } else { minDimensions = bArrType.getDimensions(); maxDimensions = aArrType.getDimensions(); } if (minDimensions == 1) { // One of the types was something like int[]. // The only possible common supertype is Object. return Type.OBJECT; } else { // Weird case: e.g., // - first common supertype of int[][] and char[][][] is // Object[] // because f.c.s. of int[] and char[][] is Object // - first common supertype of int[][][] and char[][][][][] is // Object[][] // because f.c.s. of int[] and char[][][] is Object return new ArrayType(Type.OBJECT, maxDimensions - minDimensions); } } else { // Both a and b have base types which are ObjectTypes. // Since the arrays have different numbers of dimensions, the // f.c.s. will have Object as its base type. // E.g., f.c.s. of Cat[] and Dog[][] is Object[] return new ArrayType(Type.OBJECT, Math.min(aArrType.getDimensions(), bArrType.getDimensions())); } }
[ "private", "ReferenceType", "computeFirstCommonSuperclassOfDifferentDimensionArrays", "(", "ArrayType", "aArrType", ",", "ArrayType", "bArrType", ")", "{", "assert", "aArrType", ".", "getDimensions", "(", ")", "!=", "bArrType", ".", "getDimensions", "(", ")", ";", "bo...
Get the first common superclass of arrays with different numbers of dimensions. @param aArrType an ArrayType @param bArrType another ArrayType @return ReferenceType representing first common superclass
[ "Get", "the", "first", "common", "superclass", "of", "arrays", "with", "different", "numbers", "of", "dimensions", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/ch/Subtypes2.java#L643-L680
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.restoreDeletedResource
public void restoreDeletedResource(CmsRequestContext context, CmsUUID structureId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); // write permissions on parent folder are checked later m_driverManager.restoreDeletedResource(dbc, structureId); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_RESTORE_DELETED_RESOURCE_1, structureId), e); } finally { dbc.clear(); } }
java
public void restoreDeletedResource(CmsRequestContext context, CmsUUID structureId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); // write permissions on parent folder are checked later m_driverManager.restoreDeletedResource(dbc, structureId); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_RESTORE_DELETED_RESOURCE_1, structureId), e); } finally { dbc.clear(); } }
[ "public", "void", "restoreDeletedResource", "(", "CmsRequestContext", "context", ",", "CmsUUID", "structureId", ")", "throws", "CmsException", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "(", "context", ")", ";", "try", "{", "checkOff...
Restores a deleted resource identified by its structure id from the historical archive.<p> @param context the current request context @param structureId the structure id of the resource to restore @throws CmsException if something goes wrong @see CmsObject#restoreDeletedResource(CmsUUID)
[ "Restores", "a", "deleted", "resource", "identified", "by", "its", "structure", "id", "from", "the", "historical", "archive", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L5813-L5825
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/olap/OLAPService.java
OLAPService.getStats
public SegmentStats getStats(ApplicationDefinition appDef, String shard) { checkServiceState(); return m_olap.getStats(appDef, shard); }
java
public SegmentStats getStats(ApplicationDefinition appDef, String shard) { checkServiceState(); return m_olap.getStats(appDef, shard); }
[ "public", "SegmentStats", "getStats", "(", "ApplicationDefinition", "appDef", ",", "String", "shard", ")", "{", "checkServiceState", "(", ")", ";", "return", "m_olap", ".", "getStats", "(", "appDef", ",", "shard", ")", ";", "}" ]
Get statistics for the given shard, owned by the given application. Statistics are returned as a {@link SegmentStats} object. If there is no information for the given shard, an IllegalArgumentException is thrown. @param appDef OLAP application definition. @param shard Shard name. @return Shard statistics as a {@link SegmentStats} object.
[ "Get", "statistics", "for", "the", "given", "shard", "owned", "by", "the", "given", "application", ".", "Statistics", "are", "returned", "as", "a", "{", "@link", "SegmentStats", "}", "object", ".", "If", "there", "is", "no", "information", "for", "the", "g...
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/olap/OLAPService.java#L292-L295
m-m-m/util
pojo/src/main/java/net/sf/mmm/util/pojo/descriptor/base/accessor/AbstractPojoPropertyAccessorBuilder.java
AbstractPojoPropertyAccessorBuilder.getPropertyName
protected String getPropertyName(String methodName, String prefix, String suffix) { if (methodName.startsWith(prefix) && methodName.endsWith(suffix)) { return getPropertyName(methodName, prefix.length(), suffix.length()); } return null; }
java
protected String getPropertyName(String methodName, String prefix, String suffix) { if (methodName.startsWith(prefix) && methodName.endsWith(suffix)) { return getPropertyName(methodName, prefix.length(), suffix.length()); } return null; }
[ "protected", "String", "getPropertyName", "(", "String", "methodName", ",", "String", "prefix", ",", "String", "suffix", ")", "{", "if", "(", "methodName", ".", "startsWith", "(", "prefix", ")", "&&", "methodName", ".", "endsWith", "(", "suffix", ")", ")", ...
This method gets the according {@link net.sf.mmm.util.pojo.descriptor.api.PojoPropertyDescriptor#getName() property-name} for the given {@code methodName}. <br> This is the un-capitalized substring of the {@code methodName} after between the given {@code prefix} and {@code suffix}. @param methodName is the {@link java.lang.reflect.Method#getName() name} of the {@link net.sf.mmm.util.pojo.descriptor.api.accessor.PojoPropertyAccessor#getAccessibleObject() accessor-method}. @param prefix is the prefix (e.g. "get", "set" or "is"). @param suffix is the suffix (e.g. "" or "Size"). @return the requested property-name or {@code null} if NOT available. ({@code methodName} does NOT {@link String#startsWith(String) start with} {@code prefix} or does NOT {@link String#endsWith(String) end with} {@code suffix}).
[ "This", "method", "gets", "the", "according", "{", "@link", "net", ".", "sf", ".", "mmm", ".", "util", ".", "pojo", ".", "descriptor", ".", "api", ".", "PojoPropertyDescriptor#getName", "()", "property", "-", "name", "}", "for", "the", "given", "{", "@co...
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/pojo/src/main/java/net/sf/mmm/util/pojo/descriptor/base/accessor/AbstractPojoPropertyAccessorBuilder.java#L112-L118
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/QueryRecord.java
QueryRecord.addRelationship
public void addRelationship(int linkType, Record recLeft, Record recRight, int ifldLeft1, int ifldRight1, int ifldLeft2, int ifldRight2, int ifldLeft3, int ifldRight3) { String fldLeft1 = recLeft.getField(ifldLeft1).getFieldName(); String fldRight1 = recRight.getField(ifldRight1).getFieldName(); String fldLeft2 = ifldLeft2 != -1 ? recLeft.getField(ifldLeft2).getFieldName() : null; String fldRight2 = ifldRight2 != -1 ? recRight.getField(ifldRight2).getFieldName() : null; String fldLeft3 = ifldLeft3 != -1 ? recLeft.getField(ifldLeft3).getFieldName() : null; String fldRight3 = ifldRight3 != -1 ? recRight.getField(ifldRight3).getFieldName() : null; new TableLink(this, linkType, recLeft, recRight, fldLeft1, fldRight1, fldLeft2, fldRight2, fldLeft3, fldRight3); }
java
public void addRelationship(int linkType, Record recLeft, Record recRight, int ifldLeft1, int ifldRight1, int ifldLeft2, int ifldRight2, int ifldLeft3, int ifldRight3) { String fldLeft1 = recLeft.getField(ifldLeft1).getFieldName(); String fldRight1 = recRight.getField(ifldRight1).getFieldName(); String fldLeft2 = ifldLeft2 != -1 ? recLeft.getField(ifldLeft2).getFieldName() : null; String fldRight2 = ifldRight2 != -1 ? recRight.getField(ifldRight2).getFieldName() : null; String fldLeft3 = ifldLeft3 != -1 ? recLeft.getField(ifldLeft3).getFieldName() : null; String fldRight3 = ifldRight3 != -1 ? recRight.getField(ifldRight3).getFieldName() : null; new TableLink(this, linkType, recLeft, recRight, fldLeft1, fldRight1, fldLeft2, fldRight2, fldLeft3, fldRight3); }
[ "public", "void", "addRelationship", "(", "int", "linkType", ",", "Record", "recLeft", ",", "Record", "recRight", ",", "int", "ifldLeft1", ",", "int", "ifldRight1", ",", "int", "ifldLeft2", ",", "int", "ifldRight2", ",", "int", "ifldLeft3", ",", "int", "ifld...
Add this table link to this query. Creates a new tablelink and adds it to the link list.
[ "Add", "this", "table", "link", "to", "this", "query", ".", "Creates", "a", "new", "tablelink", "and", "adds", "it", "to", "the", "link", "list", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/QueryRecord.java#L162-L171
VoltDB/voltdb
src/frontend/org/voltdb/utils/CatalogUtil.java
CatalogUtil.setClusterInfo
private static void setClusterInfo(Catalog catalog, DeploymentType deployment) { ClusterType cluster = deployment.getCluster(); int kFactor = cluster.getKfactor(); Cluster catCluster = catalog.getClusters().get("cluster"); // copy the deployment info that is currently not recorded anywhere else Deployment catDeploy = catCluster.getDeployment().get("deployment"); catDeploy.setKfactor(kFactor); if (deployment.getPartitionDetection().isEnabled()) { catCluster.setNetworkpartition(true); } else { catCluster.setNetworkpartition(false); } setSystemSettings(deployment, catDeploy); catCluster.setHeartbeattimeout(deployment.getHeartbeat().getTimeout()); // copy schema modification behavior from xml to catalog if (cluster.getSchema() != null) { catCluster.setUseddlschema(cluster.getSchema() == SchemaType.DDL); } else { // Don't think we can get here, deployment schema guarantees a default value hostLog.warn("Schema modification setting not found. " + "Forcing default behavior of UpdateCatalog to modify database schema."); catCluster.setUseddlschema(false); } }
java
private static void setClusterInfo(Catalog catalog, DeploymentType deployment) { ClusterType cluster = deployment.getCluster(); int kFactor = cluster.getKfactor(); Cluster catCluster = catalog.getClusters().get("cluster"); // copy the deployment info that is currently not recorded anywhere else Deployment catDeploy = catCluster.getDeployment().get("deployment"); catDeploy.setKfactor(kFactor); if (deployment.getPartitionDetection().isEnabled()) { catCluster.setNetworkpartition(true); } else { catCluster.setNetworkpartition(false); } setSystemSettings(deployment, catDeploy); catCluster.setHeartbeattimeout(deployment.getHeartbeat().getTimeout()); // copy schema modification behavior from xml to catalog if (cluster.getSchema() != null) { catCluster.setUseddlschema(cluster.getSchema() == SchemaType.DDL); } else { // Don't think we can get here, deployment schema guarantees a default value hostLog.warn("Schema modification setting not found. " + "Forcing default behavior of UpdateCatalog to modify database schema."); catCluster.setUseddlschema(false); } }
[ "private", "static", "void", "setClusterInfo", "(", "Catalog", "catalog", ",", "DeploymentType", "deployment", ")", "{", "ClusterType", "cluster", "=", "deployment", ".", "getCluster", "(", ")", ";", "int", "kFactor", "=", "cluster", ".", "getKfactor", "(", ")...
Set cluster info in the catalog. @param leader The leader hostname @param catalog The catalog to be updated. @param printLog Whether or not to print cluster configuration.
[ "Set", "cluster", "info", "in", "the", "catalog", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/utils/CatalogUtil.java#L1308-L1337
soklet/soklet
src/main/java/com/soklet/web/routing/RoutingServlet.java
RoutingServlet.handleUnmatchedRoute
protected boolean handleUnmatchedRoute(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpMethod httpMethod, String requestPath) { // If this resource matches a different method[s], error out specially List<HttpMethod> otherHttpMethods = new ArrayList<>(HttpMethod.values().length); for (HttpMethod otherHttpMethod : HttpMethod.values()) if (httpMethod != otherHttpMethod && routeMatcher.match(otherHttpMethod, requestPath).isPresent()) otherHttpMethods.add(otherHttpMethod); // Handle OPTIONS specially by indicating we don't want to invoke the response handler // Otherwise, throw an exception indicating a 405 if (otherHttpMethods.size() > 0) { // Always write the Allow header httpServletResponse.setHeader("Allow", otherHttpMethods.stream().map(method -> method.name()).collect(joining(", "))); if (httpMethod == HttpMethod.OPTIONS) return false; throw new MethodNotAllowedException(format("%s is not supported for this resource. Supported method%s %s", httpMethod, (otherHttpMethods.size() == 1 ? " is" : "s are"), otherHttpMethods.stream().map(method -> method.name()).collect(joining(", ")))); } // No matching route, and no possible alternatives? It's a 404 throw new NotFoundException(format("No route was found for %s %s", httpMethod.name(), requestPath)); }
java
protected boolean handleUnmatchedRoute(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpMethod httpMethod, String requestPath) { // If this resource matches a different method[s], error out specially List<HttpMethod> otherHttpMethods = new ArrayList<>(HttpMethod.values().length); for (HttpMethod otherHttpMethod : HttpMethod.values()) if (httpMethod != otherHttpMethod && routeMatcher.match(otherHttpMethod, requestPath).isPresent()) otherHttpMethods.add(otherHttpMethod); // Handle OPTIONS specially by indicating we don't want to invoke the response handler // Otherwise, throw an exception indicating a 405 if (otherHttpMethods.size() > 0) { // Always write the Allow header httpServletResponse.setHeader("Allow", otherHttpMethods.stream().map(method -> method.name()).collect(joining(", "))); if (httpMethod == HttpMethod.OPTIONS) return false; throw new MethodNotAllowedException(format("%s is not supported for this resource. Supported method%s %s", httpMethod, (otherHttpMethods.size() == 1 ? " is" : "s are"), otherHttpMethods.stream().map(method -> method.name()).collect(joining(", ")))); } // No matching route, and no possible alternatives? It's a 404 throw new NotFoundException(format("No route was found for %s %s", httpMethod.name(), requestPath)); }
[ "protected", "boolean", "handleUnmatchedRoute", "(", "HttpServletRequest", "httpServletRequest", ",", "HttpServletResponse", "httpServletResponse", ",", "HttpMethod", "httpMethod", ",", "String", "requestPath", ")", "{", "// If this resource matches a different method[s], error out...
Performs custom processing when a route was not matched. <p> Detects 404s, also useful for handling special cases like 405 errors if we detect the route would match for a different HTTP method. @return {@code true} if the response handler should be invoked, {@code false} otherwise
[ "Performs", "custom", "processing", "when", "a", "route", "was", "not", "matched", ".", "<p", ">", "Detects", "404s", "also", "useful", "for", "handling", "special", "cases", "like", "405", "errors", "if", "we", "detect", "the", "route", "would", "match", ...
train
https://github.com/soklet/soklet/blob/4f12de07d9c132e0126d50ad11cc1d8576594700/src/main/java/com/soklet/web/routing/RoutingServlet.java#L121-L147
whitesource/fs-agent
src/main/java/org/whitesource/agent/dependency/resolver/npm/YarnDependencyCollector.java
YarnDependencyCollector.isDescendant
private boolean isDescendant(DependencyInfo ancestor, DependencyInfo descendant){ for (DependencyInfo child : ancestor.getChildren()){ if (child.equals(descendant)){ return true; } if (isDescendant(child, descendant)){ return true; } } return false; }
java
private boolean isDescendant(DependencyInfo ancestor, DependencyInfo descendant){ for (DependencyInfo child : ancestor.getChildren()){ if (child.equals(descendant)){ return true; } if (isDescendant(child, descendant)){ return true; } } return false; }
[ "private", "boolean", "isDescendant", "(", "DependencyInfo", "ancestor", ",", "DependencyInfo", "descendant", ")", "{", "for", "(", "DependencyInfo", "child", ":", "ancestor", ".", "getChildren", "(", ")", ")", "{", "if", "(", "child", ".", "equals", "(", "d...
preventing circular dependencies by making sure the dependency is not a descendant of its own
[ "preventing", "circular", "dependencies", "by", "making", "sure", "the", "dependency", "is", "not", "a", "descendant", "of", "its", "own" ]
train
https://github.com/whitesource/fs-agent/blob/d6ee4842c4f08f4aeda7eb2307b24c49b6bed0e1/src/main/java/org/whitesource/agent/dependency/resolver/npm/YarnDependencyCollector.java#L163-L173
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeConverter.java
GoogleMapShapeConverter.toMultiPoint
public MultiPoint toMultiPoint(List<LatLng> latLngs, boolean hasZ, boolean hasM) { MultiPoint multiPoint = new MultiPoint(hasZ, hasM); for (LatLng latLng : latLngs) { Point point = toPoint(latLng); multiPoint.addPoint(point); } return multiPoint; }
java
public MultiPoint toMultiPoint(List<LatLng> latLngs, boolean hasZ, boolean hasM) { MultiPoint multiPoint = new MultiPoint(hasZ, hasM); for (LatLng latLng : latLngs) { Point point = toPoint(latLng); multiPoint.addPoint(point); } return multiPoint; }
[ "public", "MultiPoint", "toMultiPoint", "(", "List", "<", "LatLng", ">", "latLngs", ",", "boolean", "hasZ", ",", "boolean", "hasM", ")", "{", "MultiPoint", "multiPoint", "=", "new", "MultiPoint", "(", "hasZ", ",", "hasM", ")", ";", "for", "(", "LatLng", ...
Convert a {@link MultiLatLng} to a {@link MultiPoint} @param latLngs lat lngs @param hasZ has z flag @param hasM has m flag @return multi point
[ "Convert", "a", "{", "@link", "MultiLatLng", "}", "to", "a", "{", "@link", "MultiPoint", "}" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeConverter.java#L791-L802
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/PersistenceDelegator.java
PersistenceDelegator.onSynchronization
private void onSynchronization(Node node, EntityMetadata metadata) { DefaultTransactionResource resource = (DefaultTransactionResource) coordinator.getResource(metadata .getPersistenceUnit()); if (enableFlush) { resource.onFlush(); } else { resource.syncNode(node); } }
java
private void onSynchronization(Node node, EntityMetadata metadata) { DefaultTransactionResource resource = (DefaultTransactionResource) coordinator.getResource(metadata .getPersistenceUnit()); if (enableFlush) { resource.onFlush(); } else { resource.syncNode(node); } }
[ "private", "void", "onSynchronization", "(", "Node", "node", ",", "EntityMetadata", "metadata", ")", "{", "DefaultTransactionResource", "resource", "=", "(", "DefaultTransactionResource", ")", "coordinator", ".", "getResource", "(", "metadata", ".", "getPersistenceUnit"...
If transaction is in progress and user explicitly invokes em.flush()! @param node data node @param metadata entity metadata.
[ "If", "transaction", "is", "in", "progress", "and", "user", "explicitly", "invokes", "em", ".", "flush", "()", "!" ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/PersistenceDelegator.java#L943-L955
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/slim/Base64Fixture.java
Base64Fixture.createFrom
public String createFrom(String fileName, String base64String) { String result; String baseName = FilenameUtils.getBaseName(fileName); String target = saveBase + baseName; String ext = FilenameUtils.getExtension(fileName); byte[] content = base64Decode(base64String); String downloadedFile = FileUtil.saveToFile(target, ext, content); String wikiUrl = getWikiUrl(downloadedFile); if (wikiUrl != null) { // make href to file result = String.format("<a href=\"%s\">%s</a>", wikiUrl, fileName); } else { result = downloadedFile; } return result; }
java
public String createFrom(String fileName, String base64String) { String result; String baseName = FilenameUtils.getBaseName(fileName); String target = saveBase + baseName; String ext = FilenameUtils.getExtension(fileName); byte[] content = base64Decode(base64String); String downloadedFile = FileUtil.saveToFile(target, ext, content); String wikiUrl = getWikiUrl(downloadedFile); if (wikiUrl != null) { // make href to file result = String.format("<a href=\"%s\">%s</a>", wikiUrl, fileName); } else { result = downloadedFile; } return result; }
[ "public", "String", "createFrom", "(", "String", "fileName", ",", "String", "base64String", ")", "{", "String", "result", ";", "String", "baseName", "=", "FilenameUtils", ".", "getBaseName", "(", "fileName", ")", ";", "String", "target", "=", "saveBase", "+", ...
Creates a new file with content read from base64 encoded string. @param fileName (base) file name to create (if a file with specified name already exists a number will be added to make the name unique). @param base64String base64 encoded string to decode and use as file content. @return location of created file.
[ "Creates", "a", "new", "file", "with", "content", "read", "from", "base64", "encoded", "string", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/slim/Base64Fixture.java#L39-L54
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.core/src/com/ibm/ws/logging/LoggerHelper.java
LoggerHelper.addLoggerToGroup
public static void addLoggerToGroup(Logger logger, String group) { if (logger == null) throw new NullPointerException("logger"); if (group == null) throw new NullPointerException("group"); if (!(logger instanceof WsLogger)) throw new IllegalArgumentException("logger"); WsLogger wsLogger = (WsLogger) logger; wsLogger.addGroup(group); }
java
public static void addLoggerToGroup(Logger logger, String group) { if (logger == null) throw new NullPointerException("logger"); if (group == null) throw new NullPointerException("group"); if (!(logger instanceof WsLogger)) throw new IllegalArgumentException("logger"); WsLogger wsLogger = (WsLogger) logger; wsLogger.addGroup(group); }
[ "public", "static", "void", "addLoggerToGroup", "(", "Logger", "logger", ",", "String", "group", ")", "{", "if", "(", "logger", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"logger\"", ")", ";", "if", "(", "group", "==", "null", ")", ...
Adds the logger to the specific group. This is useful for code that needs to run in environments with and without RAS. In an environment without RAS, Logger.getLogger must be used, and addLoggerToGroup can be invoked reflectively when available. For example: <pre> private static Logger getLogger(Class&lt;?> c, String group) { &#32;&#32;Logger logger = Logger.getLogger(c.getName()); &#32;&#32;try { &#32;&#32;&#32;&#32;Class.forName("com.ibm.ws.logging.LoggerHelper") &#32;&#32;&#32;&#32;&#32;&#32;.getMethod("addLoggerToGroup", Logger.class, String.class) &#32;&#32;&#32;&#32;&#32;&#32;.invoke(logger, group); &#32;&#32;} catch (Exception e) { &#32;&#32;&#32;&#32;// Ignored. &#32;&#32;} &#32;&#32;return logger; } </pre> @param logger the logger @param group the group @throws NullPointerException if logger or group are null @throws IllegalArgumentException if logger does not support dynamically added groups
[ "Adds", "the", "logger", "to", "the", "specific", "group", ".", "This", "is", "useful", "for", "code", "that", "needs", "to", "run", "in", "environments", "with", "and", "without", "RAS", ".", "In", "an", "environment", "without", "RAS", "Logger", ".", "...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.core/src/com/ibm/ws/logging/LoggerHelper.java#L43-L53
googleapis/google-cloud-java
google-cloud-clients/google-cloud-translate/src/main/java/com/google/cloud/translate/v3beta1/TranslationServiceClient.java
TranslationServiceClient.formatGlossaryName
@Deprecated public static final String formatGlossaryName(String project, String location, String glossary) { return GLOSSARY_PATH_TEMPLATE.instantiate( "project", project, "location", location, "glossary", glossary); }
java
@Deprecated public static final String formatGlossaryName(String project, String location, String glossary) { return GLOSSARY_PATH_TEMPLATE.instantiate( "project", project, "location", location, "glossary", glossary); }
[ "@", "Deprecated", "public", "static", "final", "String", "formatGlossaryName", "(", "String", "project", ",", "String", "location", ",", "String", "glossary", ")", "{", "return", "GLOSSARY_PATH_TEMPLATE", ".", "instantiate", "(", "\"project\"", ",", "project", ",...
Formats a string containing the fully-qualified path to represent a glossary resource. @deprecated Use the {@link GlossaryName} class instead.
[ "Formats", "a", "string", "containing", "the", "fully", "-", "qualified", "path", "to", "represent", "a", "glossary", "resource", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-translate/src/main/java/com/google/cloud/translate/v3beta1/TranslationServiceClient.java#L129-L135
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/lib/ArrayUtil.java
ArrayUtil.hasNull
public static boolean hasNull(Object[] array, int[] columnMap) { int count = columnMap.length; for (int i = 0; i < count; i++) { if (array[columnMap[i]] == null) { return true; } } return false; }
java
public static boolean hasNull(Object[] array, int[] columnMap) { int count = columnMap.length; for (int i = 0; i < count; i++) { if (array[columnMap[i]] == null) { return true; } } return false; }
[ "public", "static", "boolean", "hasNull", "(", "Object", "[", "]", "array", ",", "int", "[", "]", "columnMap", ")", "{", "int", "count", "=", "columnMap", ".", "length", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++...
Determines if the array has a null column for any of the positions given in the rowColMap array.
[ "Determines", "if", "the", "array", "has", "a", "null", "column", "for", "any", "of", "the", "positions", "given", "in", "the", "rowColMap", "array", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/ArrayUtil.java#L715-L726
igniterealtime/Smack
smack-experimental/src/main/java/org/jivesoftware/smackx/push_notifications/PushNotificationsManager.java
PushNotificationsManager.disableAll
public boolean disableAll(Jid pushJid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return disable(pushJid, null); }
java
public boolean disableAll(Jid pushJid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return disable(pushJid, null); }
[ "public", "boolean", "disableAll", "(", "Jid", "pushJid", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "return", "disable", "(", "pushJid", ",", "null", ")", ";", "}" ]
Disable all push notifications. @param pushJid @return true if it was successfully disabled, false if not @throws NoResponseException @throws XMPPErrorException @throws NotConnectedException @throws InterruptedException
[ "Disable", "all", "push", "notifications", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/push_notifications/PushNotificationsManager.java#L143-L146
groupby/api-java
src/main/java/com/groupbyinc/api/AbstractBridge.java
AbstractBridge.generateSecuredPayload
public AesContent generateSecuredPayload(String customerId, Query query) throws GeneralSecurityException { return generateSecuredPayload(customerId, clientKey, query); }
java
public AesContent generateSecuredPayload(String customerId, Query query) throws GeneralSecurityException { return generateSecuredPayload(customerId, clientKey, query); }
[ "public", "AesContent", "generateSecuredPayload", "(", "String", "customerId", ",", "Query", "query", ")", "throws", "GeneralSecurityException", "{", "return", "generateSecuredPayload", "(", "customerId", ",", "clientKey", ",", "query", ")", ";", "}" ]
<code> Generates a secured payload </code> @param customerId The customerId as seen in Command Center. Ensure this is not the subdomain, which can be `customerId-cors.groupbycloud.com` @param query The query to encrypt
[ "<code", ">", "Generates", "a", "secured", "payload", "<", "/", "code", ">" ]
train
https://github.com/groupby/api-java/blob/257c4ed0777221e5e4ade3b29b9921300fac4e2e/src/main/java/com/groupbyinc/api/AbstractBridge.java#L552-L554
looly/hutool
hutool-db/src/main/java/cn/hutool/db/AbstractDb.java
AbstractDb.del
public int del(String tableName, String field, Object value) throws SQLException { return del(Entity.create(tableName).set(field, value)); }
java
public int del(String tableName, String field, Object value) throws SQLException { return del(Entity.create(tableName).set(field, value)); }
[ "public", "int", "del", "(", "String", "tableName", ",", "String", "field", ",", "Object", "value", ")", "throws", "SQLException", "{", "return", "del", "(", "Entity", ".", "create", "(", "tableName", ")", ".", "set", "(", "field", ",", "value", ")", "...
删除数据 @param tableName 表名 @param field 字段名,最好是主键 @param value 值,值可以是列表或数组,被当作IN查询处理 @return 删除行数 @throws SQLException SQL执行异常
[ "删除数据" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/AbstractDb.java#L348-L350
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java
DateFunctions.dateTruncMillis
public static Expression dateTruncMillis(Expression expression, DatePart part) { return x("DATE_TRUNC_MILLIS(" + expression.toString() + ", \"" + part.toString() + "\")"); }
java
public static Expression dateTruncMillis(Expression expression, DatePart part) { return x("DATE_TRUNC_MILLIS(" + expression.toString() + ", \"" + part.toString() + "\")"); }
[ "public", "static", "Expression", "dateTruncMillis", "(", "Expression", "expression", ",", "DatePart", "part", ")", "{", "return", "x", "(", "\"DATE_TRUNC_MILLIS(\"", "+", "expression", ".", "toString", "(", ")", "+", "\", \\\"\"", "+", "part", ".", "toString", ...
Returned expression results in UNIX timestamp that has been truncated so that the given date part is the least significant.
[ "Returned", "expression", "results", "in", "UNIX", "timestamp", "that", "has", "been", "truncated", "so", "that", "the", "given", "date", "part", "is", "the", "least", "significant", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java#L172-L174
JavaMoney/jsr354-ri
moneta-core/src/main/java/org/javamoney/moneta/FastMoney.java
FastMoney.ofMinor
public static FastMoney ofMinor(CurrencyUnit currency, long amountMinor) { return ofMinor(currency, amountMinor, currency.getDefaultFractionDigits()); }
java
public static FastMoney ofMinor(CurrencyUnit currency, long amountMinor) { return ofMinor(currency, amountMinor, currency.getDefaultFractionDigits()); }
[ "public", "static", "FastMoney", "ofMinor", "(", "CurrencyUnit", "currency", ",", "long", "amountMinor", ")", "{", "return", "ofMinor", "(", "currency", ",", "amountMinor", ",", "currency", ".", "getDefaultFractionDigits", "(", ")", ")", ";", "}" ]
Obtains an instance of {@code FastMoney} from an amount in minor units. For example, {@code ofMinor(USD, 1234)} creates the instance {@code USD 12.34}. @param currency the currency, not null @param amountMinor the amount of money in the minor division of the currency @return the monetary amount from minor units @see CurrencyUnit#getDefaultFractionDigits() @see FastMoney#ofMinor(CurrencyUnit, long, int) @throws NullPointerException when the currency is null @throws IllegalArgumentException when {@link CurrencyUnit#getDefaultFractionDigits()} is lesser than zero. @since 1.0.1
[ "Obtains", "an", "instance", "of", "{" ]
train
https://github.com/JavaMoney/jsr354-ri/blob/cf8ff2bbaf9b115acc05eb9b0c76c8397c308284/moneta-core/src/main/java/org/javamoney/moneta/FastMoney.java#L264-L266
graknlabs/grakn
server/src/graql/gremlin/fragment/Fragments.java
Fragments.attributeIndex
public static Fragment attributeIndex( @Nullable VarProperty varProperty, Variable start, Label label, Object attributeValue) { String attributeIndex = Schema.generateAttributeIndex(label, attributeValue.toString()); return new AutoValue_AttributeIndexFragment(varProperty, start, attributeIndex); }
java
public static Fragment attributeIndex( @Nullable VarProperty varProperty, Variable start, Label label, Object attributeValue) { String attributeIndex = Schema.generateAttributeIndex(label, attributeValue.toString()); return new AutoValue_AttributeIndexFragment(varProperty, start, attributeIndex); }
[ "public", "static", "Fragment", "attributeIndex", "(", "@", "Nullable", "VarProperty", "varProperty", ",", "Variable", "start", ",", "Label", "label", ",", "Object", "attributeValue", ")", "{", "String", "attributeIndex", "=", "Schema", ".", "generateAttributeIndex"...
A {@link Fragment} that uses an index stored on each attribute. Attributes are indexed by direct type and value.
[ "A", "{" ]
train
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/fragment/Fragments.java#L141-L145
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/TimephasedDataFactory.java
TimephasedDataFactory.getBaselineCost
public TimephasedCostContainer getBaselineCost(ProjectCalendar calendar, TimephasedCostNormaliser normaliser, byte[] data, boolean raw) { TimephasedCostContainer result = null; if (data != null && data.length > 0) { LinkedList<TimephasedCost> list = null; //System.out.println(ByteArrayHelper.hexdump(data, false)); int index = 16; // 16 byte header int blockSize = 20; double previousTotalCost = 0; Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 16); index += blockSize; while (index + blockSize <= data.length) { Date blockEndDate = MPPUtility.getTimestampFromTenths(data, index + 16); double currentTotalCost = (double) ((long) MPPUtility.getDouble(data, index + 8)) / 100; if (!costEquals(previousTotalCost, currentTotalCost)) { TimephasedCost cost = new TimephasedCost(); cost.setStart(blockStartDate); cost.setFinish(blockEndDate); cost.setTotalAmount(Double.valueOf(currentTotalCost - previousTotalCost)); if (list == null) { list = new LinkedList<TimephasedCost>(); } list.add(cost); //System.out.println(cost); previousTotalCost = currentTotalCost; } blockStartDate = blockEndDate; index += blockSize; } if (list != null) { result = new DefaultTimephasedCostContainer(calendar, normaliser, list, raw); } } return result; }
java
public TimephasedCostContainer getBaselineCost(ProjectCalendar calendar, TimephasedCostNormaliser normaliser, byte[] data, boolean raw) { TimephasedCostContainer result = null; if (data != null && data.length > 0) { LinkedList<TimephasedCost> list = null; //System.out.println(ByteArrayHelper.hexdump(data, false)); int index = 16; // 16 byte header int blockSize = 20; double previousTotalCost = 0; Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 16); index += blockSize; while (index + blockSize <= data.length) { Date blockEndDate = MPPUtility.getTimestampFromTenths(data, index + 16); double currentTotalCost = (double) ((long) MPPUtility.getDouble(data, index + 8)) / 100; if (!costEquals(previousTotalCost, currentTotalCost)) { TimephasedCost cost = new TimephasedCost(); cost.setStart(blockStartDate); cost.setFinish(blockEndDate); cost.setTotalAmount(Double.valueOf(currentTotalCost - previousTotalCost)); if (list == null) { list = new LinkedList<TimephasedCost>(); } list.add(cost); //System.out.println(cost); previousTotalCost = currentTotalCost; } blockStartDate = blockEndDate; index += blockSize; } if (list != null) { result = new DefaultTimephasedCostContainer(calendar, normaliser, list, raw); } } return result; }
[ "public", "TimephasedCostContainer", "getBaselineCost", "(", "ProjectCalendar", "calendar", ",", "TimephasedCostNormaliser", "normaliser", ",", "byte", "[", "]", "data", ",", "boolean", "raw", ")", "{", "TimephasedCostContainer", "result", "=", "null", ";", "if", "(...
Extracts baseline cost from the MPP file for a specific baseline. Returns null if no baseline cost is present, otherwise returns a list of timephased work items. @param calendar baseline calendar @param normaliser normaliser associated with this data @param data timephased baseline work data block @param raw flag indicating if this data is to be treated as raw @return timephased work
[ "Extracts", "baseline", "cost", "from", "the", "MPP", "file", "for", "a", "specific", "baseline", ".", "Returns", "null", "if", "no", "baseline", "cost", "is", "present", "otherwise", "returns", "a", "list", "of", "timephased", "work", "items", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/TimephasedDataFactory.java#L405-L453
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/DwgUtil.java
DwgUtil.getTextString
public static Vector getTextString(int[] data, int offset) throws Exception { int bitPos = offset; int newBitPos = ((Integer)DwgUtil.getBitShort(data, bitPos).get(0)).intValue(); int len = ((Integer)DwgUtil.getBitShort(data, bitPos).get(1)).intValue(); bitPos = newBitPos; int bitLen = len * 8; Object cosa = DwgUtil.getBits(data, bitLen, bitPos); String string; if (cosa instanceof byte[]) { string = new String((byte[])cosa); }
java
public static Vector getTextString(int[] data, int offset) throws Exception { int bitPos = offset; int newBitPos = ((Integer)DwgUtil.getBitShort(data, bitPos).get(0)).intValue(); int len = ((Integer)DwgUtil.getBitShort(data, bitPos).get(1)).intValue(); bitPos = newBitPos; int bitLen = len * 8; Object cosa = DwgUtil.getBits(data, bitLen, bitPos); String string; if (cosa instanceof byte[]) { string = new String((byte[])cosa); }
[ "public", "static", "Vector", "getTextString", "(", "int", "[", "]", "data", ",", "int", "offset", ")", "throws", "Exception", "{", "int", "bitPos", "=", "offset", ";", "int", "newBitPos", "=", "(", "(", "Integer", ")", "DwgUtil", ".", "getBitShort", "("...
Read a String from a group of unsigned bytes @param data Array of unsigned bytes obtained from the DWG binary file @param offset The current bit offset where the value begins @throws Exception If an unexpected bit value is found in the DWG file. Occurs when we are looking for LwPolylines. @return Vector This vector has two parts. First is an int value that represents the new offset, and second is the String
[ "Read", "a", "String", "from", "a", "group", "of", "unsigned", "bytes" ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/DwgUtil.java#L462-L472
frostwire/frostwire-jlibtorrent
src/main/java/com/frostwire/jlibtorrent/SessionHandle.java
SessionHandle.addTorrent
public TorrentHandle addTorrent(AddTorrentParams params, ErrorCode ec) { error_code e = new error_code(); TorrentHandle th = new TorrentHandle(s.add_torrent(params.swig(), e)); ec.assign(e); return th; }
java
public TorrentHandle addTorrent(AddTorrentParams params, ErrorCode ec) { error_code e = new error_code(); TorrentHandle th = new TorrentHandle(s.add_torrent(params.swig(), e)); ec.assign(e); return th; }
[ "public", "TorrentHandle", "addTorrent", "(", "AddTorrentParams", "params", ",", "ErrorCode", "ec", ")", "{", "error_code", "e", "=", "new", "error_code", "(", ")", ";", "TorrentHandle", "th", "=", "new", "TorrentHandle", "(", "s", ".", "add_torrent", "(", "...
You add torrents through the {@link #addTorrent(AddTorrentParams, ErrorCode)} function where you give an object with all the parameters. The {@code addTorrent} overloads will block until the torrent has been added (or failed to be added) and returns an error code and a {@link TorrentHandle}. In order to add torrents more efficiently, consider using {@link #asyncAddTorrent(AddTorrentParams)} which returns immediately, without waiting for the torrent to add. Notification of the torrent being added is sent as {@link com.frostwire.jlibtorrent.alerts.AddTorrentAlert}. <p> The {@link TorrentHandle} returned by this method can be used to retrieve information about the torrent's progress, its peers etc. It is also used to abort a torrent. <p> If the torrent you are trying to add already exists in the session (is either queued for checking, being checked or downloading) the error code will be set to {@link libtorrent_errors#duplicate_torrent} unless {@code flag_duplicate_is_error} is set to false. In that case, {@code addTorrent} will return the handle to the existing torrent. <p> All torrent handles must be destructed before the session is destructed! @param params the parameters to create the torrent download @param ec the error code if no torrent handle was created @return the torrent handle, could be invalid
[ "You", "add", "torrents", "through", "the", "{", "@link", "#addTorrent", "(", "AddTorrentParams", "ErrorCode", ")", "}", "function", "where", "you", "give", "an", "object", "with", "all", "the", "parameters", ".", "The", "{", "@code", "addTorrent", "}", "ove...
train
https://github.com/frostwire/frostwire-jlibtorrent/blob/a29249a940d34aba8c4677d238b472ef01833506/src/main/java/com/frostwire/jlibtorrent/SessionHandle.java#L247-L252
groovy/groovy-core
src/main/org/codehaus/groovy/ast/tools/GeneralUtils.java
GeneralUtils.getterX
public static Expression getterX(ClassNode annotatedNode, PropertyNode pNode) { ClassNode owner = pNode.getDeclaringClass(); if (annotatedNode.equals(owner)) { String getterName = "get" + MetaClassHelper.capitalize(pNode.getName()); if (ClassHelper.boolean_TYPE.equals(pNode.getOriginType())) { getterName = "is" + MetaClassHelper.capitalize(pNode.getName()); } return callX(new VariableExpression("this"), getterName, ArgumentListExpression.EMPTY_ARGUMENTS); } return propX(new VariableExpression("this"), pNode.getName()); }
java
public static Expression getterX(ClassNode annotatedNode, PropertyNode pNode) { ClassNode owner = pNode.getDeclaringClass(); if (annotatedNode.equals(owner)) { String getterName = "get" + MetaClassHelper.capitalize(pNode.getName()); if (ClassHelper.boolean_TYPE.equals(pNode.getOriginType())) { getterName = "is" + MetaClassHelper.capitalize(pNode.getName()); } return callX(new VariableExpression("this"), getterName, ArgumentListExpression.EMPTY_ARGUMENTS); } return propX(new VariableExpression("this"), pNode.getName()); }
[ "public", "static", "Expression", "getterX", "(", "ClassNode", "annotatedNode", ",", "PropertyNode", "pNode", ")", "{", "ClassNode", "owner", "=", "pNode", ".", "getDeclaringClass", "(", ")", ";", "if", "(", "annotatedNode", ".", "equals", "(", "owner", ")", ...
This method is similar to {@link #propX(Expression, Expression)} but will make sure that if the property being accessed is defined inside the classnode provided as a parameter, then a getter call is generated instead of a field access. @param annotatedNode the class node where the property node is accessed from @param pNode the property being accessed @return a method call expression or a property expression
[ "This", "method", "is", "similar", "to", "{" ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/tools/GeneralUtils.java#L626-L636
hamcrest/hamcrest-junit
src/main/java/org/hamcrest/junit/MatcherAssume.java
MatcherAssume.assumeThat
public static <T> void assumeThat(String message, T actual, Matcher<? super T> matcher) { Matching.checkMatch(message, actual, matcher, new MismatchAction() { @Override public void mismatch(String description) { throw new AssumptionViolatedException(description); } }); }
java
public static <T> void assumeThat(String message, T actual, Matcher<? super T> matcher) { Matching.checkMatch(message, actual, matcher, new MismatchAction() { @Override public void mismatch(String description) { throw new AssumptionViolatedException(description); } }); }
[ "public", "static", "<", "T", ">", "void", "assumeThat", "(", "String", "message", ",", "T", "actual", ",", "Matcher", "<", "?", "super", "T", ">", "matcher", ")", "{", "Matching", ".", "checkMatch", "(", "message", ",", "actual", ",", "matcher", ",", ...
Call to assume that <code>actual</code> satisfies the condition specified by <code>matcher</code>. If not, the test halts and is ignored. Example: <pre>: assumeThat(1, is(1)); // passes foo(); // will execute assumeThat(0, is(1)); // assumption failure! test halts int x = 1 / 0; // will never execute </pre> @param <T> the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assumeThat(1, is("a"))} @param actual the computed value being compared @param matcher an expression, built of {@link Matcher}s, specifying allowed values @see org.hamcrest.CoreMatchers @see JUnitMatchers
[ "Call", "to", "assume", "that", "<code", ">", "actual<", "/", "code", ">", "satisfies", "the", "condition", "specified", "by", "<code", ">", "matcher<", "/", "code", ">", ".", "If", "not", "the", "test", "halts", "and", "is", "ignored", ".", "Example", ...
train
https://github.com/hamcrest/hamcrest-junit/blob/5e02d55230b560f255433bcc490afaeda9e1a043/src/main/java/org/hamcrest/junit/MatcherAssume.java#L71-L78
anotheria/moskito
moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/fetcher/HttpHelper.java
HttpHelper.getHttpResponse
public static HttpResponse getHttpResponse(String url, UsernamePasswordCredentials credentials) throws IOException { HttpGet request = new HttpGet(url); if (credentials != null) { URI uri = request.getURI(); AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort()); Credentials cached = httpClient.getCredentialsProvider().getCredentials(authScope); if (!areSame(cached, credentials)) { httpClient.getCredentialsProvider().setCredentials(authScope, credentials); } } return httpClient.execute(request); }
java
public static HttpResponse getHttpResponse(String url, UsernamePasswordCredentials credentials) throws IOException { HttpGet request = new HttpGet(url); if (credentials != null) { URI uri = request.getURI(); AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort()); Credentials cached = httpClient.getCredentialsProvider().getCredentials(authScope); if (!areSame(cached, credentials)) { httpClient.getCredentialsProvider().setCredentials(authScope, credentials); } } return httpClient.execute(request); }
[ "public", "static", "HttpResponse", "getHttpResponse", "(", "String", "url", ",", "UsernamePasswordCredentials", "credentials", ")", "throws", "IOException", "{", "HttpGet", "request", "=", "new", "HttpGet", "(", "url", ")", ";", "if", "(", "credentials", "!=", ...
Executes a request using the given URL and credentials. @param url the http URL to connect to. @param credentials credentials to use @return the response to the request. @throws IOException in case of a problem or the connection was aborted @throws ClientProtocolException in case of an http protocol error
[ "Executes", "a", "request", "using", "the", "given", "URL", "and", "credentials", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/fetcher/HttpHelper.java#L95-L106
Yubico/yubico-j
src/com/yubico/base/CRC13239.java
CRC13239.getCRC
static public short getCRC(byte[] buf, int len) { short i; short crc = 0x7fff; boolean isNeg = true; for(int j = 0; j < len; j++) { crc ^= buf[j] & 0xff; for (i = 0; i < 8; i++) { if ((crc & 1) == 0) { crc >>= 1; if (isNeg) { isNeg = false; crc |= 0x4000; } } else { crc >>= 1; if (isNeg) { crc ^= 0x4408; } else { crc ^= 0x0408; isNeg = true; } } } } return isNeg ? (short) (crc | (short) 0x8000) : crc; }
java
static public short getCRC(byte[] buf, int len) { short i; short crc = 0x7fff; boolean isNeg = true; for(int j = 0; j < len; j++) { crc ^= buf[j] & 0xff; for (i = 0; i < 8; i++) { if ((crc & 1) == 0) { crc >>= 1; if (isNeg) { isNeg = false; crc |= 0x4000; } } else { crc >>= 1; if (isNeg) { crc ^= 0x4408; } else { crc ^= 0x0408; isNeg = true; } } } } return isNeg ? (short) (crc | (short) 0x8000) : crc; }
[ "static", "public", "short", "getCRC", "(", "byte", "[", "]", "buf", ",", "int", "len", ")", "{", "short", "i", ";", "short", "crc", "=", "0x7fff", ";", "boolean", "isNeg", "=", "true", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "len...
<p>Method for calculating a CRC13239 checksum over a byte buffer.</p> @param buf byte buffer to be checksummed. @param len how much of the buffer should be checksummed @return CRC13239 checksum
[ "<p", ">", "Method", "for", "calculating", "a", "CRC13239", "checksum", "over", "a", "byte", "buffer", ".", "<", "/", "p", ">" ]
train
https://github.com/Yubico/yubico-j/blob/46b407e885b550f9438b9becdeeccb8ff763dc5a/src/com/yubico/base/CRC13239.java#L54-L83
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/ProgramUtils.java
ProgramUtils.executeCommandWithResult
public static ExecutionResult executeCommandWithResult( final Logger logger, final String[] command, final File workingDir, final Map<String,String> environmentVars, final String applicationName, final String scopedInstancePath) throws IOException, InterruptedException { logger.fine( "Executing command: " + Arrays.toString( command )); // Setup ProcessBuilder pb = new ProcessBuilder( command ); if( workingDir != null ) pb.directory(workingDir); Map<String,String> env = pb.environment(); if( environmentVars != null && env != null ) { // No putAll() here: null key or value would cause NPE // (see ProcessBuilder.environment() javadoc). for( Map.Entry<String,String> entry : environmentVars.entrySet()) { if( entry.getKey() != null && entry.getValue() != null ) env.put( entry.getKey(), entry.getValue()); } } // Prepare the result StringBuilder normalOutput = new StringBuilder(); StringBuilder errorOutput = new StringBuilder(); int exitValue = -1; // Execute Process process = pb.start(); // Store process in ThreadLocal, so it can be cancelled later (eg. if blocked) logger.fine("Storing process [" + applicationName + "] [" + scopedInstancePath + "]"); ProcessStore.setProcess(applicationName, scopedInstancePath, process); try { new Thread( new OutputRunnable( process, true, errorOutput, logger )).start(); new Thread( new OutputRunnable( process, false, normalOutput, logger )).start(); exitValue = process.waitFor(); if( exitValue != 0 ) logger.warning( "Command execution returned a non-zero code. Code:" + exitValue ); } finally { ProcessStore.clearProcess(applicationName, scopedInstancePath); } return new ExecutionResult( normalOutput.toString().trim(), errorOutput.toString().trim(), exitValue ); }
java
public static ExecutionResult executeCommandWithResult( final Logger logger, final String[] command, final File workingDir, final Map<String,String> environmentVars, final String applicationName, final String scopedInstancePath) throws IOException, InterruptedException { logger.fine( "Executing command: " + Arrays.toString( command )); // Setup ProcessBuilder pb = new ProcessBuilder( command ); if( workingDir != null ) pb.directory(workingDir); Map<String,String> env = pb.environment(); if( environmentVars != null && env != null ) { // No putAll() here: null key or value would cause NPE // (see ProcessBuilder.environment() javadoc). for( Map.Entry<String,String> entry : environmentVars.entrySet()) { if( entry.getKey() != null && entry.getValue() != null ) env.put( entry.getKey(), entry.getValue()); } } // Prepare the result StringBuilder normalOutput = new StringBuilder(); StringBuilder errorOutput = new StringBuilder(); int exitValue = -1; // Execute Process process = pb.start(); // Store process in ThreadLocal, so it can be cancelled later (eg. if blocked) logger.fine("Storing process [" + applicationName + "] [" + scopedInstancePath + "]"); ProcessStore.setProcess(applicationName, scopedInstancePath, process); try { new Thread( new OutputRunnable( process, true, errorOutput, logger )).start(); new Thread( new OutputRunnable( process, false, normalOutput, logger )).start(); exitValue = process.waitFor(); if( exitValue != 0 ) logger.warning( "Command execution returned a non-zero code. Code:" + exitValue ); } finally { ProcessStore.clearProcess(applicationName, scopedInstancePath); } return new ExecutionResult( normalOutput.toString().trim(), errorOutput.toString().trim(), exitValue ); }
[ "public", "static", "ExecutionResult", "executeCommandWithResult", "(", "final", "Logger", "logger", ",", "final", "String", "[", "]", "command", ",", "final", "File", "workingDir", ",", "final", "Map", "<", "String", ",", "String", ">", "environmentVars", ",", ...
Executes a command on the VM and retrieves all the result. <p> This includes the process's exit value, its normal output as well as the error flow. </p> @param logger a logger (not null) @param command a command to execute (not null, not empty) @param workingDir the working directory for the command @param environmentVars a map containing environment variables (can be null) @param applicationName the roboconf application name (null if not specified) @param scopedInstancePath the roboconf scoped instance path (null if not specified) @throws IOException if a new process could not be created @throws InterruptedException if the new process encountered a process
[ "Executes", "a", "command", "on", "the", "VM", "and", "retrieves", "all", "the", "result", ".", "<p", ">", "This", "includes", "the", "process", "s", "exit", "value", "its", "normal", "output", "as", "well", "as", "the", "error", "flow", ".", "<", "/",...
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/ProgramUtils.java#L69-L123
UrielCh/ovh-java-sdk
ovh-java-sdk-horizonView/src/main/java/net/minidev/ovh/api/ApiOvhHorizonView.java
ApiOvhHorizonView.serviceName_dedicatedHorizon_customerUser_username_GET
public OvhCustomerUser serviceName_dedicatedHorizon_customerUser_username_GET(String serviceName, String username) throws IOException { String qPath = "/horizonView/{serviceName}/dedicatedHorizon/customerUser/{username}"; StringBuilder sb = path(qPath, serviceName, username); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCustomerUser.class); }
java
public OvhCustomerUser serviceName_dedicatedHorizon_customerUser_username_GET(String serviceName, String username) throws IOException { String qPath = "/horizonView/{serviceName}/dedicatedHorizon/customerUser/{username}"; StringBuilder sb = path(qPath, serviceName, username); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCustomerUser.class); }
[ "public", "OvhCustomerUser", "serviceName_dedicatedHorizon_customerUser_username_GET", "(", "String", "serviceName", ",", "String", "username", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/horizonView/{serviceName}/dedicatedHorizon/customerUser/{username}\"", ";",...
Get this object properties REST: GET /horizonView/{serviceName}/dedicatedHorizon/customerUser/{username} @param serviceName [required] Domain of the service @param username [required] Customer username of your HaaS User
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-horizonView/src/main/java/net/minidev/ovh/api/ApiOvhHorizonView.java#L476-L481
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java
ThreadLocalRandom.internalNextLong
final long internalNextLong(long origin, long bound) { long r = mix64(nextSeed()); if (origin < bound) { long n = bound - origin, m = n - 1; if ((n & m) == 0L) // power of two r = (r & m) + origin; else if (n > 0L) { // reject over-represented candidates for (long u = r >>> 1; // ensure nonnegative u + m - (r = u % n) < 0L; // rejection check u = mix64(nextSeed()) >>> 1) // retry ; r += origin; } else { // range not representable as long while (r < origin || r >= bound) r = mix64(nextSeed()); } } return r; }
java
final long internalNextLong(long origin, long bound) { long r = mix64(nextSeed()); if (origin < bound) { long n = bound - origin, m = n - 1; if ((n & m) == 0L) // power of two r = (r & m) + origin; else if (n > 0L) { // reject over-represented candidates for (long u = r >>> 1; // ensure nonnegative u + m - (r = u % n) < 0L; // rejection check u = mix64(nextSeed()) >>> 1) // retry ; r += origin; } else { // range not representable as long while (r < origin || r >= bound) r = mix64(nextSeed()); } } return r; }
[ "final", "long", "internalNextLong", "(", "long", "origin", ",", "long", "bound", ")", "{", "long", "r", "=", "mix64", "(", "nextSeed", "(", ")", ")", ";", "if", "(", "origin", "<", "bound", ")", "{", "long", "n", "=", "bound", "-", "origin", ",", ...
The form of nextLong used by LongStream Spliterators. If origin is greater than bound, acts as unbounded form of nextLong, else as bounded form. @param origin the least value, unless greater than bound @param bound the upper bound (exclusive), must not equal origin @return a pseudorandom value
[ "The", "form", "of", "nextLong", "used", "by", "LongStream", "Spliterators", ".", "If", "origin", "is", "greater", "than", "bound", "acts", "as", "unbounded", "form", "of", "nextLong", "else", "as", "bounded", "form", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java#L210-L229
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupPersonsImpl.java
PersonGroupPersonsImpl.updateWithServiceResponseAsync
public Observable<ServiceResponse<Void>> updateWithServiceResponseAsync(String personGroupId, UUID personId, UpdatePersonGroupPersonsOptionalParameter updateOptionalParameter) { if (this.client.azureRegion() == null) { throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null."); } if (personGroupId == null) { throw new IllegalArgumentException("Parameter personGroupId is required and cannot be null."); } if (personId == null) { throw new IllegalArgumentException("Parameter personId is required and cannot be null."); } final String name = updateOptionalParameter != null ? updateOptionalParameter.name() : null; final String userData = updateOptionalParameter != null ? updateOptionalParameter.userData() : null; return updateWithServiceResponseAsync(personGroupId, personId, name, userData); }
java
public Observable<ServiceResponse<Void>> updateWithServiceResponseAsync(String personGroupId, UUID personId, UpdatePersonGroupPersonsOptionalParameter updateOptionalParameter) { if (this.client.azureRegion() == null) { throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null."); } if (personGroupId == null) { throw new IllegalArgumentException("Parameter personGroupId is required and cannot be null."); } if (personId == null) { throw new IllegalArgumentException("Parameter personId is required and cannot be null."); } final String name = updateOptionalParameter != null ? updateOptionalParameter.name() : null; final String userData = updateOptionalParameter != null ? updateOptionalParameter.userData() : null; return updateWithServiceResponseAsync(personGroupId, personId, name, userData); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Void", ">", ">", "updateWithServiceResponseAsync", "(", "String", "personGroupId", ",", "UUID", "personId", ",", "UpdatePersonGroupPersonsOptionalParameter", "updateOptionalParameter", ")", "{", "if", "(", "this", "....
Update name or userData of a person. @param personGroupId Id referencing a particular person group. @param personId Id referencing a particular person. @param updateOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Update", "name", "or", "userData", "of", "a", "person", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupPersonsImpl.java#L665-L679
MorphiaOrg/morphia
morphia/src/main/java/dev/morphia/utils/Assert.java
Assert.parameterNotEmpty
public static void parameterNotEmpty(final String name, final String value) { if (value != null && value.length() == 0) { raiseError(format("Parameter '%s' is expected to NOT be empty.", name)); } }
java
public static void parameterNotEmpty(final String name, final String value) { if (value != null && value.length() == 0) { raiseError(format("Parameter '%s' is expected to NOT be empty.", name)); } }
[ "public", "static", "void", "parameterNotEmpty", "(", "final", "String", "name", ",", "final", "String", "value", ")", "{", "if", "(", "value", "!=", "null", "&&", "value", ".", "length", "(", ")", "==", "0", ")", "{", "raiseError", "(", "format", "(",...
Validates that the value is not empty @param name the parameter name @param value the proposed parameter value
[ "Validates", "that", "the", "value", "is", "not", "empty" ]
train
https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/utils/Assert.java#L73-L77
ow2-chameleon/fuchsia
bases/knx/calimero/src/main/java/tuwien/auto/calimero/tools/NetworkMonitor.java
NetworkMonitor.createMonitor
private void createMonitor(LinkListener l) throws KNXException { final KNXMediumSettings medium = (KNXMediumSettings) options.get("medium"); if (options.containsKey("serial")) { final String p = (String) options.get("serial"); try { m = new KNXNetworkMonitorFT12(Integer.parseInt(p), medium); } catch (final NumberFormatException e) { m = new KNXNetworkMonitorFT12(p, medium); } } else { // create local and remote socket address for monitor link final InetSocketAddress local = createLocalSocket((InetAddress) options .get("localhost"), (Integer) options.get("localport")); final InetSocketAddress host = new InetSocketAddress((InetAddress) options .get("host"), ((Integer) options.get("port")).intValue()); // create the monitor link, based on the KNXnet/IP protocol // specify whether network address translation shall be used, // and tell the physical medium of the KNX network m = new KNXNetworkMonitorIP(local, host, options.containsKey("nat"), medium); } // add the log writer for monitor log events LogManager.getManager().addWriter(m.getName(), w); // on console we want to have all possible information, so enable // decoding of a received raw frame by the monitor link m.setDecodeRawFrames(true); // listen to monitor link events m.addMonitorListener(l); // we always need a link closed notification (even with user supplied listener) m.addMonitorListener(new LinkListener() { public void indication(FrameEvent e) {} public void linkClosed(CloseEvent e) { System.out.println("network monitor exit, " + e.getReason()); synchronized (NetworkMonitor.this) { NetworkMonitor.this.notify(); } } }); }
java
private void createMonitor(LinkListener l) throws KNXException { final KNXMediumSettings medium = (KNXMediumSettings) options.get("medium"); if (options.containsKey("serial")) { final String p = (String) options.get("serial"); try { m = new KNXNetworkMonitorFT12(Integer.parseInt(p), medium); } catch (final NumberFormatException e) { m = new KNXNetworkMonitorFT12(p, medium); } } else { // create local and remote socket address for monitor link final InetSocketAddress local = createLocalSocket((InetAddress) options .get("localhost"), (Integer) options.get("localport")); final InetSocketAddress host = new InetSocketAddress((InetAddress) options .get("host"), ((Integer) options.get("port")).intValue()); // create the monitor link, based on the KNXnet/IP protocol // specify whether network address translation shall be used, // and tell the physical medium of the KNX network m = new KNXNetworkMonitorIP(local, host, options.containsKey("nat"), medium); } // add the log writer for monitor log events LogManager.getManager().addWriter(m.getName(), w); // on console we want to have all possible information, so enable // decoding of a received raw frame by the monitor link m.setDecodeRawFrames(true); // listen to monitor link events m.addMonitorListener(l); // we always need a link closed notification (even with user supplied listener) m.addMonitorListener(new LinkListener() { public void indication(FrameEvent e) {} public void linkClosed(CloseEvent e) { System.out.println("network monitor exit, " + e.getReason()); synchronized (NetworkMonitor.this) { NetworkMonitor.this.notify(); } } }); }
[ "private", "void", "createMonitor", "(", "LinkListener", "l", ")", "throws", "KNXException", "{", "final", "KNXMediumSettings", "medium", "=", "(", "KNXMediumSettings", ")", "options", ".", "get", "(", "\"medium\"", ")", ";", "if", "(", "options", ".", "contai...
Creates a new network monitor using the supplied options. <p> @throws KNXException on problems on monitor creation
[ "Creates", "a", "new", "network", "monitor", "using", "the", "supplied", "options", ".", "<p", ">" ]
train
https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/bases/knx/calimero/src/main/java/tuwien/auto/calimero/tools/NetworkMonitor.java#L247-L290
groupe-sii/ogham
ogham-core/src/main/java/fr/sii/ogham/core/util/bean/BeanWrapperUtils.java
BeanWrapperUtils.getReadMethod
public static Method getReadMethod(Object bean, String name) { return getReadMethods(bean).get(name); }
java
public static Method getReadMethod(Object bean, String name) { return getReadMethods(bean).get(name); }
[ "public", "static", "Method", "getReadMethod", "(", "Object", "bean", ",", "String", "name", ")", "{", "return", "getReadMethods", "(", "bean", ")", ".", "get", "(", "name", ")", ";", "}" ]
Get a read {@link Method} for a particular property. @param bean the bean instance @param name the name of the property @return the getter method for the property
[ "Get", "a", "read", "{", "@link", "Method", "}", "for", "a", "particular", "property", "." ]
train
https://github.com/groupe-sii/ogham/blob/e273b845604add74b5a25dfd931cb3c166b1008f/ogham-core/src/main/java/fr/sii/ogham/core/util/bean/BeanWrapperUtils.java#L98-L100
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/config/Config.java
Config.setAtomicLongConfigs
public Config setAtomicLongConfigs(Map<String, AtomicLongConfig> atomicLongConfigs) { this.atomicLongConfigs.clear(); this.atomicLongConfigs.putAll(atomicLongConfigs); for (Entry<String, AtomicLongConfig> entry : atomicLongConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
java
public Config setAtomicLongConfigs(Map<String, AtomicLongConfig> atomicLongConfigs) { this.atomicLongConfigs.clear(); this.atomicLongConfigs.putAll(atomicLongConfigs); for (Entry<String, AtomicLongConfig> entry : atomicLongConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
[ "public", "Config", "setAtomicLongConfigs", "(", "Map", "<", "String", ",", "AtomicLongConfig", ">", "atomicLongConfigs", ")", "{", "this", ".", "atomicLongConfigs", ".", "clear", "(", ")", ";", "this", ".", "atomicLongConfigs", ".", "putAll", "(", "atomicLongCo...
Sets the map of AtomicLong configurations, mapped by config name. The config name may be a pattern with which the configuration will be obtained in the future. @param atomicLongConfigs the AtomicLong configuration map to set @return this config instance
[ "Sets", "the", "map", "of", "AtomicLong", "configurations", "mapped", "by", "config", "name", ".", "The", "config", "name", "may", "be", "a", "pattern", "with", "which", "the", "configuration", "will", "be", "obtained", "in", "the", "future", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L1390-L1397
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java
ApiOvhDedicatedCloud.serviceName_globalTasks_GET
public ArrayList<Long> serviceName_globalTasks_GET(String serviceName, Long datacenterId, Date endDate_from, Date endDate_to, Date executionDate_from, Date executionDate_to, Long filerId, Long hostId, Date lastModificationDate_from, Date lastModificationDate_to, String name, Long networkAccessId, Long orderId, Long parentTaskId, OvhTaskStateEnum[] state, Long userId, Long vlanId) throws IOException { String qPath = "/dedicatedCloud/{serviceName}/globalTasks"; StringBuilder sb = path(qPath, serviceName); query(sb, "datacenterId", datacenterId); query(sb, "endDate.from", endDate_from); query(sb, "endDate.to", endDate_to); query(sb, "executionDate.from", executionDate_from); query(sb, "executionDate.to", executionDate_to); query(sb, "filerId", filerId); query(sb, "hostId", hostId); query(sb, "lastModificationDate.from", lastModificationDate_from); query(sb, "lastModificationDate.to", lastModificationDate_to); query(sb, "name", name); query(sb, "networkAccessId", networkAccessId); query(sb, "orderId", orderId); query(sb, "parentTaskId", parentTaskId); query(sb, "state", state); query(sb, "userId", userId); query(sb, "vlanId", vlanId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t2); }
java
public ArrayList<Long> serviceName_globalTasks_GET(String serviceName, Long datacenterId, Date endDate_from, Date endDate_to, Date executionDate_from, Date executionDate_to, Long filerId, Long hostId, Date lastModificationDate_from, Date lastModificationDate_to, String name, Long networkAccessId, Long orderId, Long parentTaskId, OvhTaskStateEnum[] state, Long userId, Long vlanId) throws IOException { String qPath = "/dedicatedCloud/{serviceName}/globalTasks"; StringBuilder sb = path(qPath, serviceName); query(sb, "datacenterId", datacenterId); query(sb, "endDate.from", endDate_from); query(sb, "endDate.to", endDate_to); query(sb, "executionDate.from", executionDate_from); query(sb, "executionDate.to", executionDate_to); query(sb, "filerId", filerId); query(sb, "hostId", hostId); query(sb, "lastModificationDate.from", lastModificationDate_from); query(sb, "lastModificationDate.to", lastModificationDate_to); query(sb, "name", name); query(sb, "networkAccessId", networkAccessId); query(sb, "orderId", orderId); query(sb, "parentTaskId", parentTaskId); query(sb, "state", state); query(sb, "userId", userId); query(sb, "vlanId", vlanId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t2); }
[ "public", "ArrayList", "<", "Long", ">", "serviceName_globalTasks_GET", "(", "String", "serviceName", ",", "Long", "datacenterId", ",", "Date", "endDate_from", ",", "Date", "endDate_to", ",", "Date", "executionDate_from", ",", "Date", "executionDate_to", ",", "Long"...
Get filtered tasks associated with this Private Cloud REST: GET /dedicatedCloud/{serviceName}/globalTasks @param executionDate_to [required] Filter the tasks by execution date (<=) @param datacenterId [required] Filter the tasks by datacenter Id @param hostId [required] Filter the tasks by host Id @param lastModificationDate_from [required] Filter the tasks by last modification date (>=) @param parentTaskId [required] Filter the tasks by parent task Id @param executionDate_from [required] Filter the tasks by execution date (>=) @param endDate_from [required] Filter the tasks by end date (>=) @param vlanId [required] Filter the tasks by vlan Id @param networkAccessId [required] Filter the tasks by network access Id @param orderId [required] Filter the tasks by order Id @param userId [required] Filter the tasks by user Id @param endDate_to [required] Filter the tasks by end date (<=) @param state [required] Filter the tasks by state @param name [required] Filter the tasks by name @param lastModificationDate_to [required] Filter the tasks by last modification date (<=) @param filerId [required] Filter the tasks by filer Id @param serviceName [required] Domain of the service
[ "Get", "filtered", "tasks", "associated", "with", "this", "Private", "Cloud" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L1012-L1033
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/InstanceInfo.java
InstanceInfo.newBuilder
public static Builder newBuilder(InstanceId instanceId, MachineTypeId machineType) { return new BuilderImpl(instanceId).setMachineType(machineType); }
java
public static Builder newBuilder(InstanceId instanceId, MachineTypeId machineType) { return new BuilderImpl(instanceId).setMachineType(machineType); }
[ "public", "static", "Builder", "newBuilder", "(", "InstanceId", "instanceId", ",", "MachineTypeId", "machineType", ")", "{", "return", "new", "BuilderImpl", "(", "instanceId", ")", ".", "setMachineType", "(", "machineType", ")", ";", "}" ]
Returns a builder for an {@code InstanceInfo} object given the instance identity and the machine type.
[ "Returns", "a", "builder", "for", "an", "{" ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/InstanceInfo.java#L636-L638
zaproxy/zaproxy
src/org/zaproxy/zap/utils/I18N.java
I18N.getString
public String getString(String key, Object... params ) { try { return MessageFormat.format(this.getStringImpl(key), params); } catch (MissingResourceException e) { return handleMissingResourceException(e); } }
java
public String getString(String key, Object... params ) { try { return MessageFormat.format(this.getStringImpl(key), params); } catch (MissingResourceException e) { return handleMissingResourceException(e); } }
[ "public", "String", "getString", "(", "String", "key", ",", "Object", "...", "params", ")", "{", "try", "{", "return", "MessageFormat", ".", "format", "(", "this", ".", "getStringImpl", "(", "key", ")", ",", "params", ")", ";", "}", "catch", "(", "Miss...
Gets the message with the given key, formatted with the given parameters. <p> The message will be obtained either from the core {@link ResourceBundle} or a {@code ResourceBundle} of an add-on (depending on the prefix of the key) and then {@link MessageFormat#format(String, Object...) formatted}. <p> <strong>Note:</strong> This method does not throw a {@code MissingResourceException} if the key does not exist, instead it logs an error and returns the key itself. This avoids breaking ZAP when a resource message is accidentally missing. Use {@link #containsKey(String)} instead to know if a message exists or not. @param key the key. @param params the parameters to format the message. @return the message formatted. @see #getString(String)
[ "Gets", "the", "message", "with", "the", "given", "key", "formatted", "with", "the", "given", "parameters", ".", "<p", ">", "The", "message", "will", "be", "obtained", "either", "from", "the", "core", "{", "@link", "ResourceBundle", "}", "or", "a", "{", ...
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/utils/I18N.java#L261-L267
alkacon/opencms-core
src/org/opencms/workplace/CmsDialog.java
CmsDialog.dialogBlock
public String dialogBlock(int segment, String headline, boolean error) { if (segment == HTML_START) { StringBuffer result = new StringBuffer(512); String errorStyle = ""; if (error) { errorStyle = " dialogerror"; } result.append("<!-- 3D block start -->\n"); result.append("<fieldset class=\"dialogblock\">\n"); if (CmsStringUtil.isNotEmpty(headline)) { result.append("<legend>"); result.append("<span class=\"textbold"); result.append(errorStyle); result.append("\" unselectable=\"on\">"); result.append(headline); result.append("</span></legend>\n"); } return result.toString(); } else { return "</fieldset>\n<!-- 3D block end -->\n"; } }
java
public String dialogBlock(int segment, String headline, boolean error) { if (segment == HTML_START) { StringBuffer result = new StringBuffer(512); String errorStyle = ""; if (error) { errorStyle = " dialogerror"; } result.append("<!-- 3D block start -->\n"); result.append("<fieldset class=\"dialogblock\">\n"); if (CmsStringUtil.isNotEmpty(headline)) { result.append("<legend>"); result.append("<span class=\"textbold"); result.append(errorStyle); result.append("\" unselectable=\"on\">"); result.append(headline); result.append("</span></legend>\n"); } return result.toString(); } else { return "</fieldset>\n<!-- 3D block end -->\n"; } }
[ "public", "String", "dialogBlock", "(", "int", "segment", ",", "String", "headline", ",", "boolean", "error", ")", "{", "if", "(", "segment", "==", "HTML_START", ")", "{", "StringBuffer", "result", "=", "new", "StringBuffer", "(", "512", ")", ";", "String"...
Builds a block with 3D border and optional subheadline in the dialog content area.<p> @param segment the HTML segment (START / END) @param headline the headline String for the block @param error if true, an error block will be created @return 3D block start / end segment
[ "Builds", "a", "block", "with", "3D", "border", "and", "optional", "subheadline", "in", "the", "dialog", "content", "area", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsDialog.java#L545-L567
openengsb/openengsb
components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/performer/TransformationPerformer.java
TransformationPerformer.setObjectToTargetField
private void setObjectToTargetField(String fieldname, Object value) throws Exception { Object toWrite = null; if (fieldname.contains(".")) { String path = StringUtils.substringBeforeLast(fieldname, "."); toWrite = getObjectValue(path, false); } if (toWrite == null && isTemporaryField(fieldname)) { String mapKey = StringUtils.substringAfter(fieldname, "#"); mapKey = StringUtils.substringBefore(mapKey, "."); temporaryFields.put(mapKey, value); return; } String realFieldName = fieldname.contains(".") ? StringUtils.substringAfterLast(fieldname, ".") : fieldname; writeObjectToField(realFieldName, value, toWrite, target); }
java
private void setObjectToTargetField(String fieldname, Object value) throws Exception { Object toWrite = null; if (fieldname.contains(".")) { String path = StringUtils.substringBeforeLast(fieldname, "."); toWrite = getObjectValue(path, false); } if (toWrite == null && isTemporaryField(fieldname)) { String mapKey = StringUtils.substringAfter(fieldname, "#"); mapKey = StringUtils.substringBefore(mapKey, "."); temporaryFields.put(mapKey, value); return; } String realFieldName = fieldname.contains(".") ? StringUtils.substringAfterLast(fieldname, ".") : fieldname; writeObjectToField(realFieldName, value, toWrite, target); }
[ "private", "void", "setObjectToTargetField", "(", "String", "fieldname", ",", "Object", "value", ")", "throws", "Exception", "{", "Object", "toWrite", "=", "null", ";", "if", "(", "fieldname", ".", "contains", "(", "\".\"", ")", ")", "{", "String", "path", ...
Sets the given value object to the field with the field name of the target object. Is also aware of temporary fields.
[ "Sets", "the", "given", "value", "object", "to", "the", "field", "with", "the", "field", "name", "of", "the", "target", "object", ".", "Is", "also", "aware", "of", "temporary", "fields", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/performer/TransformationPerformer.java#L146-L160
deephacks/confit
api-admin/src/main/java/org/deephacks/confit/admin/query/BeanQueryBuilder.java
BeanQueryBuilder.lessThan
public static <A extends Comparable<A>> BeanRestriction lessThan(String property, A value) { return new LessThan(property, value); }
java
public static <A extends Comparable<A>> BeanRestriction lessThan(String property, A value) { return new LessThan(property, value); }
[ "public", "static", "<", "A", "extends", "Comparable", "<", "A", ">", ">", "BeanRestriction", "lessThan", "(", "String", "property", ",", "A", "value", ")", "{", "return", "new", "LessThan", "(", "property", ",", "value", ")", ";", "}" ]
Query which asserts that a property is less than (but not equal to) a value. @param property field to query @param value value to query for @return restriction to be added to {@link BeanQuery}.
[ "Query", "which", "asserts", "that", "a", "property", "is", "less", "than", "(", "but", "not", "equal", "to", ")", "a", "value", "." ]
train
https://github.com/deephacks/confit/blob/4e6d4ee5fed32cbc5104433e61de1bcf1b360832/api-admin/src/main/java/org/deephacks/confit/admin/query/BeanQueryBuilder.java#L69-L72
OpenBEL/openbel-framework
org.openbel.framework.common/src/main/java/org/openbel/framework/common/BELUtilities.java
BELUtilities.asPath
public static String asPath(final String directory, final String filename) { return directory.concat(separator).concat(filename); }
java
public static String asPath(final String directory, final String filename) { return directory.concat(separator).concat(filename); }
[ "public", "static", "String", "asPath", "(", "final", "String", "directory", ",", "final", "String", "filename", ")", "{", "return", "directory", ".", "concat", "(", "separator", ")", ".", "concat", "(", "filename", ")", ";", "}" ]
Inserts the platform-specific filesystem path separator between {@code directory} and {@code filename} and returns the resulting string. @param directory Non-null string @param filename Non-null string @return String following the format {@code directory<path_separator>filename}
[ "Inserts", "the", "platform", "-", "specific", "filesystem", "path", "separator", "between", "{", "@code", "directory", "}", "and", "{", "@code", "filename", "}", "and", "returns", "the", "resulting", "string", "." ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/BELUtilities.java#L155-L157
foundation-runtime/service-directory
2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java
DirectoryServiceClient.getService
public ModelService getService(String serviceName, Watcher watcher){ WatcherRegistration wcb = null; if (watcher != null) { wcb = new WatcherRegistration(serviceName, watcher); } ProtocolHeader header = new ProtocolHeader(); header.setType(ProtocolType.GetService); GetServiceProtocol p = new GetServiceProtocol(serviceName); p.setWatcher(watcher != null); GetServiceResponse resp ; resp = (GetServiceResponse) connection.submitRequest(header, p, wcb); return resp.getService(); }
java
public ModelService getService(String serviceName, Watcher watcher){ WatcherRegistration wcb = null; if (watcher != null) { wcb = new WatcherRegistration(serviceName, watcher); } ProtocolHeader header = new ProtocolHeader(); header.setType(ProtocolType.GetService); GetServiceProtocol p = new GetServiceProtocol(serviceName); p.setWatcher(watcher != null); GetServiceResponse resp ; resp = (GetServiceResponse) connection.submitRequest(header, p, wcb); return resp.getService(); }
[ "public", "ModelService", "getService", "(", "String", "serviceName", ",", "Watcher", "watcher", ")", "{", "WatcherRegistration", "wcb", "=", "null", ";", "if", "(", "watcher", "!=", "null", ")", "{", "wcb", "=", "new", "WatcherRegistration", "(", "serviceName...
Get the Service. @param serviceName the serviceName. @param watcher the Watcher. @return the ModelService.
[ "Get", "the", "Service", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java#L686-L700
prestodb/presto
presto-main/src/main/java/com/facebook/presto/execution/executor/MultilevelSplitQueue.java
MultilevelSplitQueue.updatePriority
public Priority updatePriority(Priority oldPriority, long quantaNanos, long scheduledNanos) { int oldLevel = oldPriority.getLevel(); int newLevel = computeLevel(scheduledNanos); long levelContribution = Math.min(quantaNanos, LEVEL_CONTRIBUTION_CAP); if (oldLevel == newLevel) { addLevelTime(oldLevel, levelContribution); return new Priority(oldLevel, oldPriority.getLevelPriority() + quantaNanos); } long remainingLevelContribution = levelContribution; long remainingTaskTime = quantaNanos; // a task normally slowly accrues scheduled time in a level and then moves to the next, but // if the split had a particularly long quanta, accrue time to each level as if it had run // in that level up to the level limit. for (int currentLevel = oldLevel; currentLevel < newLevel; currentLevel++) { long timeAccruedToLevel = Math.min(SECONDS.toNanos(LEVEL_THRESHOLD_SECONDS[currentLevel + 1] - LEVEL_THRESHOLD_SECONDS[currentLevel]), remainingLevelContribution); addLevelTime(currentLevel, timeAccruedToLevel); remainingLevelContribution -= timeAccruedToLevel; remainingTaskTime -= timeAccruedToLevel; } addLevelTime(newLevel, remainingLevelContribution); long newLevelMinPriority = getLevelMinPriority(newLevel, scheduledNanos); return new Priority(newLevel, newLevelMinPriority + remainingTaskTime); }
java
public Priority updatePriority(Priority oldPriority, long quantaNanos, long scheduledNanos) { int oldLevel = oldPriority.getLevel(); int newLevel = computeLevel(scheduledNanos); long levelContribution = Math.min(quantaNanos, LEVEL_CONTRIBUTION_CAP); if (oldLevel == newLevel) { addLevelTime(oldLevel, levelContribution); return new Priority(oldLevel, oldPriority.getLevelPriority() + quantaNanos); } long remainingLevelContribution = levelContribution; long remainingTaskTime = quantaNanos; // a task normally slowly accrues scheduled time in a level and then moves to the next, but // if the split had a particularly long quanta, accrue time to each level as if it had run // in that level up to the level limit. for (int currentLevel = oldLevel; currentLevel < newLevel; currentLevel++) { long timeAccruedToLevel = Math.min(SECONDS.toNanos(LEVEL_THRESHOLD_SECONDS[currentLevel + 1] - LEVEL_THRESHOLD_SECONDS[currentLevel]), remainingLevelContribution); addLevelTime(currentLevel, timeAccruedToLevel); remainingLevelContribution -= timeAccruedToLevel; remainingTaskTime -= timeAccruedToLevel; } addLevelTime(newLevel, remainingLevelContribution); long newLevelMinPriority = getLevelMinPriority(newLevel, scheduledNanos); return new Priority(newLevel, newLevelMinPriority + remainingTaskTime); }
[ "public", "Priority", "updatePriority", "(", "Priority", "oldPriority", ",", "long", "quantaNanos", ",", "long", "scheduledNanos", ")", "{", "int", "oldLevel", "=", "oldPriority", ".", "getLevel", "(", ")", ";", "int", "newLevel", "=", "computeLevel", "(", "sc...
Presto 'charges' the quanta run time to the task <i>and</i> the level it belongs to in an effort to maintain the target thread utilization ratios between levels and to maintain fairness within a level. <p> Consider an example split where a read hung for several minutes. This is either a bug or a failing dependency. In either case we do not want to charge the task too much, and we especially do not want to charge the level too much - i.e. cause other queries in this level to starve. @return the new priority for the task
[ "Presto", "charges", "the", "quanta", "run", "time", "to", "the", "task", "<i", ">", "and<", "/", "i", ">", "the", "level", "it", "belongs", "to", "in", "an", "effort", "to", "maintain", "the", "target", "thread", "utilization", "ratios", "between", "lev...
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/execution/executor/MultilevelSplitQueue.java#L217-L245