repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
188
func_name
stringlengths
7
127
whole_func_string
stringlengths
77
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
77
3.91k
func_code_tokens
listlengths
20
745
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
477
split_name
stringclasses
1 value
func_code_url
stringlengths
111
288
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/nio/ch/NativeObject.java
NativeObject.putObject
void putObject(int offset, NativeObject ob) { switch (addressSize()) { case 8: putLong(offset, ob.address); break; case 4: putInt(offset, (int)(ob.address & 0x00000000FFFFFFFF)); break; default: throw new InternalError("Address size not supported"); } }
java
void putObject(int offset, NativeObject ob) { switch (addressSize()) { case 8: putLong(offset, ob.address); break; case 4: putInt(offset, (int)(ob.address & 0x00000000FFFFFFFF)); break; default: throw new InternalError("Address size not supported"); } }
[ "void", "putObject", "(", "int", "offset", ",", "NativeObject", "ob", ")", "{", "switch", "(", "addressSize", "(", ")", ")", "{", "case", "8", ":", "putLong", "(", "offset", ",", "ob", ".", "address", ")", ";", "break", ";", "case", "4", ":", "putI...
Writes the base address of the given native object at the given offset of this native object. @param offset The offset at which the address is to be written. Note that the size of an address is implementation-dependent. @param ob The native object whose address is to be written
[ "Writes", "the", "base", "address", "of", "the", "given", "native", "object", "at", "the", "given", "offset", "of", "this", "native", "object", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/nio/ch/NativeObject.java#L150-L161
javagl/ND
nd-tuples/src/main/java/de/javagl/nd/tuples/j/LongTuples.java
LongTuples.of
public static MutableLongTuple of(long x, long y, long z, long w) { return new DefaultLongTuple(new long[]{ x, y, z, w }); }
java
public static MutableLongTuple of(long x, long y, long z, long w) { return new DefaultLongTuple(new long[]{ x, y, z, w }); }
[ "public", "static", "MutableLongTuple", "of", "(", "long", "x", ",", "long", "y", ",", "long", "z", ",", "long", "w", ")", "{", "return", "new", "DefaultLongTuple", "(", "new", "long", "[", "]", "{", "x", ",", "y", ",", "z", ",", "w", "}", ")", ...
Creates a new {@link MutableLongTuple} with the given values. @param x The x coordinate @param y The y coordinate @param z The z coordinate @param w The w coordinate @return The new tuple
[ "Creates", "a", "new", "{", "@link", "MutableLongTuple", "}", "with", "the", "given", "values", "." ]
train
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/j/LongTuples.java#L1510-L1513
seedstack/business
core/src/main/java/org/seedstack/business/spi/BaseDtoInfoResolver.java
BaseDtoInfoResolver.createFromFactory
protected <A extends AggregateRoot<?>> A createFromFactory(Class<A> aggregateClass, Object... parameters) { checkNotNull(aggregateClass); checkNotNull(parameters); Factory<A> factory = domainRegistry.getFactory(aggregateClass); // Find the method in the factory which match the signature determined with the previously // extracted parameters Method factoryMethod; boolean useDefaultFactory = false; try { factoryMethod = MethodMatcher.findMatchingMethod(factory.getClass(), aggregateClass, parameters); if (factoryMethod == null) { useDefaultFactory = true; } } catch (Exception e) { throw BusinessException.wrap(e, BusinessErrorCode.UNABLE_TO_FIND_FACTORY_METHOD) .put("aggregateClass", aggregateClass.getName()) .put("parameters", Arrays.toString(parameters)); } // Invoke the factory to create the aggregate root try { if (useDefaultFactory) { return factory.create(parameters); } else { if (parameters.length == 0) { return ReflectUtils.invoke(factoryMethod, factory); } else { return ReflectUtils.invoke(factoryMethod, factory, parameters); } } } catch (Exception e) { throw BusinessException.wrap(e, BusinessErrorCode.UNABLE_TO_INVOKE_FACTORY_METHOD) .put("aggregateClass", aggregateClass.getName()) .put("factoryClass", factory.getClass() .getName()) .put("factoryMethod", Optional.ofNullable(factoryMethod) .map(Method::getName) .orElse("create")) .put("parameters", Arrays.toString(parameters)); } }
java
protected <A extends AggregateRoot<?>> A createFromFactory(Class<A> aggregateClass, Object... parameters) { checkNotNull(aggregateClass); checkNotNull(parameters); Factory<A> factory = domainRegistry.getFactory(aggregateClass); // Find the method in the factory which match the signature determined with the previously // extracted parameters Method factoryMethod; boolean useDefaultFactory = false; try { factoryMethod = MethodMatcher.findMatchingMethod(factory.getClass(), aggregateClass, parameters); if (factoryMethod == null) { useDefaultFactory = true; } } catch (Exception e) { throw BusinessException.wrap(e, BusinessErrorCode.UNABLE_TO_FIND_FACTORY_METHOD) .put("aggregateClass", aggregateClass.getName()) .put("parameters", Arrays.toString(parameters)); } // Invoke the factory to create the aggregate root try { if (useDefaultFactory) { return factory.create(parameters); } else { if (parameters.length == 0) { return ReflectUtils.invoke(factoryMethod, factory); } else { return ReflectUtils.invoke(factoryMethod, factory, parameters); } } } catch (Exception e) { throw BusinessException.wrap(e, BusinessErrorCode.UNABLE_TO_INVOKE_FACTORY_METHOD) .put("aggregateClass", aggregateClass.getName()) .put("factoryClass", factory.getClass() .getName()) .put("factoryMethod", Optional.ofNullable(factoryMethod) .map(Method::getName) .orElse("create")) .put("parameters", Arrays.toString(parameters)); } }
[ "protected", "<", "A", "extends", "AggregateRoot", "<", "?", ">", ">", "A", "createFromFactory", "(", "Class", "<", "A", ">", "aggregateClass", ",", "Object", "...", "parameters", ")", "{", "checkNotNull", "(", "aggregateClass", ")", ";", "checkNotNull", "("...
Implements the logic to create an aggregate. @param aggregateClass the aggregate class. @param parameters the parameters to pass to the factory if any. @param <A> the type of the aggregate root. @return the aggregate root.
[ "Implements", "the", "logic", "to", "create", "an", "aggregate", "." ]
train
https://github.com/seedstack/business/blob/55b3e861fe152e9b125ebc69daa91a682deeae8a/core/src/main/java/org/seedstack/business/spi/BaseDtoInfoResolver.java#L75-L117
aoindustries/aoweb-framework
src/main/java/com/aoindustries/website/framework/WebPage.java
WebPage.doGet
protected void doGet(WebSiteRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException { WebPageLayout layout=getWebPageLayout(req); ChainWriter out=getHTMLChainWriter(req, resp); try { layout.startHTML(this, req, resp, out, null); doGet(out, req, resp); layout.endHTML(this, req, resp, out); } finally { out.flush(); out.close(); } }
java
protected void doGet(WebSiteRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException { WebPageLayout layout=getWebPageLayout(req); ChainWriter out=getHTMLChainWriter(req, resp); try { layout.startHTML(this, req, resp, out, null); doGet(out, req, resp); layout.endHTML(this, req, resp, out); } finally { out.flush(); out.close(); } }
[ "protected", "void", "doGet", "(", "WebSiteRequest", "req", ",", "HttpServletResponse", "resp", ")", "throws", "ServletException", ",", "IOException", ",", "SQLException", "{", "WebPageLayout", "layout", "=", "getWebPageLayout", "(", "req", ")", ";", "ChainWriter", ...
The layout is automatically applied to the page, then <code>doGet</code> is called. To not have this automatically applied, override this method. By the time this method is called, security checks, authentication, and redirects have been done.<br /> <br /> The first thing this method does is print the frameset if needed. Second, it uses the output cache to quickly print the output if possible. And third, it will call doGet(ChainWriter,WebSiteRequest,HttpServletResponse) with a stream directly out if the first two actions were not taken. @see #doGet(ChainWriter,WebSiteRequest,HttpServletResponse)
[ "The", "layout", "is", "automatically", "applied", "to", "the", "page", "then", "<code", ">", "doGet<", "/", "code", ">", "is", "called", ".", "To", "not", "have", "this", "automatically", "applied", "override", "this", "method", ".", "By", "the", "time", ...
train
https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L348-L360
nakamura5akihito/six-util
src/main/java/jp/go/aist/six/util/search/RelationalBinding.java
RelationalBinding.greaterEqualBinding
public static RelationalBinding greaterEqualBinding( final String property, final Object value ) { return (new RelationalBinding( property, Relation.GREATER_EQUAL, value )); }
java
public static RelationalBinding greaterEqualBinding( final String property, final Object value ) { return (new RelationalBinding( property, Relation.GREATER_EQUAL, value )); }
[ "public", "static", "RelationalBinding", "greaterEqualBinding", "(", "final", "String", "property", ",", "final", "Object", "value", ")", "{", "return", "(", "new", "RelationalBinding", "(", "property", ",", "Relation", ".", "GREATER_EQUAL", ",", "value", ")", "...
Creates a 'GREATER_EQUAL' binding. @param property the property. @param value the value to which the property should be related. @return a 'GREATER_EQUAL' binding.
[ "Creates", "a", "GREATER_EQUAL", "binding", "." ]
train
https://github.com/nakamura5akihito/six-util/blob/a6db388a345e220cea2b1fa6324d15c80c6278b6/src/main/java/jp/go/aist/six/util/search/RelationalBinding.java#L150-L156
banq/jdonframework
src/main/java/com/jdon/util/RequestUtil.java
RequestUtil.setCookie
public static void setCookie(HttpServletResponse response, String name, String value, String path) { Cookie cookie = new Cookie(name, value); cookie.setSecure(false); cookie.setPath(path); cookie.setMaxAge(3600 * 24 * 30); // 30 days response.addCookie(cookie); }
java
public static void setCookie(HttpServletResponse response, String name, String value, String path) { Cookie cookie = new Cookie(name, value); cookie.setSecure(false); cookie.setPath(path); cookie.setMaxAge(3600 * 24 * 30); // 30 days response.addCookie(cookie); }
[ "public", "static", "void", "setCookie", "(", "HttpServletResponse", "response", ",", "String", "name", ",", "String", "value", ",", "String", "path", ")", "{", "Cookie", "cookie", "=", "new", "Cookie", "(", "name", ",", "value", ")", ";", "cookie", ".", ...
Convenience method to set a cookie @param response @param name @param value @param path @return HttpServletResponse
[ "Convenience", "method", "to", "set", "a", "cookie" ]
train
https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/RequestUtil.java#L182-L190
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/GitLabApiForm.java
GitLabApiForm.withParam
public GitLabApiForm withParam(String name, Object value) throws IllegalArgumentException { return (withParam(name, value, false)); }
java
public GitLabApiForm withParam(String name, Object value) throws IllegalArgumentException { return (withParam(name, value, false)); }
[ "public", "GitLabApiForm", "withParam", "(", "String", "name", ",", "Object", "value", ")", "throws", "IllegalArgumentException", "{", "return", "(", "withParam", "(", "name", ",", "value", ",", "false", ")", ")", ";", "}" ]
Fluent method for adding query and form parameters to a get() or post() call. @param name the name of the field/attribute to add @param value the value of the field/attribute to add @return this GitLabAPiForm instance
[ "Fluent", "method", "for", "adding", "query", "and", "form", "parameters", "to", "a", "get", "()", "or", "post", "()", "call", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GitLabApiForm.java#L46-L48
TakahikoKawasaki/nv-cipher
src/main/java/com/neovisionaries/security/CodecCipher.java
CodecCipher.setInit
public CodecCipher setInit(Key key) throws IllegalArgumentException { return setInit(key, null, null, null); }
java
public CodecCipher setInit(Key key) throws IllegalArgumentException { return setInit(key, null, null, null); }
[ "public", "CodecCipher", "setInit", "(", "Key", "key", ")", "throws", "IllegalArgumentException", "{", "return", "setInit", "(", "key", ",", "null", ",", "null", ",", "null", ")", ";", "}" ]
Set cipher initialization parameters. <p> If this method is used to set initialization parameters, {@link Cipher#init(int, Key) Cipher.init(mode, (Key)key)} is called later from within {@code encrypt}/{@code decrypt} methods. </p> @param key @return {@code this} object. @throws IllegalArgumentException {@code key} is {@code null}.
[ "Set", "cipher", "initialization", "parameters", "." ]
train
https://github.com/TakahikoKawasaki/nv-cipher/blob/d01aa4f53611e2724ae03633060f55bacf549175/src/main/java/com/neovisionaries/security/CodecCipher.java#L721-L724
h2oai/h2o-2
src/main/java/water/api/Models.java
Models.summarizeDeepLearningModel
private static void summarizeDeepLearningModel(ModelSummary summary, hex.deeplearning.DeepLearningModel model) { // add generic fields such as column names summarizeModelCommonFields(summary, model); summary.model_algorithm = "DeepLearning"; JsonObject all_params = (model.get_params()).toJSON(); summary.critical_parameters = whitelistJsonObject(all_params, DL_critical_params); summary.secondary_parameters = whitelistJsonObject(all_params, DL_secondary_params); summary.expert_parameters = whitelistJsonObject(all_params, DL_expert_params); }
java
private static void summarizeDeepLearningModel(ModelSummary summary, hex.deeplearning.DeepLearningModel model) { // add generic fields such as column names summarizeModelCommonFields(summary, model); summary.model_algorithm = "DeepLearning"; JsonObject all_params = (model.get_params()).toJSON(); summary.critical_parameters = whitelistJsonObject(all_params, DL_critical_params); summary.secondary_parameters = whitelistJsonObject(all_params, DL_secondary_params); summary.expert_parameters = whitelistJsonObject(all_params, DL_expert_params); }
[ "private", "static", "void", "summarizeDeepLearningModel", "(", "ModelSummary", "summary", ",", "hex", ".", "deeplearning", ".", "DeepLearningModel", "model", ")", "{", "// add generic fields such as column names", "summarizeModelCommonFields", "(", "summary", ",", "model",...
Summarize fields which are specific to hex.deeplearning.DeepLearningModel.
[ "Summarize", "fields", "which", "are", "specific", "to", "hex", ".", "deeplearning", ".", "DeepLearningModel", "." ]
train
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/api/Models.java#L311-L321
googleads/googleads-java-lib
modules/ads_lib/src/main/java/com/google/api/ads/admanager/lib/utils/DateTimesHelper.java
DateTimesHelper.toStringForTimeZone
public String toStringForTimeZone(T dateTime, String newZoneID) { return toDateTime(dateTime) .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone(newZoneID))) .toString(ISODateTimeFormat.dateHourMinuteSecond()); }
java
public String toStringForTimeZone(T dateTime, String newZoneID) { return toDateTime(dateTime) .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone(newZoneID))) .toString(ISODateTimeFormat.dateHourMinuteSecond()); }
[ "public", "String", "toStringForTimeZone", "(", "T", "dateTime", ",", "String", "newZoneID", ")", "{", "return", "toDateTime", "(", "dateTime", ")", ".", "withZone", "(", "DateTimeZone", ".", "forTimeZone", "(", "TimeZone", ".", "getTimeZone", "(", "newZoneID", ...
Returns string representation of this date time with a different time zone, preserving the millisecond instant. <p>This method is useful for finding the local time in another time zone, especially for filtering. <p>For example, if this date time holds 12:30 in Europe/London, the result from this method with Europe/Paris would be 13:30. You may also want to use this with your network's time zone, i.e. <pre><code> String timeZoneId = networkService.getCurrentNetwork().getTimeZone(); String statementPart = "startDateTime > " + DateTimes.toString(apiDateTime, timeZoneId); //... statementBuilder.where(statementPart); </code></pre> This method is in the same style of {@link DateTime#withZone(org.joda.time.DateTimeZone)}. @param dateTime the date time to stringify into a new time zone @param newZoneID the time zone ID of the new zone @return a string representation of the {@code DateTime} in {@code yyyy-MM-dd'T'HH:mm:ss}
[ "Returns", "string", "representation", "of", "this", "date", "time", "with", "a", "different", "time", "zone", "preserving", "the", "millisecond", "instant", ".", "<p", ">", "This", "method", "is", "useful", "for", "finding", "the", "local", "time", "in", "a...
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/ads_lib/src/main/java/com/google/api/ads/admanager/lib/utils/DateTimesHelper.java#L240-L244
Netflix/ndbench
ndbench-es-plugins/src/main/java/com/netflix/ndbench/plugin/es/EsAutoTuner.java
EsAutoTuner.recommendNewRate
double recommendNewRate(double currentRateLimit, List<WriteResult> event, NdBenchMonitor runStats) { long currentTime = new Date().getTime(); if (timeOfFirstAutoTuneRequest < 0) { // race condition here when multiple writers, but can be ignored timeOfFirstAutoTuneRequest = currentTime; } // Keep rate at current rate if calculated write failure ratio meets or exceeds configured threshold, // But don't even do this check if a divide by zero error would result from calculating the write // failure ratio via the formula: writesFailures / writeSuccesses // if (runStats.getWriteSuccess() > 0) { double calculatedFailureRatio = runStats.getWriteFailure() / (1.0 * runStats.getWriteSuccess()); if (calculatedFailureRatio >= autoTuneFailureRatioThreshold) { crossedAllowedFailureThreshold = true; logger.info( "Not considering increase of write rate limit. calculatedFailureRatio={}. threshold={}", calculatedFailureRatio, autoTuneFailureRatioThreshold); return currentRateLimit; } else { // by forgetting we crossed threshold and resetting timeOfFirstAutoTuneRequest we allow the // write rate to drop back down to the specified initial value and we get another shot at // trying to step wise increase to the max rate. if (crossedAllowedFailureThreshold) { crossedAllowedFailureThreshold = false; timeOfFirstAutoTuneRequest = currentTime; } } } return rateIncreaser.getRateForGivenClockTime(timeOfFirstAutoTuneRequest, currentTime); }
java
double recommendNewRate(double currentRateLimit, List<WriteResult> event, NdBenchMonitor runStats) { long currentTime = new Date().getTime(); if (timeOfFirstAutoTuneRequest < 0) { // race condition here when multiple writers, but can be ignored timeOfFirstAutoTuneRequest = currentTime; } // Keep rate at current rate if calculated write failure ratio meets or exceeds configured threshold, // But don't even do this check if a divide by zero error would result from calculating the write // failure ratio via the formula: writesFailures / writeSuccesses // if (runStats.getWriteSuccess() > 0) { double calculatedFailureRatio = runStats.getWriteFailure() / (1.0 * runStats.getWriteSuccess()); if (calculatedFailureRatio >= autoTuneFailureRatioThreshold) { crossedAllowedFailureThreshold = true; logger.info( "Not considering increase of write rate limit. calculatedFailureRatio={}. threshold={}", calculatedFailureRatio, autoTuneFailureRatioThreshold); return currentRateLimit; } else { // by forgetting we crossed threshold and resetting timeOfFirstAutoTuneRequest we allow the // write rate to drop back down to the specified initial value and we get another shot at // trying to step wise increase to the max rate. if (crossedAllowedFailureThreshold) { crossedAllowedFailureThreshold = false; timeOfFirstAutoTuneRequest = currentTime; } } } return rateIncreaser.getRateForGivenClockTime(timeOfFirstAutoTuneRequest, currentTime); }
[ "double", "recommendNewRate", "(", "double", "currentRateLimit", ",", "List", "<", "WriteResult", ">", "event", ",", "NdBenchMonitor", "runStats", ")", "{", "long", "currentTime", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "if", "(", "tim...
Recommends the new write rate potentially taking into account the current rate, the result of the last write and statistics accumulated to date. Currently only the success-to-failure ratio is considered and compared against {@link com.netflix.ndbench.core.config.IConfiguration#getAutoTuneWriteFailureRatioThreshold()} Note that we can ignore the possible race condition that arises if multiple threads call this method at around the same time. In this case two threads will be attempting to set timeOfFirstAutoTuneRequest.. but the target values they are using to set this variable be so close it will not affect the desired behavior of the auto-tuning feature. Note 2: this method will only be called after the ndbench driver tries to perform a writeSingle operation
[ "Recommends", "the", "new", "write", "rate", "potentially", "taking", "into", "account", "the", "current", "rate", "the", "result", "of", "the", "last", "write", "and", "statistics", "accumulated", "to", "date", ".", "Currently", "only", "the", "success", "-",...
train
https://github.com/Netflix/ndbench/blob/8d664244b5f9d01395248a296b86a3c822e6d764/ndbench-es-plugins/src/main/java/com/netflix/ndbench/plugin/es/EsAutoTuner.java#L72-L103
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/relatedsamples/KendallTauCorrelation.java
KendallTauCorrelation.scoreToPvalue
private static double scoreToPvalue(double score, int n) { double variance=2.0*(2.0*n+5.0)/(9.0*n*(n-1.0)); double Z=score/Math.sqrt(variance); //follows approximately Normal with 0 mean and variance as calculated above return ContinuousDistributions.gaussCdf(Z); }
java
private static double scoreToPvalue(double score, int n) { double variance=2.0*(2.0*n+5.0)/(9.0*n*(n-1.0)); double Z=score/Math.sqrt(variance); //follows approximately Normal with 0 mean and variance as calculated above return ContinuousDistributions.gaussCdf(Z); }
[ "private", "static", "double", "scoreToPvalue", "(", "double", "score", ",", "int", "n", ")", "{", "double", "variance", "=", "2.0", "*", "(", "2.0", "*", "n", "+", "5.0", ")", "/", "(", "9.0", "*", "n", "*", "(", "n", "-", "1.0", ")", ")", ";"...
Returns the Pvalue for a particular score @param score @param n @return
[ "Returns", "the", "Pvalue", "for", "a", "particular", "score" ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/relatedsamples/KendallTauCorrelation.java#L127-L133
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/AbstractValueData.java
AbstractValueData.validateAndAdjustLenght
protected long validateAndAdjustLenght(long length, long position, long dataLength) throws IOException { if (position < 0) { throw new IOException("Position must be higher or equals 0. But given " + position); } if (length < 0) { throw new IOException("Length must be higher or equals 0. But given " + length); } if (position >= dataLength && position > 0) { throw new IOException("Position " + position + " out of value size " + dataLength); } if (position + length >= dataLength) { return dataLength - position; } return length; }
java
protected long validateAndAdjustLenght(long length, long position, long dataLength) throws IOException { if (position < 0) { throw new IOException("Position must be higher or equals 0. But given " + position); } if (length < 0) { throw new IOException("Length must be higher or equals 0. But given " + length); } if (position >= dataLength && position > 0) { throw new IOException("Position " + position + " out of value size " + dataLength); } if (position + length >= dataLength) { return dataLength - position; } return length; }
[ "protected", "long", "validateAndAdjustLenght", "(", "long", "length", ",", "long", "position", ",", "long", "dataLength", ")", "throws", "IOException", "{", "if", "(", "position", "<", "0", ")", "{", "throw", "new", "IOException", "(", "\"Position must be highe...
Validate parameters. <code>Length</code> and <code>position</code> should not be negative and <code>length</code> should not be greater than <code>dataLength</code> @return adjusted length of byte to read. Should not be possible to exceed array border.
[ "Validate", "parameters", ".", "<code", ">", "Length<", "/", "code", ">", "and", "<code", ">", "position<", "/", "code", ">", "should", "not", "be", "negative", "and", "<code", ">", "length<", "/", "code", ">", "should", "not", "be", "greater", "than", ...
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/AbstractValueData.java#L148-L171
cose-wg/COSE-JAVA
src/main/java/COSE/Attribute.java
Attribute.AddProtected
@Deprecated public void AddProtected(HeaderKeys label, byte[] value) throws CoseException { addAttribute(label, value, PROTECTED); }
java
@Deprecated public void AddProtected(HeaderKeys label, byte[] value) throws CoseException { addAttribute(label, value, PROTECTED); }
[ "@", "Deprecated", "public", "void", "AddProtected", "(", "HeaderKeys", "label", ",", "byte", "[", "]", "value", ")", "throws", "CoseException", "{", "addAttribute", "(", "label", ",", "value", ",", "PROTECTED", ")", ";", "}" ]
Set an attribute in the protect bucket of the COSE object @param label CBOR object which identifies the attribute in the map @param value byte array of value @deprecated As of COSE 0.9.0, use addAttribute(HeaderKeys, byte[], Attribute.PROTECTED); @exception CoseException COSE Package exception
[ "Set", "an", "attribute", "in", "the", "protect", "bucket", "of", "the", "COSE", "object" ]
train
https://github.com/cose-wg/COSE-JAVA/blob/f972b11ab4c9a18f911bc49a15225a6951cf6f63/src/main/java/COSE/Attribute.java#L205-L208
xmlet/XsdAsmFaster
src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmVisitor.java
XsdAsmVisitor.addVisitorElementMethod
@SuppressWarnings("Duplicates") private static void addVisitorElementMethod(ClassWriter classWriter, String elementName, String apiName) { elementName = getCleanName(elementName); String classType = getFullClassTypeName(elementName, apiName); String classTypeDesc = getFullClassTypeNameDesc(elementName, apiName); MethodVisitor mVisitor = classWriter.visitMethod(ACC_PUBLIC, VISIT_ELEMENT_NAME + elementName, "(" + classTypeDesc + ")V", "<Z::" + elementTypeDesc + ">(L" + classType + "<TZ;>;)V", null); mVisitor.visitCode(); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitVarInsn(ALOAD, 1); mVisitor.visitMethodInsn(INVOKEVIRTUAL, elementVisitorType, VISIT_ELEMENT_NAME, "(" + elementTypeDesc + ")V", false); mVisitor.visitInsn(RETURN); mVisitor.visitMaxs(2, 2); mVisitor.visitEnd(); }
java
@SuppressWarnings("Duplicates") private static void addVisitorElementMethod(ClassWriter classWriter, String elementName, String apiName) { elementName = getCleanName(elementName); String classType = getFullClassTypeName(elementName, apiName); String classTypeDesc = getFullClassTypeNameDesc(elementName, apiName); MethodVisitor mVisitor = classWriter.visitMethod(ACC_PUBLIC, VISIT_ELEMENT_NAME + elementName, "(" + classTypeDesc + ")V", "<Z::" + elementTypeDesc + ">(L" + classType + "<TZ;>;)V", null); mVisitor.visitCode(); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitVarInsn(ALOAD, 1); mVisitor.visitMethodInsn(INVOKEVIRTUAL, elementVisitorType, VISIT_ELEMENT_NAME, "(" + elementTypeDesc + ")V", false); mVisitor.visitInsn(RETURN); mVisitor.visitMaxs(2, 2); mVisitor.visitEnd(); }
[ "@", "SuppressWarnings", "(", "\"Duplicates\"", ")", "private", "static", "void", "addVisitorElementMethod", "(", "ClassWriter", "classWriter", ",", "String", "elementName", ",", "String", "apiName", ")", "{", "elementName", "=", "getCleanName", "(", "elementName", ...
Adds a specific method for a visitElement call. Example: void visitElementHtml(Html<Z> html){ visitElement(html); } @param classWriter The ElementVisitor class {@link ClassWriter}. @param elementName The specific element. @param apiName The name of the generated fluent interface.
[ "Adds", "a", "specific", "method", "for", "a", "visitElement", "call", ".", "Example", ":", "void", "visitElementHtml", "(", "Html<Z", ">", "html", ")", "{", "visitElement", "(", "html", ")", ";", "}" ]
train
https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmVisitor.java#L130-L144
bullhorn/sdk-rest
src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java
StandardBullhornData.handleGetMetaData
protected <T extends BullhornEntity> MetaData<T> handleGetMetaData(Class<T> type, MetaParameter metaParameter, Set<String> fieldSet, Integer privateLabelId) { Map<String, String> uriVariables = restUriVariablesFactory.getUriVariablesForMeta(BullhornEntityInfo.getTypesRestEntityName(type), metaParameter, fieldSet, privateLabelId); return handleGetMetaData(uriVariables, privateLabelId); }
java
protected <T extends BullhornEntity> MetaData<T> handleGetMetaData(Class<T> type, MetaParameter metaParameter, Set<String> fieldSet, Integer privateLabelId) { Map<String, String> uriVariables = restUriVariablesFactory.getUriVariablesForMeta(BullhornEntityInfo.getTypesRestEntityName(type), metaParameter, fieldSet, privateLabelId); return handleGetMetaData(uriVariables, privateLabelId); }
[ "protected", "<", "T", "extends", "BullhornEntity", ">", "MetaData", "<", "T", ">", "handleGetMetaData", "(", "Class", "<", "T", ">", "type", ",", "MetaParameter", "metaParameter", ",", "Set", "<", "String", ">", "fieldSet", ",", "Integer", "privateLabelId", ...
Makes the "meta" api call <p> HttpMethod: GET @param type the BullhornEntity type @param metaParameter additional meta parameters @param fieldSet fields to return meta information about. Pass in null for all fields. @return the MetaData
[ "Makes", "the", "meta", "api", "call", "<p", ">", "HttpMethod", ":", "GET" ]
train
https://github.com/bullhorn/sdk-rest/blob/0c75a141c768bb31510afc3a412c11bd101eca06/src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java#L1241-L1246
Jasig/uPortal
uPortal-portlets/src/main/java/org/apereo/portal/portlets/jsp/JspInvokerPortletController.java
JspInvokerPortletController.addSecurityRoleChecksToModel
private void addSecurityRoleChecksToModel(PortletRequest req, Map<String, Object> model) { PortletPreferences prefs = req.getPreferences(); String[] securityRoles = prefs.getValues(PREF_SECURITY_ROLE_NAMES, new String[] {}); for (int i = 0; i < securityRoles.length; i++) { model.put( "is" + securityRoles[i].replace(" ", "_"), req.isUserInRole(securityRoles[i])); } }
java
private void addSecurityRoleChecksToModel(PortletRequest req, Map<String, Object> model) { PortletPreferences prefs = req.getPreferences(); String[] securityRoles = prefs.getValues(PREF_SECURITY_ROLE_NAMES, new String[] {}); for (int i = 0; i < securityRoles.length; i++) { model.put( "is" + securityRoles[i].replace(" ", "_"), req.isUserInRole(securityRoles[i])); } }
[ "private", "void", "addSecurityRoleChecksToModel", "(", "PortletRequest", "req", ",", "Map", "<", "String", ",", "Object", ">", "model", ")", "{", "PortletPreferences", "prefs", "=", "req", ".", "getPreferences", "(", ")", ";", "String", "[", "]", "securityRol...
Run through the list of configured security roles and add an "is"+Rolename to the model. The security roles must also be defined with a <code>&lt;security-role-ref&gt;</code> element in the portlet.xml. @param req Portlet request @param model Model object to add security indicators to
[ "Run", "through", "the", "list", "of", "configured", "security", "roles", "and", "add", "an", "is", "+", "Rolename", "to", "the", "model", ".", "The", "security", "roles", "must", "also", "be", "defined", "with", "a", "<code", ">", "&lt", ";", "security"...
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/jsp/JspInvokerPortletController.java#L157-L164
ykrasik/jaci
jaci-cli-core/src/main/java/com/github/ykrasik/jaci/cli/param/CliParamParseContext.java
CliParamParseContext.createParamAssistInfo
public ParamAssistInfo createParamAssistInfo(String prefix) throws ParseException { if (nextNamedParam.isPresent()) { // The last parsed value was a call-by-name (ended with '-{paramName}'). // Have that named parameter auto-complete the prefix. final CliParam param = nextNamedParam.get(); final AutoComplete autoComplete = param.autoComplete(prefix); final BoundParams boundParams = new BoundParams(parsedValues, nextNamedParam); return new ParamAssistInfo(boundParams, autoComplete); } final CliParam nextParam = getNextUnboundParam(prefix); // Check if 'prefix' starts with the named parameter call prefix. final AutoComplete autoComplete; if (prefix.startsWith(CliConstants.NAMED_PARAM_PREFIX)) { // Prefix starts with the named parameter call prefix. // Auto complete it with possible unbound parameter names. // TODO: Can also be a negative number... which cannot be auto-completed. final String paramNamePrefix = prefix.substring(1); autoComplete = autoCompleteParamName(paramNamePrefix); } else { // Prefix doesn't start with the named parameter call prefix. // Have the next unbound parameter auto complete it's value. autoComplete = nextParam.autoComplete(prefix); } final BoundParams boundParams = new BoundParams(parsedValues, Opt.of(nextParam)); return new ParamAssistInfo(boundParams, autoComplete); }
java
public ParamAssistInfo createParamAssistInfo(String prefix) throws ParseException { if (nextNamedParam.isPresent()) { // The last parsed value was a call-by-name (ended with '-{paramName}'). // Have that named parameter auto-complete the prefix. final CliParam param = nextNamedParam.get(); final AutoComplete autoComplete = param.autoComplete(prefix); final BoundParams boundParams = new BoundParams(parsedValues, nextNamedParam); return new ParamAssistInfo(boundParams, autoComplete); } final CliParam nextParam = getNextUnboundParam(prefix); // Check if 'prefix' starts with the named parameter call prefix. final AutoComplete autoComplete; if (prefix.startsWith(CliConstants.NAMED_PARAM_PREFIX)) { // Prefix starts with the named parameter call prefix. // Auto complete it with possible unbound parameter names. // TODO: Can also be a negative number... which cannot be auto-completed. final String paramNamePrefix = prefix.substring(1); autoComplete = autoCompleteParamName(paramNamePrefix); } else { // Prefix doesn't start with the named parameter call prefix. // Have the next unbound parameter auto complete it's value. autoComplete = nextParam.autoComplete(prefix); } final BoundParams boundParams = new BoundParams(parsedValues, Opt.of(nextParam)); return new ParamAssistInfo(boundParams, autoComplete); }
[ "public", "ParamAssistInfo", "createParamAssistInfo", "(", "String", "prefix", ")", "throws", "ParseException", "{", "if", "(", "nextNamedParam", ".", "isPresent", "(", ")", ")", "{", "// The last parsed value was a call-by-name (ended with '-{paramName}').", "// Have that na...
Create {@link ParamAssistInfo} out of this context's state (already parsed values, and parameters still needing to be parsed). In case the last argument parsed by the context was a call-by-name (ended with '-{paramName}'), the returned assist info will contain that parameter's auto complete. Otherwise, if the given prefix starts with '-' (call-by-name prefix), the returned assist info will contain suggestions for unbound parameter names. Otherwise the returned assist info will contain suggestions for values for the next unbound positional parameter. @param prefix Prefix to create assistance for. @return A {@link ParamAssistInfo} if the context managed to construct one according to the above rules. @throws ParseException If an error occurred, according to the above rules.
[ "Create", "{", "@link", "ParamAssistInfo", "}", "out", "of", "this", "context", "s", "state", "(", "already", "parsed", "values", "and", "parameters", "still", "needing", "to", "be", "parsed", ")", ".", "In", "case", "the", "last", "argument", "parsed", "b...
train
https://github.com/ykrasik/jaci/blob/4615edef7c76288ad5ea8d678132b161645ca1e3/jaci-cli-core/src/main/java/com/github/ykrasik/jaci/cli/param/CliParamParseContext.java#L214-L241
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/AsyncHbaseSchemaService.java
AsyncHbaseSchemaService._canSkipWhileScanning
private boolean _canSkipWhileScanning(MetricSchemaRecordQuery query, RecordType type) { if( (RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type)) && !SchemaService.containsFilter(query.getTagKey()) && !SchemaService.containsFilter(query.getTagValue()) && !SchemaService.containsFilter(query.getNamespace())) { if(RecordType.METRIC.equals(type) && !SchemaService.containsFilter(query.getMetric())) { return false; } if(RecordType.SCOPE.equals(type) && !SchemaService.containsFilter(query.getScope())) { return false; } return true; } return false; }
java
private boolean _canSkipWhileScanning(MetricSchemaRecordQuery query, RecordType type) { if( (RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type)) && !SchemaService.containsFilter(query.getTagKey()) && !SchemaService.containsFilter(query.getTagValue()) && !SchemaService.containsFilter(query.getNamespace())) { if(RecordType.METRIC.equals(type) && !SchemaService.containsFilter(query.getMetric())) { return false; } if(RecordType.SCOPE.equals(type) && !SchemaService.containsFilter(query.getScope())) { return false; } return true; } return false; }
[ "private", "boolean", "_canSkipWhileScanning", "(", "MetricSchemaRecordQuery", "query", ",", "RecordType", "type", ")", "{", "if", "(", "(", "RecordType", ".", "METRIC", ".", "equals", "(", "type", ")", "||", "RecordType", ".", "SCOPE", ".", "equals", "(", "...
Check if we can perform a faster scan. We can only perform a faster scan when we are trying to discover scopes or metrics without having information on any other fields.
[ "Check", "if", "we", "can", "perform", "a", "faster", "scan", ".", "We", "can", "only", "perform", "a", "faster", "scan", "when", "we", "are", "trying", "to", "discover", "scopes", "or", "metrics", "without", "having", "information", "on", "any", "other", ...
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/AsyncHbaseSchemaService.java#L449-L468
Hygieia/Hygieia
api/src/main/java/com/capitalone/dashboard/service/BusCompOwnerServiceImpl.java
BusCompOwnerServiceImpl.doesMatchFullName
private boolean doesMatchFullName(String firstName, String fullName){ boolean matching = false; if(firstName != null && !firstName.isEmpty() && fullName != null && !fullName.isEmpty()){ String firstFromCMDB; String[] array = fullName.split(" "); firstName = firstName.toLowerCase(); firstFromCMDB = array[0]; firstFromCMDB = firstFromCMDB.toLowerCase(); if(firstFromCMDB.length() < firstName.length()){ if(firstName.indexOf(firstFromCMDB) != -1){ matching = true; } }else if (firstFromCMDB.indexOf(firstName) != -1){ matching = true; } } return matching; }
java
private boolean doesMatchFullName(String firstName, String fullName){ boolean matching = false; if(firstName != null && !firstName.isEmpty() && fullName != null && !fullName.isEmpty()){ String firstFromCMDB; String[] array = fullName.split(" "); firstName = firstName.toLowerCase(); firstFromCMDB = array[0]; firstFromCMDB = firstFromCMDB.toLowerCase(); if(firstFromCMDB.length() < firstName.length()){ if(firstName.indexOf(firstFromCMDB) != -1){ matching = true; } }else if (firstFromCMDB.indexOf(firstName) != -1){ matching = true; } } return matching; }
[ "private", "boolean", "doesMatchFullName", "(", "String", "firstName", ",", "String", "fullName", ")", "{", "boolean", "matching", "=", "false", ";", "if", "(", "firstName", "!=", "null", "&&", "!", "firstName", ".", "isEmpty", "(", ")", "&&", "fullName", ...
Takes first name and full name and returns true or false if first name is found in full name @param firstName @param fullName @return true or false if match found
[ "Takes", "first", "name", "and", "full", "name", "and", "returns", "true", "or", "false", "if", "first", "name", "is", "found", "in", "full", "name" ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/api/src/main/java/com/capitalone/dashboard/service/BusCompOwnerServiceImpl.java#L134-L152
netty/netty
codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionStatus.java
SpdySessionStatus.valueOf
public static SpdySessionStatus valueOf(int code) { switch (code) { case 0: return OK; case 1: return PROTOCOL_ERROR; case 2: return INTERNAL_ERROR; } return new SpdySessionStatus(code, "UNKNOWN (" + code + ')'); }
java
public static SpdySessionStatus valueOf(int code) { switch (code) { case 0: return OK; case 1: return PROTOCOL_ERROR; case 2: return INTERNAL_ERROR; } return new SpdySessionStatus(code, "UNKNOWN (" + code + ')'); }
[ "public", "static", "SpdySessionStatus", "valueOf", "(", "int", "code", ")", "{", "switch", "(", "code", ")", "{", "case", "0", ":", "return", "OK", ";", "case", "1", ":", "return", "PROTOCOL_ERROR", ";", "case", "2", ":", "return", "INTERNAL_ERROR", ";"...
Returns the {@link SpdySessionStatus} represented by the specified code. If the specified code is a defined SPDY status code, a cached instance will be returned. Otherwise, a new instance will be returned.
[ "Returns", "the", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionStatus.java#L46-L57
op4j/op4j
src/main/java/org/op4j/functions/Call.java
Call.setOfString
public static Function<Object,Set<String>> setOfString(final String methodName, final Object... optionalParameters) { return methodForSetOfString(methodName, optionalParameters); }
java
public static Function<Object,Set<String>> setOfString(final String methodName, final Object... optionalParameters) { return methodForSetOfString(methodName, optionalParameters); }
[ "public", "static", "Function", "<", "Object", ",", "Set", "<", "String", ">", ">", "setOfString", "(", "final", "String", "methodName", ",", "final", "Object", "...", "optionalParameters", ")", "{", "return", "methodForSetOfString", "(", "methodName", ",", "o...
<p> Abbreviation for {{@link #methodForSetOfString(String, Object...)}. </p> @since 1.1 @param methodName the name of the method @param optionalParameters the (optional) parameters of the method. @return the result of the method execution
[ "<p", ">", "Abbreviation", "for", "{{", "@link", "#methodForSetOfString", "(", "String", "Object", "...", ")", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/functions/Call.java#L581-L583
actorapp/droidkit-actors
actors/src/main/java/com/droidkit/actors/ActorSystem.java
ActorSystem.actorOf
public <T extends Actor> ActorRef actorOf(Class<T> actor, String path) { return actorOf(Props.create(actor), path); }
java
public <T extends Actor> ActorRef actorOf(Class<T> actor, String path) { return actorOf(Props.create(actor), path); }
[ "public", "<", "T", "extends", "Actor", ">", "ActorRef", "actorOf", "(", "Class", "<", "T", ">", "actor", ",", "String", "path", ")", "{", "return", "actorOf", "(", "Props", ".", "create", "(", "actor", ")", ",", "path", ")", ";", "}" ]
Creating or getting existing actor from actor class @param actor Actor Class @param path Actor Path @param <T> Actor Class @return ActorRef
[ "Creating", "or", "getting", "existing", "actor", "from", "actor", "class" ]
train
https://github.com/actorapp/droidkit-actors/blob/fdb72fcfdd1c5e54a970f203a33a71fa54344217/actors/src/main/java/com/droidkit/actors/ActorSystem.java#L104-L106
alkacon/opencms-core
src/org/opencms/ugc/CmsUgcSession.java
CmsUgcSession.addContentValues
protected CmsXmlContent addContentValues(CmsFile file, Map<String, String> contentValues) throws CmsException { CmsXmlContent content = unmarshalXmlContent(file); Locale locale = m_cms.getRequestContext().getLocale(); addContentValues(content, locale, contentValues); return content; }
java
protected CmsXmlContent addContentValues(CmsFile file, Map<String, String> contentValues) throws CmsException { CmsXmlContent content = unmarshalXmlContent(file); Locale locale = m_cms.getRequestContext().getLocale(); addContentValues(content, locale, contentValues); return content; }
[ "protected", "CmsXmlContent", "addContentValues", "(", "CmsFile", "file", ",", "Map", "<", "String", ",", "String", ">", "contentValues", ")", "throws", "CmsException", "{", "CmsXmlContent", "content", "=", "unmarshalXmlContent", "(", "file", ")", ";", "Locale", ...
Adds the given values to the content document.<p> @param file the content file @param contentValues the values to add @return the content document @throws CmsException if writing the XML fails
[ "Adds", "the", "given", "values", "to", "the", "content", "document", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ugc/CmsUgcSession.java#L579-L586
anotheria/moskito
moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/parser/StatusData.java
StatusData.ensureValueCorrectness
private Object ensureValueCorrectness(T key, Object value) { checkKey(key); if (key.isCorrectValue(value) || value == null) { return value; } if (value instanceof String) { value = key.parseValue(String.class.cast(value)); return value; } throw new IllegalArgumentException("Entry <'"+key+"','"+value+"'> rejected! Value should be of correct type or of type String(for auto-parsing)!"); }
java
private Object ensureValueCorrectness(T key, Object value) { checkKey(key); if (key.isCorrectValue(value) || value == null) { return value; } if (value instanceof String) { value = key.parseValue(String.class.cast(value)); return value; } throw new IllegalArgumentException("Entry <'"+key+"','"+value+"'> rejected! Value should be of correct type or of type String(for auto-parsing)!"); }
[ "private", "Object", "ensureValueCorrectness", "(", "T", "key", ",", "Object", "value", ")", "{", "checkKey", "(", "key", ")", ";", "if", "(", "key", ".", "isCorrectValue", "(", "value", ")", "||", "value", "==", "null", ")", "{", "return", "value", ";...
Ensure that value is of correct type for the given key. If value is not already of correct type but of type String, attempt parsing into correct type. @return provided value if it's correctly typed or parsed value of correct type or {@code null} if auto-conversion failed. @throws IllegalArgumentException if the given key is {@code null} or if value is neither of correct type nor of String type.
[ "Ensure", "that", "value", "is", "of", "correct", "type", "for", "the", "given", "key", ".", "If", "value", "is", "not", "already", "of", "correct", "type", "but", "of", "type", "String", "attempt", "parsing", "into", "correct", "type", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/parser/StatusData.java#L65-L75
casbin/jcasbin
src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java
ManagementEnforcer.removeNamedGroupingPolicy
public boolean removeNamedGroupingPolicy(String ptype, String... params) { return removeNamedGroupingPolicy(ptype, Arrays.asList(params)); }
java
public boolean removeNamedGroupingPolicy(String ptype, String... params) { return removeNamedGroupingPolicy(ptype, Arrays.asList(params)); }
[ "public", "boolean", "removeNamedGroupingPolicy", "(", "String", "ptype", ",", "String", "...", "params", ")", "{", "return", "removeNamedGroupingPolicy", "(", "ptype", ",", "Arrays", ".", "asList", "(", "params", ")", ")", ";", "}" ]
removeNamedGroupingPolicy removes a role inheritance rule from the current named policy. @param ptype the policy type, can be "g", "g2", "g3", .. @param params the "g" policy rule. @return succeeds or not.
[ "removeNamedGroupingPolicy", "removes", "a", "role", "inheritance", "rule", "from", "the", "current", "named", "policy", "." ]
train
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L525-L527
reinert/requestor
requestor/ext/requestor-oauth2/src/main/java/io/reinert/requestor/oauth2/Auth.java
Auth.login
public void login(AuthRequest req, final Callback<TokenInfo, Throwable> callback) { lastRequest = req; lastCallback = callback; String authUrl = req.toUrl(urlCodex) + "&redirect_uri=" + urlCodex.encode(oauthWindowUrl); // Try to look up the token we have stored. final TokenInfo info = getToken(req); if (info == null || info.getExpires() == null || expiringSoon(info)) { // Token wasn't found, or doesn't have an expiration, or is expired or // expiring soon. Requesting access will refresh the token. doLogin(authUrl, callback); } else { // Token was found and is good, immediately execute the callback with the // access token. scheduler.scheduleDeferred(new ScheduledCommand() { @Override public void execute() { callback.onSuccess(info); } }); } }
java
public void login(AuthRequest req, final Callback<TokenInfo, Throwable> callback) { lastRequest = req; lastCallback = callback; String authUrl = req.toUrl(urlCodex) + "&redirect_uri=" + urlCodex.encode(oauthWindowUrl); // Try to look up the token we have stored. final TokenInfo info = getToken(req); if (info == null || info.getExpires() == null || expiringSoon(info)) { // Token wasn't found, or doesn't have an expiration, or is expired or // expiring soon. Requesting access will refresh the token. doLogin(authUrl, callback); } else { // Token was found and is good, immediately execute the callback with the // access token. scheduler.scheduleDeferred(new ScheduledCommand() { @Override public void execute() { callback.onSuccess(info); } }); } }
[ "public", "void", "login", "(", "AuthRequest", "req", ",", "final", "Callback", "<", "TokenInfo", ",", "Throwable", ">", "callback", ")", "{", "lastRequest", "=", "req", ";", "lastCallback", "=", "callback", ";", "String", "authUrl", "=", "req", ".", "toUr...
Request an access token from an OAuth 2.0 provider. <p/> <p> If it can be determined that the user has already granted access, and the token has not yet expired, and that the token will not expire soon, the existing token will be passed to the callback. </p> <p/> <p> Otherwise, a popup window will be displayed which may prompt the user to grant access. If the user has already granted access the popup will immediately close and the token will be passed to the callback. If access hasn't been granted, the user will be prompted, and when they grant, the token will be passed to the callback. </p> @param req Request for authentication. @param callback Callback to pass the token to when access has been granted.
[ "Request", "an", "access", "token", "from", "an", "OAuth", "2", ".", "0", "provider", ".", "<p", "/", ">", "<p", ">", "If", "it", "can", "be", "determined", "that", "the", "user", "has", "already", "granted", "access", "and", "the", "token", "has", "...
train
https://github.com/reinert/requestor/blob/40163a75cd17815d5089935d0dd97b8d652ad6d4/requestor/ext/requestor-oauth2/src/main/java/io/reinert/requestor/oauth2/Auth.java#L73-L96
alkacon/opencms-core
src/org/opencms/staticexport/CmsStaticExportRfsRule.java
CmsStaticExportRfsRule.getLocalizedRfsName
public String getLocalizedRfsName(String rfsName, String fileSeparator) { String locRfsName = null; // this might be too simple locRfsName = CmsStringUtil.substitute( rfsName, fileSeparator + CmsLocaleManager.getDefaultLocale().toString() + fileSeparator, fileSeparator + getName() + fileSeparator); return locRfsName; }
java
public String getLocalizedRfsName(String rfsName, String fileSeparator) { String locRfsName = null; // this might be too simple locRfsName = CmsStringUtil.substitute( rfsName, fileSeparator + CmsLocaleManager.getDefaultLocale().toString() + fileSeparator, fileSeparator + getName() + fileSeparator); return locRfsName; }
[ "public", "String", "getLocalizedRfsName", "(", "String", "rfsName", ",", "String", "fileSeparator", ")", "{", "String", "locRfsName", "=", "null", ";", "// this might be too simple", "locRfsName", "=", "CmsStringUtil", ".", "substitute", "(", "rfsName", ",", "fileS...
Returns the rfs name for the given locale, only used for multi-language export.<p> @param rfsName the original rfs name @param fileSeparator the file separator to use @return the rfs name for the given locale
[ "Returns", "the", "rfs", "name", "for", "the", "given", "locale", "only", "used", "for", "multi", "-", "language", "export", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsStaticExportRfsRule.java#L238-L248
pressgang-ccms/PressGangCCMSBuilder
src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookBuilder.java
DocBookBuilder.createDummyTranslatedTopic
private TranslatedTopicWrapper createDummyTranslatedTopic(final TopicWrapper topic, final LocaleWrapper locale) { final TranslatedTopicWrapper translatedTopic = translatedTopicProvider.newTranslatedTopic(); translatedTopic.setTopic(topic); translatedTopic.setId(topic.getId() * -1); // If we get to this point then no translation exists or the default locale translation failed to be downloaded. translatedTopic.setTopicId(topic.getId()); translatedTopic.setTopicRevision(topic.getRevision()); translatedTopic.setTranslationPercentage(100); translatedTopic.setXml(topic.getXml()); translatedTopic.setTags(topic.getTags()); translatedTopic.setSourceURLs(topic.getSourceURLs()); translatedTopic.setProperties(topic.getProperties()); translatedTopic.setLocale(locale); translatedTopic.setTitle(topic.getTitle()); return translatedTopic; }
java
private TranslatedTopicWrapper createDummyTranslatedTopic(final TopicWrapper topic, final LocaleWrapper locale) { final TranslatedTopicWrapper translatedTopic = translatedTopicProvider.newTranslatedTopic(); translatedTopic.setTopic(topic); translatedTopic.setId(topic.getId() * -1); // If we get to this point then no translation exists or the default locale translation failed to be downloaded. translatedTopic.setTopicId(topic.getId()); translatedTopic.setTopicRevision(topic.getRevision()); translatedTopic.setTranslationPercentage(100); translatedTopic.setXml(topic.getXml()); translatedTopic.setTags(topic.getTags()); translatedTopic.setSourceURLs(topic.getSourceURLs()); translatedTopic.setProperties(topic.getProperties()); translatedTopic.setLocale(locale); translatedTopic.setTitle(topic.getTitle()); return translatedTopic; }
[ "private", "TranslatedTopicWrapper", "createDummyTranslatedTopic", "(", "final", "TopicWrapper", "topic", ",", "final", "LocaleWrapper", "locale", ")", "{", "final", "TranslatedTopicWrapper", "translatedTopic", "=", "translatedTopicProvider", ".", "newTranslatedTopic", "(", ...
Creates a dummy translated topic so that a book can be built using the same relationships as a normal build. @param topic The topic to create the dummy topic from. @param locale The locale to build the dummy translations for. @return The dummy translated topic.
[ "Creates", "a", "dummy", "translated", "topic", "so", "that", "a", "book", "can", "be", "built", "using", "the", "same", "relationships", "as", "a", "normal", "build", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookBuilder.java#L1002-L1019
eclipse/xtext-core
org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/util/NodeModelUtils.java
NodeModelUtils.getLineAndColumn
public static LineAndColumn getLineAndColumn(INode anyNode, int documentOffset) { // special treatment for inconsistent nodes such as SyntheticLinkingLeafNode if (anyNode.getParent() == null && !(anyNode instanceof RootNode)) { return LineAndColumn.from(1,1); } return InternalNodeModelUtils.getLineAndColumn(anyNode, documentOffset); }
java
public static LineAndColumn getLineAndColumn(INode anyNode, int documentOffset) { // special treatment for inconsistent nodes such as SyntheticLinkingLeafNode if (anyNode.getParent() == null && !(anyNode instanceof RootNode)) { return LineAndColumn.from(1,1); } return InternalNodeModelUtils.getLineAndColumn(anyNode, documentOffset); }
[ "public", "static", "LineAndColumn", "getLineAndColumn", "(", "INode", "anyNode", ",", "int", "documentOffset", ")", "{", "// special treatment for inconsistent nodes such as SyntheticLinkingLeafNode", "if", "(", "anyNode", ".", "getParent", "(", ")", "==", "null", "&&", ...
Compute the line and column information at the given offset from any node that belongs the the document. The line is one-based, e.g. the first line has the line number '1'. The line break belongs the line that it breaks. In other words, the first line break in the document also has the line number '1'. The column number starts at '1', too. In effect, the document offset '0' will always return line '1' and column '1'. If the given documentOffset points exactly to {@code anyNode.root.text.length}, it's assumed to be a virtual character thus the offset is valid and the column and line information is returned as if it was there. This contract is in sync with {@link org.eclipse.emf.ecore.resource.Resource.Diagnostic}. @throws IndexOutOfBoundsException if the document offset does not belong to the document, {@code documentOffset < 0 || documentOffset > anyNode.rootNode.text.length}
[ "Compute", "the", "line", "and", "column", "information", "at", "the", "given", "offset", "from", "any", "node", "that", "belongs", "the", "the", "document", ".", "The", "line", "is", "one", "-", "based", "e", ".", "g", ".", "the", "first", "line", "ha...
train
https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/util/NodeModelUtils.java#L125-L131
alkacon/opencms-core
src-modules/org/opencms/workplace/commons/CmsPreferences.java
CmsPreferences.buildSelectCopyFileMode
public String buildSelectCopyFileMode(String htmlAttributes) { List<String> options = new ArrayList<String>(2); options.add(key(Messages.GUI_PREF_COPY_AS_SIBLING_0)); options.add(key(Messages.GUI_COPY_AS_NEW_0)); List<String> values = new ArrayList<String>(2); values.add(CmsResource.COPY_AS_SIBLING.toString()); values.add(CmsResource.COPY_AS_NEW.toString()); int selectedIndex = values.indexOf(getParamTabDiCopyFileMode()); return buildSelect(htmlAttributes, options, values, selectedIndex); }
java
public String buildSelectCopyFileMode(String htmlAttributes) { List<String> options = new ArrayList<String>(2); options.add(key(Messages.GUI_PREF_COPY_AS_SIBLING_0)); options.add(key(Messages.GUI_COPY_AS_NEW_0)); List<String> values = new ArrayList<String>(2); values.add(CmsResource.COPY_AS_SIBLING.toString()); values.add(CmsResource.COPY_AS_NEW.toString()); int selectedIndex = values.indexOf(getParamTabDiCopyFileMode()); return buildSelect(htmlAttributes, options, values, selectedIndex); }
[ "public", "String", "buildSelectCopyFileMode", "(", "String", "htmlAttributes", ")", "{", "List", "<", "String", ">", "options", "=", "new", "ArrayList", "<", "String", ">", "(", "2", ")", ";", "options", ".", "add", "(", "key", "(", "Messages", ".", "GU...
Builds the html for the default copy file mode select box.<p> @param htmlAttributes optional html attributes for the &lgt;select&gt; tag @return the html for the default copy file mode select box
[ "Builds", "the", "html", "for", "the", "default", "copy", "file", "mode", "select", "box", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsPreferences.java#L589-L599
bingoohuang/excel2javabeans
src/main/java/com/github/bingoohuang/excel2beans/PoiUtil.java
PoiUtil.searchRow
public static Cell searchRow(Row row, String searchKey) { if (row == null) return null; for (int j = row.getFirstCellNum(), jj = row.getLastCellNum(); j < jj; ++j) { Cell cell = matchCell(row, j, searchKey); if (cell != null) return cell; } return null; }
java
public static Cell searchRow(Row row, String searchKey) { if (row == null) return null; for (int j = row.getFirstCellNum(), jj = row.getLastCellNum(); j < jj; ++j) { Cell cell = matchCell(row, j, searchKey); if (cell != null) return cell; } return null; }
[ "public", "static", "Cell", "searchRow", "(", "Row", "row", ",", "String", "searchKey", ")", "{", "if", "(", "row", "==", "null", ")", "return", "null", ";", "for", "(", "int", "j", "=", "row", ".", "getFirstCellNum", "(", ")", ",", "jj", "=", "row...
在行中查找。 @param row 行 @param searchKey 单元格中包含的关键字 @return 单元格,没有找到时返回null
[ "在行中查找。" ]
train
https://github.com/bingoohuang/excel2javabeans/blob/db136d460b93b649814366c0d84a982698b96dc3/src/main/java/com/github/bingoohuang/excel2beans/PoiUtil.java#L379-L387
codeprimate-software/cp-elements
src/main/java/org/cp/elements/data/conversion/converters/DateConverter.java
DateConverter.canConvert
@Override public boolean canConvert(Class<?> fromType, Class<?> toType) { return isAssignableTo(fromType, Calendar.class, Date.class, Number.class, String.class) && Date.class.equals(toType); }
java
@Override public boolean canConvert(Class<?> fromType, Class<?> toType) { return isAssignableTo(fromType, Calendar.class, Date.class, Number.class, String.class) && Date.class.equals(toType); }
[ "@", "Override", "public", "boolean", "canConvert", "(", "Class", "<", "?", ">", "fromType", ",", "Class", "<", "?", ">", "toType", ")", "{", "return", "isAssignableTo", "(", "fromType", ",", "Calendar", ".", "class", ",", "Date", ".", "class", ",", "N...
Determines whether this {@link Converter} can convert {@link Object Objects} {@link Class from type} {@link Class to type}. @param fromType {@link Class type} to convert from. @param toType {@link Class type} to convert to. @return a boolean indicating whether this {@link Converter} can convert {@link Object Objects} {@link Class from type} {@link Class to type}. @see org.cp.elements.data.conversion.ConversionService#canConvert(Class, Class) @see #canConvert(Object, Class)
[ "Determines", "whether", "this", "{", "@link", "Converter", "}", "can", "convert", "{", "@link", "Object", "Objects", "}", "{", "@link", "Class", "from", "type", "}", "{", "@link", "Class", "to", "type", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/data/conversion/converters/DateConverter.java#L71-L75
sdaschner/jaxrs-analyzer
src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java
JavaUtils.getAnnotation
public static <A extends Annotation> A getAnnotation(final AnnotatedElement annotatedElement, final Class<A> annotationClass) { final Optional<Annotation> annotation = Stream.of(annotatedElement.getAnnotations()) .filter(a -> a.annotationType().getName().equals(annotationClass.getName())) .findAny(); return (A) annotation.orElse(null); }
java
public static <A extends Annotation> A getAnnotation(final AnnotatedElement annotatedElement, final Class<A> annotationClass) { final Optional<Annotation> annotation = Stream.of(annotatedElement.getAnnotations()) .filter(a -> a.annotationType().getName().equals(annotationClass.getName())) .findAny(); return (A) annotation.orElse(null); }
[ "public", "static", "<", "A", "extends", "Annotation", ">", "A", "getAnnotation", "(", "final", "AnnotatedElement", "annotatedElement", ",", "final", "Class", "<", "A", ">", "annotationClass", ")", "{", "final", "Optional", "<", "Annotation", ">", "annotation", ...
Returns the annotation or {@code null} if the element is not annotated with that type. <b>Note:</b> This step is necessary due to issues with external class loaders (e.g. Maven). The classes may not be identical and are therefore compared by FQ class name.
[ "Returns", "the", "annotation", "or", "{" ]
train
https://github.com/sdaschner/jaxrs-analyzer/blob/4ac62942202d05632977d6c14d3cd7e2d27e2b9b/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java#L66-L71
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/restore/CmsRestoreDialog.java
CmsRestoreDialog.loadAndShow
public void loadAndShow() { CmsRpcAction<CmsRestoreInfoBean> action = new CmsRpcAction<CmsRestoreInfoBean>() { @Override public void execute() { start(0, true); CmsCoreProvider.getVfsService().getRestoreInfo(m_structureId, this); } @Override protected void onResponse(CmsRestoreInfoBean result) { stop(false); m_restoreView = new CmsRestoreView(result, m_afterRestoreAction); m_restoreView.setPopup(CmsRestoreDialog.this); setMainContent(m_restoreView); List<CmsPushButton> buttons = m_restoreView.getDialogButtons(); for (CmsPushButton button : buttons) { addButton(button); } center(); } }; action.execute(); }
java
public void loadAndShow() { CmsRpcAction<CmsRestoreInfoBean> action = new CmsRpcAction<CmsRestoreInfoBean>() { @Override public void execute() { start(0, true); CmsCoreProvider.getVfsService().getRestoreInfo(m_structureId, this); } @Override protected void onResponse(CmsRestoreInfoBean result) { stop(false); m_restoreView = new CmsRestoreView(result, m_afterRestoreAction); m_restoreView.setPopup(CmsRestoreDialog.this); setMainContent(m_restoreView); List<CmsPushButton> buttons = m_restoreView.getDialogButtons(); for (CmsPushButton button : buttons) { addButton(button); } center(); } }; action.execute(); }
[ "public", "void", "loadAndShow", "(", ")", "{", "CmsRpcAction", "<", "CmsRestoreInfoBean", ">", "action", "=", "new", "CmsRpcAction", "<", "CmsRestoreInfoBean", ">", "(", ")", "{", "@", "Override", "public", "void", "execute", "(", ")", "{", "start", "(", ...
Loads the necessary data for the dialog from the server and shows the dialog.<p>
[ "Loads", "the", "necessary", "data", "for", "the", "dialog", "from", "the", "server", "and", "shows", "the", "dialog", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/restore/CmsRestoreDialog.java#L71-L97
bozaro/git-lfs-java
gitlfs-client/src/main/java/ru/bozaro/gitlfs/client/Client.java
Client.getMeta
@Nullable public ObjectRes getMeta(@NotNull final String hash) throws IOException { return doWork(auth -> doRequest(auth, new MetaGet(), AuthHelper.join(auth.getHref(), PATH_OBJECTS + "/" + hash)), Operation.Download); }
java
@Nullable public ObjectRes getMeta(@NotNull final String hash) throws IOException { return doWork(auth -> doRequest(auth, new MetaGet(), AuthHelper.join(auth.getHref(), PATH_OBJECTS + "/" + hash)), Operation.Download); }
[ "@", "Nullable", "public", "ObjectRes", "getMeta", "(", "@", "NotNull", "final", "String", "hash", ")", "throws", "IOException", "{", "return", "doWork", "(", "auth", "->", "doRequest", "(", "auth", ",", "new", "MetaGet", "(", ")", ",", "AuthHelper", ".", ...
Get metadata for object by hash. @param hash Object hash. @return Object metadata or null, if object not found. @throws IOException
[ "Get", "metadata", "for", "object", "by", "hash", "." ]
train
https://github.com/bozaro/git-lfs-java/blob/ee05bf0472ee61bf362cf93d283e5ee5d44ef685/gitlfs-client/src/main/java/ru/bozaro/gitlfs/client/Client.java#L79-L82
moparisthebest/beehive
beehive-netui-tags/src/main/java/org/apache/beehive/netui/databinding/datagrid/runtime/util/JspFunctions.java
JspFunctions.isSortedAscending
public static boolean isSortedAscending(SortModel sortModel, String sortExpression) { if(sortModel == null || sortExpression == null) return false; Sort sort = sortModel.lookupSort(sortExpression); if(sort != null && sort.getDirection() == SortDirection.ASCENDING) return true; else return false; }
java
public static boolean isSortedAscending(SortModel sortModel, String sortExpression) { if(sortModel == null || sortExpression == null) return false; Sort sort = sortModel.lookupSort(sortExpression); if(sort != null && sort.getDirection() == SortDirection.ASCENDING) return true; else return false; }
[ "public", "static", "boolean", "isSortedAscending", "(", "SortModel", "sortModel", ",", "String", "sortExpression", ")", "{", "if", "(", "sortModel", "==", "null", "||", "sortExpression", "==", "null", ")", "return", "false", ";", "Sort", "sort", "=", "sortMod...
Given a sort expression, check to see if the sort expression is sorted ascending in a data grid's {@link SortModel}. @param sortModel a grid's sort model @param sortExpression the sort expression @return return <code>true</code> if a {@link Sort} is found whose sort expression matches the sort expression given here and whose direction is {@link SortDirection#ASCENDING}. @netui:jspfunction name="isSortedAscending" signature="boolean isSortedAscending(org.apache.beehive.netui.databinding.datagrid.api.sort.SortModel,java.lang.String)"
[ "Given", "a", "sort", "expression", "check", "to", "see", "if", "the", "sort", "expression", "is", "sorted", "ascending", "in", "a", "data", "grid", "s", "{" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/databinding/datagrid/runtime/util/JspFunctions.java#L55-L63
agmip/agmip-common-functions
src/main/java/org/agmip/functions/ExperimentHelper.java
ExperimentHelper.isValidDate
private static boolean isValidDate(String date, Calendar out, String separator) { try { String[] dates = date.split(separator); out.set(Calendar.DATE, Integer.parseInt(dates[dates.length - 1])); out.set(Calendar.MONTH, Integer.parseInt(dates[dates.length - 2])); if (dates.length > 2) { out.set(Calendar.YEAR, Integer.parseInt(dates[dates.length - 3])); } } catch (Exception e) { try { out.set(Calendar.DATE, Integer.parseInt(date.substring(date.length() - 2, date.length()))); out.set(Calendar.MONTH, Integer.parseInt(date.substring(date.length() - 4, date.length() - 2)) - 1); if (date.length() > 4) { out.set(Calendar.YEAR, Integer.parseInt(date.substring(date.length() - 8, date.length() - 4)) - 1); } } catch (Exception e2) { return false; } } return true; }
java
private static boolean isValidDate(String date, Calendar out, String separator) { try { String[] dates = date.split(separator); out.set(Calendar.DATE, Integer.parseInt(dates[dates.length - 1])); out.set(Calendar.MONTH, Integer.parseInt(dates[dates.length - 2])); if (dates.length > 2) { out.set(Calendar.YEAR, Integer.parseInt(dates[dates.length - 3])); } } catch (Exception e) { try { out.set(Calendar.DATE, Integer.parseInt(date.substring(date.length() - 2, date.length()))); out.set(Calendar.MONTH, Integer.parseInt(date.substring(date.length() - 4, date.length() - 2)) - 1); if (date.length() > 4) { out.set(Calendar.YEAR, Integer.parseInt(date.substring(date.length() - 8, date.length() - 4)) - 1); } } catch (Exception e2) { return false; } } return true; }
[ "private", "static", "boolean", "isValidDate", "(", "String", "date", ",", "Calendar", "out", ",", "String", "separator", ")", "{", "try", "{", "String", "[", "]", "dates", "=", "date", ".", "split", "(", "separator", ")", ";", "out", ".", "set", "(", ...
To check if the input date string is valid and match with the required format @param date The input date string, which should comes with the format of yyyy-mm-dd, the separator should be same with the third parameter @param out The Calendar instance which will be assigned with input year, month and day @param separator The separator string used in date format @return check result
[ "To", "check", "if", "the", "input", "date", "string", "is", "valid", "and", "match", "with", "the", "required", "format" ]
train
https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/functions/ExperimentHelper.java#L466-L487
Sciss/abc4j
abc/src/main/java/abc/ui/swing/JStaffLine.java
JStaffLine.setTablature
protected void setTablature(Tablature tablature) { if (tablature != null) m_tablature = new JTablature(tablature, getBase(), getMetrics()); else m_tablature = null; }
java
protected void setTablature(Tablature tablature) { if (tablature != null) m_tablature = new JTablature(tablature, getBase(), getMetrics()); else m_tablature = null; }
[ "protected", "void", "setTablature", "(", "Tablature", "tablature", ")", "{", "if", "(", "tablature", "!=", "null", ")", "m_tablature", "=", "new", "JTablature", "(", "tablature", ",", "getBase", "(", ")", ",", "getMetrics", "(", ")", ")", ";", "else", "...
attaches a tablature to this staff line @param tablature null to remove tablature
[ "attaches", "a", "tablature", "to", "this", "staff", "line" ]
train
https://github.com/Sciss/abc4j/blob/117b405642c84a7bfca4e3e13668838258b90ca7/abc/src/main/java/abc/ui/swing/JStaffLine.java#L106-L111
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.getAt
@SuppressWarnings("unchecked") public static List<Float> getAt(float[] array, ObjectRange range) { return primitiveArrayGet(array, range); }
java
@SuppressWarnings("unchecked") public static List<Float> getAt(float[] array, ObjectRange range) { return primitiveArrayGet(array, range); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "List", "<", "Float", ">", "getAt", "(", "float", "[", "]", "array", ",", "ObjectRange", "range", ")", "{", "return", "primitiveArrayGet", "(", "array", ",", "range", ")", ";", "}" ]
Support the subscript operator with an ObjectRange for a float array @param array a float array @param range an ObjectRange indicating the indices for the items to retrieve @return list of the retrieved floats @since 1.0
[ "Support", "the", "subscript", "operator", "with", "an", "ObjectRange", "for", "a", "float", "array" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L13899-L13902
jbundle/jbundle
base/screen/model/src/main/java/org/jbundle/base/screen/model/report/parser/XMLParser.java
XMLParser.getTagData
public String getTagData(String strData, String strTag) { int iStartData = strData.indexOf('<' + strTag + '>'); if (iStartData == -1) return null; iStartData = iStartData + strTag.length() + 2; int iEndData = strData.indexOf("</" + strTag + '>'); if (iStartData == -1) return null; return strData.substring(iStartData, iEndData); }
java
public String getTagData(String strData, String strTag) { int iStartData = strData.indexOf('<' + strTag + '>'); if (iStartData == -1) return null; iStartData = iStartData + strTag.length() + 2; int iEndData = strData.indexOf("</" + strTag + '>'); if (iStartData == -1) return null; return strData.substring(iStartData, iEndData); }
[ "public", "String", "getTagData", "(", "String", "strData", ",", "String", "strTag", ")", "{", "int", "iStartData", "=", "strData", ".", "indexOf", "(", "'", "'", "+", "strTag", "+", "'", "'", ")", ";", "if", "(", "iStartData", "==", "-", "1", ")", ...
Find the data between these XML tags. @param strData The XML code to find the tags in. @param strTag The tag to find.
[ "Find", "the", "data", "between", "these", "XML", "tags", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/report/parser/XMLParser.java#L81-L91
apache/groovy
src/main/java/org/codehaus/groovy/runtime/memoize/LRUCache.java
LRUCache.getAndPut
@Override public V getAndPut(K key, ValueProvider<? super K, ? extends V> valueProvider) { return map.computeIfAbsent(key, valueProvider::provide); }
java
@Override public V getAndPut(K key, ValueProvider<? super K, ? extends V> valueProvider) { return map.computeIfAbsent(key, valueProvider::provide); }
[ "@", "Override", "public", "V", "getAndPut", "(", "K", "key", ",", "ValueProvider", "<", "?", "super", "K", ",", "?", "extends", "V", ">", "valueProvider", ")", "{", "return", "map", ".", "computeIfAbsent", "(", "key", ",", "valueProvider", "::", "provid...
Try to get the value from cache. If not found, create the value by {@link MemoizeCache.ValueProvider} and put it into the cache, at last return the value. The operation is completed atomically. @param key @param valueProvider provide the value if the associated value not found
[ "Try", "to", "get", "the", "value", "from", "cache", ".", "If", "not", "found", "create", "the", "value", "by", "{", "@link", "MemoizeCache", ".", "ValueProvider", "}", "and", "put", "it", "into", "the", "cache", "at", "last", "return", "the", "value", ...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/memoize/LRUCache.java#L61-L64
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/DistanceTable.java
DistanceTable.scanTerritory
private Node scanTerritory(DistanceMap map, String desired, String supported) { Node node; for (String partition : PARTITION_TABLE.getRegionPartition(desired)) { node = map.get(partition, supported); if (node != null) { return node; } } for (String partition : PARTITION_TABLE.getRegionPartition(supported)) { node = map.get(desired, partition); if (node != null) { return node; } } return null; }
java
private Node scanTerritory(DistanceMap map, String desired, String supported) { Node node; for (String partition : PARTITION_TABLE.getRegionPartition(desired)) { node = map.get(partition, supported); if (node != null) { return node; } } for (String partition : PARTITION_TABLE.getRegionPartition(supported)) { node = map.get(desired, partition); if (node != null) { return node; } } return null; }
[ "private", "Node", "scanTerritory", "(", "DistanceMap", "map", ",", "String", "desired", ",", "String", "supported", ")", "{", "Node", "node", ";", "for", "(", "String", "partition", ":", "PARTITION_TABLE", ".", "getRegionPartition", "(", "desired", ")", ")", ...
Scan the desired region against the supported partitions and vice versa. Return the first matching node.
[ "Scan", "the", "desired", "region", "against", "the", "supported", "partitions", "and", "vice", "versa", ".", "Return", "the", "first", "matching", "node", "." ]
train
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/DistanceTable.java#L172-L189
OpenLiberty/open-liberty
dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/ProbeManagerImpl.java
ProbeManagerImpl.removeInterestedByClass
synchronized void removeInterestedByClass(Class<?> clazz, ProbeListener listener) { Set<ProbeListener> listeners = listenersByClass.get(clazz); if (listeners != null) { listeners.remove(listener); if (listeners.isEmpty()) { listenersByClass.remove(clazz); } } }
java
synchronized void removeInterestedByClass(Class<?> clazz, ProbeListener listener) { Set<ProbeListener> listeners = listenersByClass.get(clazz); if (listeners != null) { listeners.remove(listener); if (listeners.isEmpty()) { listenersByClass.remove(clazz); } } }
[ "synchronized", "void", "removeInterestedByClass", "(", "Class", "<", "?", ">", "clazz", ",", "ProbeListener", "listener", ")", "{", "Set", "<", "ProbeListener", ">", "listeners", "=", "listenersByClass", ".", "get", "(", "clazz", ")", ";", "if", "(", "liste...
Remove the specified listener from the collection of listeners with {@link ProbeFilter}s that match the specified class. @param clazz the candidate probe source @param listener the listener with a filter that matched {@code clazz}
[ "Remove", "the", "specified", "listener", "from", "the", "collection", "of", "listeners", "with", "{", "@link", "ProbeFilter", "}", "s", "that", "match", "the", "specified", "class", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/ProbeManagerImpl.java#L579-L587
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_line_serviceName_phone_phonebook_bookKey_PUT
public void billingAccount_line_serviceName_phone_phonebook_bookKey_PUT(String billingAccount, String serviceName, String bookKey, OvhPhonebook body) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/phone/phonebook/{bookKey}"; StringBuilder sb = path(qPath, billingAccount, serviceName, bookKey); exec(qPath, "PUT", sb.toString(), body); }
java
public void billingAccount_line_serviceName_phone_phonebook_bookKey_PUT(String billingAccount, String serviceName, String bookKey, OvhPhonebook body) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/phone/phonebook/{bookKey}"; StringBuilder sb = path(qPath, billingAccount, serviceName, bookKey); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "billingAccount_line_serviceName_phone_phonebook_bookKey_PUT", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "String", "bookKey", ",", "OvhPhonebook", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/...
Alter this object properties REST: PUT /telephony/{billingAccount}/line/{serviceName}/phone/phonebook/{bookKey} @param body [required] New object properties @param billingAccount [required] The name of your billingAccount @param serviceName [required] @param bookKey [required] Identifier of the phonebook
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L1259-L1263
RuedigerMoeller/kontraktor
modules/kontraktor-http/src/main/java/org/nustaq/kontraktor/remoting/http/undertow/UndertowHttpServerConnector.java
UndertowHttpServerConnector.handleRegularRequest
protected void handleRegularRequest(HttpServerExchange exchange, HttpObjectSocket httpObjectSocket, Object[] received, StreamSinkChannel sinkchannel) { ArrayList<IPromise> futures = new ArrayList<>(); httpObjectSocket.getSink().receiveObject(received, futures, exchange.getRequestHeaders().getFirst("JWT") ); Runnable reply = () -> { // piggy back outstanding lp messages, outstanding lp request is untouched Pair<byte[], Integer> nextQueuedMessage = httpObjectSocket.getNextQueuedMessage(); byte response[] = nextQueuedMessage.getFirst(); exchange.setResponseContentLength(response.length); if (response.length == 0) { exchange.endExchange(); } else { httpObjectSocket.storeLPMessage(nextQueuedMessage.cdr(), response); //FIXME: ASYNC !!! long tim = System.nanoTime(); ByteBuffer responseBuf = ByteBuffer.wrap(response); try { while (responseBuf.remaining()>0) { sinkchannel.write(responseBuf); } } catch (IOException e) { Log.Warn(this,e); } // System.out.println("syncwrite time micros:"+(System.nanoTime()-tim)/1000); exchange.endExchange(); } }; if ( futures == null || futures.size() == 0 ) { reply.run(); } else { Actors.all((List) futures).timeoutIn(REQUEST_RESULTING_FUTURE_TIMEOUT).then( () -> { reply.run(); }).onTimeout( () -> reply.run() ); sinkchannel.resumeWrites(); } }
java
protected void handleRegularRequest(HttpServerExchange exchange, HttpObjectSocket httpObjectSocket, Object[] received, StreamSinkChannel sinkchannel) { ArrayList<IPromise> futures = new ArrayList<>(); httpObjectSocket.getSink().receiveObject(received, futures, exchange.getRequestHeaders().getFirst("JWT") ); Runnable reply = () -> { // piggy back outstanding lp messages, outstanding lp request is untouched Pair<byte[], Integer> nextQueuedMessage = httpObjectSocket.getNextQueuedMessage(); byte response[] = nextQueuedMessage.getFirst(); exchange.setResponseContentLength(response.length); if (response.length == 0) { exchange.endExchange(); } else { httpObjectSocket.storeLPMessage(nextQueuedMessage.cdr(), response); //FIXME: ASYNC !!! long tim = System.nanoTime(); ByteBuffer responseBuf = ByteBuffer.wrap(response); try { while (responseBuf.remaining()>0) { sinkchannel.write(responseBuf); } } catch (IOException e) { Log.Warn(this,e); } // System.out.println("syncwrite time micros:"+(System.nanoTime()-tim)/1000); exchange.endExchange(); } }; if ( futures == null || futures.size() == 0 ) { reply.run(); } else { Actors.all((List) futures).timeoutIn(REQUEST_RESULTING_FUTURE_TIMEOUT).then( () -> { reply.run(); }).onTimeout( () -> reply.run() ); sinkchannel.resumeWrites(); } }
[ "protected", "void", "handleRegularRequest", "(", "HttpServerExchange", "exchange", ",", "HttpObjectSocket", "httpObjectSocket", ",", "Object", "[", "]", "received", ",", "StreamSinkChannel", "sinkchannel", ")", "{", "ArrayList", "<", "IPromise", ">", "futures", "=", ...
handle a remote method call (not a long poll) @param exchange @param httpObjectSocket @param received @param sinkchannel
[ "handle", "a", "remote", "method", "call", "(", "not", "a", "long", "poll", ")" ]
train
https://github.com/RuedigerMoeller/kontraktor/blob/d5f3817f9476f3786187b8ef00400b7a4f25a404/modules/kontraktor-http/src/main/java/org/nustaq/kontraktor/remoting/http/undertow/UndertowHttpServerConnector.java#L269-L305
intendia-oss/rxjava-gwt
src/main/modified/io/reactivex/super/io/reactivex/Flowable.java
Flowable.repeatUntil
@CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> repeatUntil(BooleanSupplier stop) { ObjectHelper.requireNonNull(stop, "stop is null"); return RxJavaPlugins.onAssembly(new FlowableRepeatUntil<T>(this, stop)); }
java
@CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> repeatUntil(BooleanSupplier stop) { ObjectHelper.requireNonNull(stop, "stop is null"); return RxJavaPlugins.onAssembly(new FlowableRepeatUntil<T>(this, stop)); }
[ "@", "CheckReturnValue", "@", "BackpressureSupport", "(", "BackpressureKind", ".", "FULL", ")", "@", "SchedulerSupport", "(", "SchedulerSupport", ".", "NONE", ")", "public", "final", "Flowable", "<", "T", ">", "repeatUntil", "(", "BooleanSupplier", "stop", ")", ...
Returns a Flowable that repeats the sequence of items emitted by the source Publisher until the provided stop function returns true. <p> <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeat.on.png" alt=""> <dl> <dt><b>Backpressure:</b></dt> <dd>The operator honors downstream backpressure and expects the source {@code Publisher} to honor backpressure as well. If this expectation is violated, the operator <em>may</em> throw an {@code IllegalStateException}.</dd> <dt><b>Scheduler:</b></dt> <dd>{@code repeatUntil} does not operate by default on a particular {@link Scheduler}.</dd> </dl> @param stop a boolean supplier that is called when the current Flowable completes and unless it returns false, the current Flowable is resubscribed @return the new Flowable instance @throws NullPointerException if {@code stop} is null @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a>
[ "Returns", "a", "Flowable", "that", "repeats", "the", "sequence", "of", "items", "emitted", "by", "the", "source", "Publisher", "until", "the", "provided", "stop", "function", "returns", "true", ".", "<p", ">", "<img", "width", "=", "640", "height", "=", "...
train
https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Flowable.java#L12359-L12365
authlete/authlete-java-common
src/main/java/com/authlete/common/util/TypedProperties.java
TypedProperties.setLong
public void setLong(Enum<?> key, long value) { if (key == null) { return; } setLong(key.name(), value); }
java
public void setLong(Enum<?> key, long value) { if (key == null) { return; } setLong(key.name(), value); }
[ "public", "void", "setLong", "(", "Enum", "<", "?", ">", "key", ",", "long", "value", ")", "{", "if", "(", "key", "==", "null", ")", "{", "return", ";", "}", "setLong", "(", "key", ".", "name", "(", ")", ",", "value", ")", ";", "}" ]
Equivalent to {@link #setLong(String, long) setLong}{@code (key.name(), value)}. If {@code key} is null, nothing is done.
[ "Equivalent", "to", "{" ]
train
https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/util/TypedProperties.java#L726-L734
googleapis/google-cloud-java
google-cloud-clients/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/v1/SubscriptionAdminClient.java
SubscriptionAdminClient.modifyPushConfig
public final void modifyPushConfig(String subscription, PushConfig pushConfig) { ModifyPushConfigRequest request = ModifyPushConfigRequest.newBuilder() .setSubscription(subscription) .setPushConfig(pushConfig) .build(); modifyPushConfig(request); }
java
public final void modifyPushConfig(String subscription, PushConfig pushConfig) { ModifyPushConfigRequest request = ModifyPushConfigRequest.newBuilder() .setSubscription(subscription) .setPushConfig(pushConfig) .build(); modifyPushConfig(request); }
[ "public", "final", "void", "modifyPushConfig", "(", "String", "subscription", ",", "PushConfig", "pushConfig", ")", "{", "ModifyPushConfigRequest", "request", "=", "ModifyPushConfigRequest", ".", "newBuilder", "(", ")", ".", "setSubscription", "(", "subscription", ")"...
Modifies the `PushConfig` for a specified subscription. <p>This may be used to change a push subscription to a pull one (signified by an empty `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push subscription. Messages will accumulate for delivery continuously through the call regardless of changes to the `PushConfig`. <p>Sample code: <pre><code> try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) { ProjectSubscriptionName subscription = ProjectSubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]"); PushConfig pushConfig = PushConfig.newBuilder().build(); subscriptionAdminClient.modifyPushConfig(subscription.toString(), pushConfig); } </code></pre> @param subscription The name of the subscription. Format is `projects/{project}/subscriptions/{sub}`. @param pushConfig The push configuration for future deliveries. <p>An empty `pushConfig` indicates that the Pub/Sub system should stop pushing messages from the given subscription and allow messages to be pulled and acknowledged - effectively pausing the subscription if `Pull` or `StreamingPull` is not called. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Modifies", "the", "PushConfig", "for", "a", "specified", "subscription", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/v1/SubscriptionAdminClient.java#L1291-L1299
apereo/cas
core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/scripting/ScriptingUtils.java
ScriptingUtils.executeGroovyScript
public static <T> T executeGroovyScript(final Resource groovyScript, final String methodName, final Class<T> clazz, final Object... args) { return executeGroovyScript(groovyScript, methodName, args, clazz, false); }
java
public static <T> T executeGroovyScript(final Resource groovyScript, final String methodName, final Class<T> clazz, final Object... args) { return executeGroovyScript(groovyScript, methodName, args, clazz, false); }
[ "public", "static", "<", "T", ">", "T", "executeGroovyScript", "(", "final", "Resource", "groovyScript", ",", "final", "String", "methodName", ",", "final", "Class", "<", "T", ">", "clazz", ",", "final", "Object", "...", "args", ")", "{", "return", "execut...
Execute groovy script t. @param <T> the type parameter @param groovyScript the groovy script @param methodName the method name @param clazz the clazz @param args the args @return the type to return
[ "Execute", "groovy", "script", "t", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/scripting/ScriptingUtils.java#L167-L172
FasterXML/woodstox
src/main/java/com/ctc/wstx/dtd/DTDSubsetImpl.java
DTDSubsetImpl.combineElements
private void combineElements(InputProblemReporter rep, HashMap<PrefixedName,DTDElement> intElems, HashMap<PrefixedName,DTDElement> extElems) throws XMLStreamException { for (Map.Entry<PrefixedName,DTDElement> me : extElems.entrySet()) { PrefixedName key = me.getKey(); DTDElement extElem = me.getValue(); DTDElement intElem = intElems.get(key); // If there was no old value, can just merge new one in and continue if (intElem == null) { intElems.put(key, extElem); continue; } // Which one is defined (if either)? if (extElem.isDefined()) { // one from the ext subset if (intElem.isDefined()) { // but both can't be; that's an error throwElementException(intElem, extElem.getLocation()); } else { /* Note: can/should not modify the external element (by * for example adding attributes); external element may * be cached and shared... so, need to do the reverse, * define the one from internal subset. */ intElem.defineFrom(rep, extElem, mFullyValidating); } } else { if (!intElem.isDefined()) { /* ??? Should we warn about neither of them being really * declared? */ rep.reportProblem(intElem.getLocation(), ErrorConsts.WT_ENT_DECL, ErrorConsts.W_UNDEFINED_ELEM, extElem.getDisplayName(), null); } else { intElem.mergeMissingAttributesFrom(rep, extElem, mFullyValidating); } } } }
java
private void combineElements(InputProblemReporter rep, HashMap<PrefixedName,DTDElement> intElems, HashMap<PrefixedName,DTDElement> extElems) throws XMLStreamException { for (Map.Entry<PrefixedName,DTDElement> me : extElems.entrySet()) { PrefixedName key = me.getKey(); DTDElement extElem = me.getValue(); DTDElement intElem = intElems.get(key); // If there was no old value, can just merge new one in and continue if (intElem == null) { intElems.put(key, extElem); continue; } // Which one is defined (if either)? if (extElem.isDefined()) { // one from the ext subset if (intElem.isDefined()) { // but both can't be; that's an error throwElementException(intElem, extElem.getLocation()); } else { /* Note: can/should not modify the external element (by * for example adding attributes); external element may * be cached and shared... so, need to do the reverse, * define the one from internal subset. */ intElem.defineFrom(rep, extElem, mFullyValidating); } } else { if (!intElem.isDefined()) { /* ??? Should we warn about neither of them being really * declared? */ rep.reportProblem(intElem.getLocation(), ErrorConsts.WT_ENT_DECL, ErrorConsts.W_UNDEFINED_ELEM, extElem.getDisplayName(), null); } else { intElem.mergeMissingAttributesFrom(rep, extElem, mFullyValidating); } } } }
[ "private", "void", "combineElements", "(", "InputProblemReporter", "rep", ",", "HashMap", "<", "PrefixedName", ",", "DTDElement", ">", "intElems", ",", "HashMap", "<", "PrefixedName", ",", "DTDElement", ">", "extElems", ")", "throws", "XMLStreamException", "{", "f...
Method that will try to merge in elements defined in the external subset, into internal subset; it will also check for redeclarations when doing this, as it's invalid to redeclare elements. Care has to be taken to only check actual redeclarations: placeholders should not cause problems.
[ "Method", "that", "will", "try", "to", "merge", "in", "elements", "defined", "in", "the", "external", "subset", "into", "internal", "subset", ";", "it", "will", "also", "check", "for", "redeclarations", "when", "doing", "this", "as", "it", "s", "invalid", ...
train
https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/dtd/DTDSubsetImpl.java#L473-L514
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java
StringGroovyMethods.replaceFirst
public static String replaceFirst(final CharSequence self, final CharSequence regex, final CharSequence replacement) { return self.toString().replaceFirst(regex.toString(), replacement.toString()); }
java
public static String replaceFirst(final CharSequence self, final CharSequence regex, final CharSequence replacement) { return self.toString().replaceFirst(regex.toString(), replacement.toString()); }
[ "public", "static", "String", "replaceFirst", "(", "final", "CharSequence", "self", ",", "final", "CharSequence", "regex", ",", "final", "CharSequence", "replacement", ")", "{", "return", "self", ".", "toString", "(", ")", ".", "replaceFirst", "(", "regex", "....
Replaces the first substring of this CharSequence that matches the given regular expression with the given replacement. @param self a CharSequence @param regex the capturing regex @param replacement the CharSequence to be substituted for each match @return a CharSequence with replaced content @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid @see String#replaceFirst(String, String) @since 1.8.2
[ "Replaces", "the", "first", "substring", "of", "this", "CharSequence", "that", "matches", "the", "given", "regular", "expression", "with", "the", "given", "replacement", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java#L2629-L2631
cdk/cdk
legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java
GeometryTools.shiftContainer
public static Rectangle2D shiftContainer(IAtomContainer container, Rectangle2D bounds, Rectangle2D last, double gap) { // determine if the containers are overlapping if (last.getMaxX() + gap >= bounds.getMinX()) { double xShift = last.getMaxX() + gap - bounds.getMinX(); Vector2d shift = new Vector2d(xShift, 0.0); GeometryTools.translate2D(container, shift); return new Rectangle2D.Double(bounds.getX() + xShift, bounds.getY(), bounds.getWidth(), bounds.getHeight()); } else { // the containers are not overlapping return bounds; } }
java
public static Rectangle2D shiftContainer(IAtomContainer container, Rectangle2D bounds, Rectangle2D last, double gap) { // determine if the containers are overlapping if (last.getMaxX() + gap >= bounds.getMinX()) { double xShift = last.getMaxX() + gap - bounds.getMinX(); Vector2d shift = new Vector2d(xShift, 0.0); GeometryTools.translate2D(container, shift); return new Rectangle2D.Double(bounds.getX() + xShift, bounds.getY(), bounds.getWidth(), bounds.getHeight()); } else { // the containers are not overlapping return bounds; } }
[ "public", "static", "Rectangle2D", "shiftContainer", "(", "IAtomContainer", "container", ",", "Rectangle2D", "bounds", ",", "Rectangle2D", "last", ",", "double", "gap", ")", "{", "// determine if the containers are overlapping", "if", "(", "last", ".", "getMaxX", "(",...
Shift the container horizontally to the right to make its bounds not overlap with the other bounds. @param container the {@link IAtomContainer} to shift to the right @param bounds the {@link Rectangle2D} of the {@link IAtomContainer} to shift @param last the bounds that is used as reference @param gap the gap between the two {@link Rectangle2D}s @return the {@link Rectangle2D} of the {@link IAtomContainer} after the shift
[ "Shift", "the", "container", "horizontally", "to", "the", "right", "to", "make", "its", "bounds", "not", "overlap", "with", "the", "other", "bounds", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java#L1649-L1660
elki-project/elki
elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/heap/UpdatableHeap.java
UpdatableHeap.heapifyUp
@Override protected void heapifyUp(int pos, Object cur) { while(pos > 0) { final int parent = (pos - 1) >>> 1; Object par = queue[parent]; if(comparator.compare(cur, par) >= 0) { break; } queue[pos] = par; index.put(par, pos); pos = parent; } queue[pos] = cur; index.put(cur, pos); }
java
@Override protected void heapifyUp(int pos, Object cur) { while(pos > 0) { final int parent = (pos - 1) >>> 1; Object par = queue[parent]; if(comparator.compare(cur, par) >= 0) { break; } queue[pos] = par; index.put(par, pos); pos = parent; } queue[pos] = cur; index.put(cur, pos); }
[ "@", "Override", "protected", "void", "heapifyUp", "(", "int", "pos", ",", "Object", "cur", ")", "{", "while", "(", "pos", ">", "0", ")", "{", "final", "int", "parent", "=", "(", "pos", "-", "1", ")", ">>>", "1", ";", "Object", "par", "=", "queue...
Execute a "Heapify Upwards" aka "SiftUp". Used in insertions. @param pos insertion position @param cur Element to insert
[ "Execute", "a", "Heapify", "Upwards", "aka", "SiftUp", ".", "Used", "in", "insertions", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/heap/UpdatableHeap.java#L189-L204
jcuda/jcudnn
JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java
JCudnn.cudnnGetConvolutionBackwardFilterWorkspaceSize
public static int cudnnGetConvolutionBackwardFilterWorkspaceSize( cudnnHandle handle, cudnnTensorDescriptor xDesc, cudnnTensorDescriptor dyDesc, cudnnConvolutionDescriptor convDesc, cudnnFilterDescriptor gradDesc, int algo, long[] sizeInBytes) { return checkResult(cudnnGetConvolutionBackwardFilterWorkspaceSizeNative(handle, xDesc, dyDesc, convDesc, gradDesc, algo, sizeInBytes)); }
java
public static int cudnnGetConvolutionBackwardFilterWorkspaceSize( cudnnHandle handle, cudnnTensorDescriptor xDesc, cudnnTensorDescriptor dyDesc, cudnnConvolutionDescriptor convDesc, cudnnFilterDescriptor gradDesc, int algo, long[] sizeInBytes) { return checkResult(cudnnGetConvolutionBackwardFilterWorkspaceSizeNative(handle, xDesc, dyDesc, convDesc, gradDesc, algo, sizeInBytes)); }
[ "public", "static", "int", "cudnnGetConvolutionBackwardFilterWorkspaceSize", "(", "cudnnHandle", "handle", ",", "cudnnTensorDescriptor", "xDesc", ",", "cudnnTensorDescriptor", "dyDesc", ",", "cudnnConvolutionDescriptor", "convDesc", ",", "cudnnFilterDescriptor", "gradDesc", ","...
Helper function to return the minimum size of the workspace to be passed to the convolution given an algo
[ "Helper", "function", "to", "return", "the", "minimum", "size", "of", "the", "workspace", "to", "be", "passed", "to", "the", "convolution", "given", "an", "algo" ]
train
https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L1372-L1382
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PatternsImpl.java
PatternsImpl.deletePattern
public OperationStatus deletePattern(UUID appId, String versionId, UUID patternId) { return deletePatternWithServiceResponseAsync(appId, versionId, patternId).toBlocking().single().body(); }
java
public OperationStatus deletePattern(UUID appId, String versionId, UUID patternId) { return deletePatternWithServiceResponseAsync(appId, versionId, patternId).toBlocking().single().body(); }
[ "public", "OperationStatus", "deletePattern", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "patternId", ")", "{", "return", "deletePatternWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "patternId", ")", ".", "toBlocking", "(", ")...
Deletes the pattern with the specified ID. @param appId The application ID. @param versionId The version ID. @param patternId The pattern ID. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the OperationStatus object if successful.
[ "Deletes", "the", "pattern", "with", "the", "specified", "ID", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PatternsImpl.java#L759-L761
groovy/groovy-core
subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java
Sql.withInstance
public static void withInstance(Map<String, Object> args, Closure c) throws SQLException, ClassNotFoundException { Sql sql = null; try { sql = newInstance(args); c.call(sql); } finally { if (sql != null) sql.close(); } }
java
public static void withInstance(Map<String, Object> args, Closure c) throws SQLException, ClassNotFoundException { Sql sql = null; try { sql = newInstance(args); c.call(sql); } finally { if (sql != null) sql.close(); } }
[ "public", "static", "void", "withInstance", "(", "Map", "<", "String", ",", "Object", ">", "args", ",", "Closure", "c", ")", "throws", "SQLException", ",", "ClassNotFoundException", "{", "Sql", "sql", "=", "null", ";", "try", "{", "sql", "=", "newInstance"...
Invokes a closure passing it a new Sql instance created from the given map of arguments. The created connection will be closed if required. @param args a Map contain further arguments @param c the Closure to call @see #newInstance(java.util.Map) @throws SQLException if a database access error occurs @throws ClassNotFoundException if the driver class cannot be found or loaded
[ "Invokes", "a", "closure", "passing", "it", "a", "new", "Sql", "instance", "created", "from", "the", "given", "map", "of", "arguments", ".", "The", "created", "connection", "will", "be", "closed", "if", "required", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L608-L616
intuit/QuickBooks-V3-Java-SDK
ipp-v3-java-devkit/src/main/java/com/intuit/ipp/serialization/IntuitResponseDeserializer.java
IntuitResponseDeserializer.getQueryResponse
private QueryResponse getQueryResponse(JsonNode jsonNode) throws IOException { ObjectMapper mapper = new ObjectMapper(); SimpleModule simpleModule = new SimpleModule("QueryResponseDeserializer", new Version(1, 0, 0, null)); simpleModule.addDeserializer(QueryResponse.class, new QueryResponseDeserializer()); mapper.registerModule(simpleModule); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper.treeToValue(jsonNode, QueryResponse.class); }
java
private QueryResponse getQueryResponse(JsonNode jsonNode) throws IOException { ObjectMapper mapper = new ObjectMapper(); SimpleModule simpleModule = new SimpleModule("QueryResponseDeserializer", new Version(1, 0, 0, null)); simpleModule.addDeserializer(QueryResponse.class, new QueryResponseDeserializer()); mapper.registerModule(simpleModule); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper.treeToValue(jsonNode, QueryResponse.class); }
[ "private", "QueryResponse", "getQueryResponse", "(", "JsonNode", "jsonNode", ")", "throws", "IOException", "{", "ObjectMapper", "mapper", "=", "new", "ObjectMapper", "(", ")", ";", "SimpleModule", "simpleModule", "=", "new", "SimpleModule", "(", "\"QueryResponseDeseri...
Method to deserialize the QueryResponse object @param jsonNode @return QueryResponse
[ "Method", "to", "deserialize", "the", "QueryResponse", "object" ]
train
https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/serialization/IntuitResponseDeserializer.java#L318-L328
domaframework/doma-gen
src/main/java/org/seasar/doma/extension/gen/GlobalFactory.java
GlobalFactory.createDataSource
public DataSource createDataSource(Driver driver, String user, String password, String url) { SimpleDataSource dataSource = new SimpleDataSource(); dataSource.setDriver(driver); dataSource.setUser(user); dataSource.setPassword(password); dataSource.setUrl(url); return dataSource; }
java
public DataSource createDataSource(Driver driver, String user, String password, String url) { SimpleDataSource dataSource = new SimpleDataSource(); dataSource.setDriver(driver); dataSource.setUser(user); dataSource.setPassword(password); dataSource.setUrl(url); return dataSource; }
[ "public", "DataSource", "createDataSource", "(", "Driver", "driver", ",", "String", "user", ",", "String", "password", ",", "String", "url", ")", "{", "SimpleDataSource", "dataSource", "=", "new", "SimpleDataSource", "(", ")", ";", "dataSource", ".", "setDriver"...
データソースを作成します。 @param driver JDBCドライバー @param user ユーザー @param password パスワード @param url 接続URL @return データソース
[ "データソースを作成します。" ]
train
https://github.com/domaframework/doma-gen/blob/8046e0b28d2167d444125f206ce36e554b3ee616/src/main/java/org/seasar/doma/extension/gen/GlobalFactory.java#L25-L32
cesarferreira/AndroidQuickUtils
library/src/main/java/quickutils/core/categories/share.java
share.genericSharing
public static void genericSharing(String subject, String message) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, message); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); QuickUtils.getContext().startActivity(intent); }
java
public static void genericSharing(String subject, String message) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, message); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); QuickUtils.getContext().startActivity(intent); }
[ "public", "static", "void", "genericSharing", "(", "String", "subject", ",", "String", "message", ")", "{", "Intent", "intent", "=", "new", "Intent", "(", "Intent", ".", "ACTION_SEND", ")", ";", "intent", ".", "setType", "(", "\"text/plain\"", ")", ";", "i...
Generic method for sharing that Deliver some data to someone else. Who the data is being delivered to is not specified; it is up to the receiver of this action to ask the user where the data should be sent. @param subject The title, if applied @param message Message to be delivered
[ "Generic", "method", "for", "sharing", "that", "Deliver", "some", "data", "to", "someone", "else", ".", "Who", "the", "data", "is", "being", "delivered", "to", "is", "not", "specified", ";", "it", "is", "up", "to", "the", "receiver", "of", "this", "actio...
train
https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/categories/share.java#L80-L87
Azure/azure-sdk-for-java
recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/BackupResourceStorageConfigsInner.java
BackupResourceStorageConfigsInner.updateAsync
public Observable<Void> updateAsync(String vaultName, String resourceGroupName, BackupResourceConfigResourceInner parameters) { return updateWithServiceResponseAsync(vaultName, resourceGroupName, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> updateAsync(String vaultName, String resourceGroupName, BackupResourceConfigResourceInner parameters) { return updateWithServiceResponseAsync(vaultName, resourceGroupName, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "updateAsync", "(", "String", "vaultName", ",", "String", "resourceGroupName", ",", "BackupResourceConfigResourceInner", "parameters", ")", "{", "return", "updateWithServiceResponseAsync", "(", "vaultName", ",", "resourceGroupName...
Updates vault storage model type. @param vaultName The name of the recovery services vault. @param resourceGroupName The name of the resource group where the recovery services vault is present. @param parameters Vault storage config request @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Updates", "vault", "storage", "model", "type", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/BackupResourceStorageConfigsInner.java#L188-L195
tropo/tropo-webapi-java
src/main/java/com/voxeo/tropo/Key.java
Key.SAY_OF_MESSAGE
public static Key SAY_OF_MESSAGE(com.voxeo.tropo.actions.MessageAction.Say... says) { return createKey("say", says); }
java
public static Key SAY_OF_MESSAGE(com.voxeo.tropo.actions.MessageAction.Say... says) { return createKey("say", says); }
[ "public", "static", "Key", "SAY_OF_MESSAGE", "(", "com", ".", "voxeo", ".", "tropo", ".", "actions", ".", "MessageAction", ".", "Say", "...", "says", ")", "{", "return", "createKey", "(", "\"say\"", ",", "says", ")", ";", "}" ]
<p> This determines what is played or sent to the caller. This can be a single object or an array of objects. </p>
[ "<p", ">", "This", "determines", "what", "is", "played", "or", "sent", "to", "the", "caller", ".", "This", "can", "be", "a", "single", "object", "or", "an", "array", "of", "objects", ".", "<", "/", "p", ">" ]
train
https://github.com/tropo/tropo-webapi-java/blob/96af1fa292c1d4b6321d85a559d9718d33eec7e0/src/main/java/com/voxeo/tropo/Key.java#L767-L770
elki-project/elki
elki-index-rtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/spatial/rstarvariants/AbstractRStarTree.java
AbstractRStarTree.overflowTreatment
private N overflowTreatment(N node, IndexTreePath<E> path) { if(settings.getOverflowTreatment().handleOverflow(this, node, path)) { return null; } return split(node); }
java
private N overflowTreatment(N node, IndexTreePath<E> path) { if(settings.getOverflowTreatment().handleOverflow(this, node, path)) { return null; } return split(node); }
[ "private", "N", "overflowTreatment", "(", "N", "node", ",", "IndexTreePath", "<", "E", ">", "path", ")", "{", "if", "(", "settings", ".", "getOverflowTreatment", "(", ")", ".", "handleOverflow", "(", "this", ",", "node", ",", "path", ")", ")", "{", "re...
Treatment of overflow in the specified node: if the node is not the root node and this is the first call of overflowTreatment in the given level during insertion the specified node will be reinserted, otherwise the node will be split. @param node the node where an overflow occurred @param path the path to the specified node @return the newly created split node in case of split, null in case of reinsertion
[ "Treatment", "of", "overflow", "in", "the", "specified", "node", ":", "if", "the", "node", "is", "not", "the", "root", "node", "and", "this", "is", "the", "first", "call", "of", "overflowTreatment", "in", "the", "given", "level", "during", "insertion", "th...
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-rtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/spatial/rstarvariants/AbstractRStarTree.java#L557-L562
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/View.java
View.setMapReduce
@InterfaceAudience.Public public boolean setMapReduce(Mapper mapBlock, Reducer reduceBlock, String version) { assert (mapBlock != null); assert (version != null); boolean changed = (this.version == null || !this.version.equals(version)); this.mapBlock = mapBlock; this.reduceBlock = reduceBlock; this.version = version; viewStore.setVersion(version); // for SQLite return changed; }
java
@InterfaceAudience.Public public boolean setMapReduce(Mapper mapBlock, Reducer reduceBlock, String version) { assert (mapBlock != null); assert (version != null); boolean changed = (this.version == null || !this.version.equals(version)); this.mapBlock = mapBlock; this.reduceBlock = reduceBlock; this.version = version; viewStore.setVersion(version); // for SQLite return changed; }
[ "@", "InterfaceAudience", ".", "Public", "public", "boolean", "setMapReduce", "(", "Mapper", "mapBlock", ",", "Reducer", "reduceBlock", ",", "String", "version", ")", "{", "assert", "(", "mapBlock", "!=", "null", ")", ";", "assert", "(", "version", "!=", "nu...
Defines a view's functions. <p/> The view's definition is given as a class that conforms to the Mapper or Reducer interface (or null to delete the view). The body of the block should call the 'emit' object (passed in as a paramter) for every key/value pair it wants to write to the view. <p/> Since the function itself is obviously not stored in the database (only a unique string idenfitying it), you must re-define the view on every launch of the app! If the database needs to rebuild the view but the function hasn't been defined yet, it will fail and the view will be empty, causing weird problems later on. <p/> It is very important that this block be a law-abiding map function! As in other languages, it must be a "pure" function, with no side effects, that always emits the same values given the same input document. That means that it should not access or change any external state; be careful, since callbacks make that so easy that you might do it inadvertently! The callback may be called on any thread, or on multiple threads simultaneously. This won't be a problem if the code is "pure" as described above, since it will as a consequence also be thread-safe.
[ "Defines", "a", "view", "s", "functions", ".", "<p", "/", ">", "The", "view", "s", "definition", "is", "given", "as", "a", "class", "that", "conforms", "to", "the", "Mapper", "or", "Reducer", "interface", "(", "or", "null", "to", "delete", "the", "view...
train
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/View.java#L150-L160
intendia-oss/rxjava-gwt
src/main/modified/io/reactivex/super/io/reactivex/Single.java
Single.onErrorResumeNext
@CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> onErrorResumeNext( final Function<? super Throwable, ? extends SingleSource<? extends T>> resumeFunctionInCaseOfError) { ObjectHelper.requireNonNull(resumeFunctionInCaseOfError, "resumeFunctionInCaseOfError is null"); return RxJavaPlugins.onAssembly(new SingleResumeNext<T>(this, resumeFunctionInCaseOfError)); }
java
@CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Single<T> onErrorResumeNext( final Function<? super Throwable, ? extends SingleSource<? extends T>> resumeFunctionInCaseOfError) { ObjectHelper.requireNonNull(resumeFunctionInCaseOfError, "resumeFunctionInCaseOfError is null"); return RxJavaPlugins.onAssembly(new SingleResumeNext<T>(this, resumeFunctionInCaseOfError)); }
[ "@", "CheckReturnValue", "@", "SchedulerSupport", "(", "SchedulerSupport", ".", "NONE", ")", "public", "final", "Single", "<", "T", ">", "onErrorResumeNext", "(", "final", "Function", "<", "?", "super", "Throwable", ",", "?", "extends", "SingleSource", "<", "?...
Instructs a Single to pass control to another Single rather than invoking {@link SingleObserver#onError(Throwable)} if it encounters an error. <p> <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.onErrorResumeNext.f.png" alt=""> <p> By default, when a Single encounters an error that prevents it from emitting the expected item to its {@link SingleObserver}, the Single invokes its SingleObserver's {@code onError} method, and then quits without invoking any more of its SingleObserver's methods. The {@code onErrorResumeNext} method changes this behavior. If you pass a function that will return another Single ({@code resumeFunctionInCaseOfError}) to a Single's {@code onErrorResumeNext} method, if the original Single encounters an error, instead of invoking its SingleObserver's {@code onError} method, it will instead relinquish control to {@code resumeSingleInCaseOfError} which will invoke the SingleObserver's {@link SingleObserver#onSuccess onSuccess} method if it is able to do so. In such a case, because no Single necessarily invokes {@code onError}, the SingleObserver may never know that an error happened. <p> You can use this to prevent errors from propagating or to supply fallback data should errors be encountered. <dl> <dt><b>Scheduler:</b></dt> <dd>{@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}.</dd> </dl> @param resumeFunctionInCaseOfError a function that returns a Single that will take control if source Single encounters an error. @return the original Single, with appropriately modified behavior. @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> @since .20
[ "Instructs", "a", "Single", "to", "pass", "control", "to", "another", "Single", "rather", "than", "invoking", "{", "@link", "SingleObserver#onError", "(", "Throwable", ")", "}", "if", "it", "encounters", "an", "error", ".", "<p", ">", "<img", "width", "=", ...
train
https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Single.java#L3078-L3084
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java
MemberSummaryBuilder.buildFieldsSummary
public void buildFieldsSummary(XMLNode node, Content memberSummaryTree) { MemberSummaryWriter writer = memberSummaryWriters.get(VisibleMemberMap.Kind.FIELDS); VisibleMemberMap visibleMemberMap = getVisibleMemberMap(VisibleMemberMap.Kind.FIELDS); addSummary(writer, visibleMemberMap, true, memberSummaryTree); }
java
public void buildFieldsSummary(XMLNode node, Content memberSummaryTree) { MemberSummaryWriter writer = memberSummaryWriters.get(VisibleMemberMap.Kind.FIELDS); VisibleMemberMap visibleMemberMap = getVisibleMemberMap(VisibleMemberMap.Kind.FIELDS); addSummary(writer, visibleMemberMap, true, memberSummaryTree); }
[ "public", "void", "buildFieldsSummary", "(", "XMLNode", "node", ",", "Content", "memberSummaryTree", ")", "{", "MemberSummaryWriter", "writer", "=", "memberSummaryWriters", ".", "get", "(", "VisibleMemberMap", ".", "Kind", ".", "FIELDS", ")", ";", "VisibleMemberMap"...
Build the summary for the fields. @param node the XML element that specifies which components to document @param memberSummaryTree the content tree to which the documentation will be added
[ "Build", "the", "summary", "for", "the", "fields", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java#L265-L271
carewebframework/carewebframework-core
org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/event/EventSubscriptions.java
EventSubscriptions.hasSubscribers
public boolean hasSubscribers(String eventName, boolean exact) { while (!StringUtils.isEmpty(eventName)) { if (hasSubscribers(eventName)) { return true; } else if (exact) { return false; } else { eventName = stripLevel(eventName); } } return false; }
java
public boolean hasSubscribers(String eventName, boolean exact) { while (!StringUtils.isEmpty(eventName)) { if (hasSubscribers(eventName)) { return true; } else if (exact) { return false; } else { eventName = stripLevel(eventName); } } return false; }
[ "public", "boolean", "hasSubscribers", "(", "String", "eventName", ",", "boolean", "exact", ")", "{", "while", "(", "!", "StringUtils", ".", "isEmpty", "(", "eventName", ")", ")", "{", "if", "(", "hasSubscribers", "(", "eventName", ")", ")", "{", "return",...
Returns true If the event has subscribers. @param eventName Name of the event. @param exact If false, will iterate through parent events until a subscriber is found. If true, only the exact event is considered. @return True if a subscriber was found.
[ "Returns", "true", "If", "the", "event", "has", "subscribers", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/event/EventSubscriptions.java#L103-L115
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/transform/XmlResponsesSaxParser.java
XmlResponsesSaxParser.parseXmlInputStream
protected void parseXmlInputStream(DefaultHandler handler, InputStream inputStream) throws IOException { try { if (log.isDebugEnabled()) { log.debug("Parsing XML response document with handler: " + handler.getClass()); } BufferedReader breader = new BufferedReader(new InputStreamReader(inputStream, Constants.DEFAULT_ENCODING)); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(breader)); } catch (IOException e) { throw e; } catch (Throwable t) { try { inputStream.close(); } catch (IOException e) { if (log.isErrorEnabled()) { log.error("Unable to close response InputStream up after XML parse failure", e); } } throw new SdkClientException("Failed to parse XML document with handler " + handler.getClass(), t); } }
java
protected void parseXmlInputStream(DefaultHandler handler, InputStream inputStream) throws IOException { try { if (log.isDebugEnabled()) { log.debug("Parsing XML response document with handler: " + handler.getClass()); } BufferedReader breader = new BufferedReader(new InputStreamReader(inputStream, Constants.DEFAULT_ENCODING)); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(breader)); } catch (IOException e) { throw e; } catch (Throwable t) { try { inputStream.close(); } catch (IOException e) { if (log.isErrorEnabled()) { log.error("Unable to close response InputStream up after XML parse failure", e); } } throw new SdkClientException("Failed to parse XML document with handler " + handler.getClass(), t); } }
[ "protected", "void", "parseXmlInputStream", "(", "DefaultHandler", "handler", ",", "InputStream", "inputStream", ")", "throws", "IOException", "{", "try", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Parsing XM...
Parses an XML document from an input stream using a document handler. @param handler the handler for the XML document @param inputStream an input stream containing the XML document to parse @throws IOException on error reading from the input stream (ie connection reset) @throws SdkClientException on error with malformed XML, etc
[ "Parses", "an", "XML", "document", "from", "an", "input", "stream", "using", "a", "document", "handler", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/transform/XmlResponsesSaxParser.java#L140-L168
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/version/internal/DefaultVersion.java
DefaultVersion.comparePadding
private static int comparePadding(List<Element> elements, int index, Boolean number) { int rel = 0; for (Iterator<Element> it = elements.listIterator(index); it.hasNext();) { Element element = it.next(); if (number != null && number.booleanValue() != element.isNumber()) { break; } rel = element.compareTo(null); if (rel != 0) { break; } } return rel; }
java
private static int comparePadding(List<Element> elements, int index, Boolean number) { int rel = 0; for (Iterator<Element> it = elements.listIterator(index); it.hasNext();) { Element element = it.next(); if (number != null && number.booleanValue() != element.isNumber()) { break; } rel = element.compareTo(null); if (rel != 0) { break; } } return rel; }
[ "private", "static", "int", "comparePadding", "(", "List", "<", "Element", ">", "elements", ",", "int", "index", ",", "Boolean", "number", ")", "{", "int", "rel", "=", "0", ";", "for", "(", "Iterator", "<", "Element", ">", "it", "=", "elements", ".", ...
Compare the end of the version with 0. @param elements the elements to compare to 0 @param index the index where to start comparing with 0 @param number indicate of the previous element is a number @return the comparison result
[ "Compare", "the", "end", "of", "the", "version", "with", "0", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/version/internal/DefaultVersion.java#L616-L633
advantageous/boon
reflekt/src/main/java/io/advantageous/boon/core/Str.java
Str.sputl
public static CharBuf sputl(CharBuf buf, Object... messages) { for (Object message : messages) { if (message == null) { buf.add("<NULL>"); } else if (message.getClass().isArray()) { buf.add(toListOrSingletonList(message).toString()); } else { buf.add(message.toString()); } buf.add('\n'); } buf.add('\n'); return buf; }
java
public static CharBuf sputl(CharBuf buf, Object... messages) { for (Object message : messages) { if (message == null) { buf.add("<NULL>"); } else if (message.getClass().isArray()) { buf.add(toListOrSingletonList(message).toString()); } else { buf.add(message.toString()); } buf.add('\n'); } buf.add('\n'); return buf; }
[ "public", "static", "CharBuf", "sputl", "(", "CharBuf", "buf", ",", "Object", "...", "messages", ")", "{", "for", "(", "Object", "message", ":", "messages", ")", "{", "if", "(", "message", "==", "null", ")", "{", "buf", ".", "add", "(", "\"<NULL>\"", ...
Writes to a char buf. A char buf is like a StringBuilder. @param buf char buf @param messages messages @return charbuf
[ "Writes", "to", "a", "char", "buf", ".", "A", "char", "buf", "is", "like", "a", "StringBuilder", "." ]
train
https://github.com/advantageous/boon/blob/12712d376761aa3b33223a9f1716720ddb67cb5e/reflekt/src/main/java/io/advantageous/boon/core/Str.java#L940-L957
intive-FDV/DynamicJasper
src/main/java/ar/com/fdvs/dj/domain/chart/builder/DJBarChartBuilder.java
DJBarChartBuilder.addSerie
public DJBarChartBuilder addSerie(AbstractColumn column, StringExpression labelExpression) { getDataset().addSerie(column, labelExpression); return this; }
java
public DJBarChartBuilder addSerie(AbstractColumn column, StringExpression labelExpression) { getDataset().addSerie(column, labelExpression); return this; }
[ "public", "DJBarChartBuilder", "addSerie", "(", "AbstractColumn", "column", ",", "StringExpression", "labelExpression", ")", "{", "getDataset", "(", ")", ".", "addSerie", "(", "column", ",", "labelExpression", ")", ";", "return", "this", ";", "}" ]
Adds the specified serie column to the dataset with custom label. @param column the serie column
[ "Adds", "the", "specified", "serie", "column", "to", "the", "dataset", "with", "custom", "label", "." ]
train
https://github.com/intive-FDV/DynamicJasper/blob/63919574cc401ae40574d13129f628e66d1682a3/src/main/java/ar/com/fdvs/dj/domain/chart/builder/DJBarChartBuilder.java#L376-L379
Azure/azure-sdk-for-java
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/InstanceFailoverGroupsInner.java
InstanceFailoverGroupsInner.beginCreateOrUpdateAsync
public Observable<InstanceFailoverGroupInner> beginCreateOrUpdateAsync(String resourceGroupName, String locationName, String failoverGroupName, InstanceFailoverGroupInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, locationName, failoverGroupName, parameters).map(new Func1<ServiceResponse<InstanceFailoverGroupInner>, InstanceFailoverGroupInner>() { @Override public InstanceFailoverGroupInner call(ServiceResponse<InstanceFailoverGroupInner> response) { return response.body(); } }); }
java
public Observable<InstanceFailoverGroupInner> beginCreateOrUpdateAsync(String resourceGroupName, String locationName, String failoverGroupName, InstanceFailoverGroupInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, locationName, failoverGroupName, parameters).map(new Func1<ServiceResponse<InstanceFailoverGroupInner>, InstanceFailoverGroupInner>() { @Override public InstanceFailoverGroupInner call(ServiceResponse<InstanceFailoverGroupInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "InstanceFailoverGroupInner", ">", "beginCreateOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "locationName", ",", "String", "failoverGroupName", ",", "InstanceFailoverGroupInner", "parameters", ")", "{", "return", "beginCrea...
Creates or updates a failover group. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param locationName The name of the region where the resource is located. @param failoverGroupName The name of the failover group. @param parameters The failover group parameters. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the InstanceFailoverGroupInner object
[ "Creates", "or", "updates", "a", "failover", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/InstanceFailoverGroupsInner.java#L329-L336
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/DateUtilities.java
DateUtilities.createDate
public static Date createDate(final int day, final int month, final int year) { Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.MONTH, month - 1); cal.set(Calendar.YEAR, year); return cal.getTime(); }
java
public static Date createDate(final int day, final int month, final int year) { Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.MONTH, month - 1); cal.set(Calendar.YEAR, year); return cal.getTime(); }
[ "public", "static", "Date", "createDate", "(", "final", "int", "day", ",", "final", "int", "month", ",", "final", "int", "year", ")", "{", "Calendar", "cal", "=", "Calendar", ".", "getInstance", "(", ")", ";", "cal", ".", "clear", "(", ")", ";", "cal...
Creates a date from the given components. @param day the day of the month, 1-31. @param month the month, 1-12. @param year the year. @return a date with the specified settings.
[ "Creates", "a", "date", "from", "the", "given", "components", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/DateUtilities.java#L29-L38
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RuleBasedCollator.java
RuleBasedCollator.getCollationElementIterator
public CollationElementIterator getCollationElementIterator(CharacterIterator source) { initMaxExpansions(); CharacterIterator newsource = (CharacterIterator) source.clone(); return new CollationElementIterator(newsource, this); }
java
public CollationElementIterator getCollationElementIterator(CharacterIterator source) { initMaxExpansions(); CharacterIterator newsource = (CharacterIterator) source.clone(); return new CollationElementIterator(newsource, this); }
[ "public", "CollationElementIterator", "getCollationElementIterator", "(", "CharacterIterator", "source", ")", "{", "initMaxExpansions", "(", ")", ";", "CharacterIterator", "newsource", "=", "(", "CharacterIterator", ")", "source", ".", "clone", "(", ")", ";", "return"...
Return a CollationElementIterator for the given CharacterIterator. The source iterator's integrity will be preserved since a new copy will be created for use. @see CollationElementIterator
[ "Return", "a", "CollationElementIterator", "for", "the", "given", "CharacterIterator", ".", "The", "source", "iterator", "s", "integrity", "will", "be", "preserved", "since", "a", "new", "copy", "will", "be", "created", "for", "use", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RuleBasedCollator.java#L277-L281
spring-projects/spring-mobile
spring-mobile-device/src/main/java/org/springframework/mobile/device/switcher/SiteSwitcherHandlerInterceptor.java
SiteSwitcherHandlerInterceptor.mDot
public static SiteSwitcherHandlerInterceptor mDot(String serverName, Boolean tabletIsMobile) { return new SiteSwitcherHandlerInterceptor(StandardSiteSwitcherHandlerFactory.mDot(serverName, tabletIsMobile)); }
java
public static SiteSwitcherHandlerInterceptor mDot(String serverName, Boolean tabletIsMobile) { return new SiteSwitcherHandlerInterceptor(StandardSiteSwitcherHandlerFactory.mDot(serverName, tabletIsMobile)); }
[ "public", "static", "SiteSwitcherHandlerInterceptor", "mDot", "(", "String", "serverName", ",", "Boolean", "tabletIsMobile", ")", "{", "return", "new", "SiteSwitcherHandlerInterceptor", "(", "StandardSiteSwitcherHandlerFactory", ".", "mDot", "(", "serverName", ",", "table...
Creates a site switcher that redirects to a <code>m.</code> domain for normal site requests that either originate from a mobile device or indicate a mobile site preference. Uses a {@link CookieSitePreferenceRepository} that saves a cookie that is shared between the two domains.
[ "Creates", "a", "site", "switcher", "that", "redirects", "to", "a", "<code", ">", "m", ".", "<", "/", "code", ">", "domain", "for", "normal", "site", "requests", "that", "either", "originate", "from", "a", "mobile", "device", "or", "indicate", "a", "mobi...
train
https://github.com/spring-projects/spring-mobile/blob/a402cbcaf208e24288b957f44c9984bd6e8bf064/spring-mobile-device/src/main/java/org/springframework/mobile/device/switcher/SiteSwitcherHandlerInterceptor.java#L130-L132
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.beginGenerateVpnProfileAsync
public Observable<String> beginGenerateVpnProfileAsync(String resourceGroupName, String virtualNetworkGatewayName, VpnClientParameters parameters) { return beginGenerateVpnProfileWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, parameters).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); }
java
public Observable<String> beginGenerateVpnProfileAsync(String resourceGroupName, String virtualNetworkGatewayName, VpnClientParameters parameters) { return beginGenerateVpnProfileWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, parameters).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); }
[ "public", "Observable", "<", "String", ">", "beginGenerateVpnProfileAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ",", "VpnClientParameters", "parameters", ")", "{", "return", "beginGenerateVpnProfileWithServiceResponseAsync", "(", "r...
Generates VPN profile for P2S client of the virtual network gateway in the specified resource group. Used for IKEV2 and radius based authentication. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param parameters Parameters supplied to the generate virtual network gateway VPN client package operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the String object
[ "Generates", "VPN", "profile", "for", "P2S", "client", "of", "the", "virtual", "network", "gateway", "in", "the", "specified", "resource", "group", ".", "Used", "for", "IKEV2", "and", "radius", "based", "authentication", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L1734-L1741
openbase/jul
communication/controller/src/main/java/org/openbase/jul/communication/controller/AbstractRemoteClient.java
AbstractRemoteClient.waitForData
@Override public void waitForData() throws CouldNotPerformException, InterruptedException { try { if (isDataAvailable()) { return; } logger.debug("Wait for " + this.toString() + " data..."); getDataFuture().get(); dataObservable.waitForValue(); } catch (ExecutionException | CancellationException ex) { if (shutdownInitiated) { throw new InterruptedException("Interrupt request because system shutdown was initiated!"); } throw new CouldNotPerformException("Could not wait for data!", ex); } }
java
@Override public void waitForData() throws CouldNotPerformException, InterruptedException { try { if (isDataAvailable()) { return; } logger.debug("Wait for " + this.toString() + " data..."); getDataFuture().get(); dataObservable.waitForValue(); } catch (ExecutionException | CancellationException ex) { if (shutdownInitiated) { throw new InterruptedException("Interrupt request because system shutdown was initiated!"); } throw new CouldNotPerformException("Could not wait for data!", ex); } }
[ "@", "Override", "public", "void", "waitForData", "(", ")", "throws", "CouldNotPerformException", ",", "InterruptedException", "{", "try", "{", "if", "(", "isDataAvailable", "(", ")", ")", "{", "return", ";", "}", "logger", ".", "debug", "(", "\"Wait for \"", ...
{@inheritDoc} @throws CouldNotPerformException {@inheritDoc} @throws InterruptedException {@inheritDoc}
[ "{", "@inheritDoc", "}" ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/communication/controller/src/main/java/org/openbase/jul/communication/controller/AbstractRemoteClient.java#L1175-L1190
kikinteractive/ice
ice-jmx/src/main/java/com/kik/config/ice/source/JmxDynamicConfigSource.java
JmxDynamicConfigSource.fireEvent
@Override public void fireEvent(String configName, Optional<String> valueOpt) { this.emitEvent(configName, valueOpt); }
java
@Override public void fireEvent(String configName, Optional<String> valueOpt) { this.emitEvent(configName, valueOpt); }
[ "@", "Override", "public", "void", "fireEvent", "(", "String", "configName", ",", "Optional", "<", "String", ">", "valueOpt", ")", "{", "this", ".", "emitEvent", "(", "configName", ",", "valueOpt", ")", ";", "}" ]
Used by instances of {@link ConfigDynamicMBean} to emit values back to the config system. @param configName full configuration name from the descriptor @param valueOpt the value to be emitted (if different from last emission)
[ "Used", "by", "instances", "of", "{", "@link", "ConfigDynamicMBean", "}", "to", "emit", "values", "back", "to", "the", "config", "system", "." ]
train
https://github.com/kikinteractive/ice/blob/0c58d7bf2d9f6504892d0768d6022fcfa6df7514/ice-jmx/src/main/java/com/kik/config/ice/source/JmxDynamicConfigSource.java#L110-L114
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/RelationshipPrefetcherFactory.java
RelationshipPrefetcherFactory.createRelationshipPrefetcher
public RelationshipPrefetcher createRelationshipPrefetcher(ClassDescriptor anOwnerCld, String aRelationshipName) { ObjectReferenceDescriptor ord; ord = anOwnerCld.getCollectionDescriptorByName(aRelationshipName); if (ord == null) { ord = anOwnerCld.getObjectReferenceDescriptorByName(aRelationshipName); if (ord == null) { throw new PersistenceBrokerException("Relationship named '" + aRelationshipName + "' not found in owner class " + (anOwnerCld != null ? anOwnerCld.getClassNameOfObject() : null)); } } return createRelationshipPrefetcher(ord); }
java
public RelationshipPrefetcher createRelationshipPrefetcher(ClassDescriptor anOwnerCld, String aRelationshipName) { ObjectReferenceDescriptor ord; ord = anOwnerCld.getCollectionDescriptorByName(aRelationshipName); if (ord == null) { ord = anOwnerCld.getObjectReferenceDescriptorByName(aRelationshipName); if (ord == null) { throw new PersistenceBrokerException("Relationship named '" + aRelationshipName + "' not found in owner class " + (anOwnerCld != null ? anOwnerCld.getClassNameOfObject() : null)); } } return createRelationshipPrefetcher(ord); }
[ "public", "RelationshipPrefetcher", "createRelationshipPrefetcher", "(", "ClassDescriptor", "anOwnerCld", ",", "String", "aRelationshipName", ")", "{", "ObjectReferenceDescriptor", "ord", ";", "ord", "=", "anOwnerCld", ".", "getCollectionDescriptorByName", "(", "aRelationship...
create either a CollectionPrefetcher or a ReferencePrefetcher
[ "create", "either", "a", "CollectionPrefetcher", "or", "a", "ReferencePrefetcher" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/RelationshipPrefetcherFactory.java#L65-L80
exoplatform/jcr
exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/metadata/AddMetadataAction.java
AddMetadataAction.extractMetaInfoProperties
private Properties extractMetaInfoProperties(Context ctx, Content content) throws IllegalArgumentException, RepositoryException, IOException, DocumentReadException, HandlerNotFoundException { DocumentReaderService readerService = (DocumentReaderService)((ExoContainer)ctx.get(InvocationContext.EXO_CONTAINER)) .getComponentInstanceOfType(DocumentReaderService.class); if (readerService == null) { throw new IllegalArgumentException("No DocumentReaderService configured for current container"); } Properties props = new Properties(); props = readerService.getDocumentReader(content.mimeType).getProperties(content.stream); return props; }
java
private Properties extractMetaInfoProperties(Context ctx, Content content) throws IllegalArgumentException, RepositoryException, IOException, DocumentReadException, HandlerNotFoundException { DocumentReaderService readerService = (DocumentReaderService)((ExoContainer)ctx.get(InvocationContext.EXO_CONTAINER)) .getComponentInstanceOfType(DocumentReaderService.class); if (readerService == null) { throw new IllegalArgumentException("No DocumentReaderService configured for current container"); } Properties props = new Properties(); props = readerService.getDocumentReader(content.mimeType).getProperties(content.stream); return props; }
[ "private", "Properties", "extractMetaInfoProperties", "(", "Context", "ctx", ",", "Content", "content", ")", "throws", "IllegalArgumentException", ",", "RepositoryException", ",", "IOException", ",", "DocumentReadException", ",", "HandlerNotFoundException", "{", "DocumentRe...
Extracts some metainfo properties from content using {@link DocumentReaderService}. @throws IllegalArgumentException if {@link DocumentReaderService} not configured @throws RepositoryException @throws HandlerNotFoundException @throws DocumentReadException @throws IOException
[ "Extracts", "some", "metainfo", "properties", "from", "content", "using", "{", "@link", "DocumentReaderService", "}", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/metadata/AddMetadataAction.java#L115-L131
apache/groovy
src/main/java/org/codehaus/groovy/runtime/ProcessGroovyMethods.java
ProcessGroovyMethods.consumeProcessErrorStream
public static Thread consumeProcessErrorStream(Process self, Appendable error) { Thread thread = new Thread(new TextDumper(self.getErrorStream(), error)); thread.start(); return thread; }
java
public static Thread consumeProcessErrorStream(Process self, Appendable error) { Thread thread = new Thread(new TextDumper(self.getErrorStream(), error)); thread.start(); return thread; }
[ "public", "static", "Thread", "consumeProcessErrorStream", "(", "Process", "self", ",", "Appendable", "error", ")", "{", "Thread", "thread", "=", "new", "Thread", "(", "new", "TextDumper", "(", "self", ".", "getErrorStream", "(", ")", ",", "error", ")", ")",...
Gets the error stream from a process and reads it to keep the process from blocking due to a full buffer. The processed stream data is appended to the supplied Appendable. A new Thread is started, so this method will return immediately. @param self a Process @param error an Appendable to capture the process stderr @return the Thread @since 1.7.5
[ "Gets", "the", "error", "stream", "from", "a", "process", "and", "reads", "it", "to", "keep", "the", "process", "from", "blocking", "due", "to", "a", "full", "buffer", ".", "The", "processed", "stream", "data", "is", "appended", "to", "the", "supplied", ...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ProcessGroovyMethods.java#L300-L304
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/trento_p/net/Pipe.java
Pipe.setFeatureField
private Number setFeatureField( SimpleFeature pipe, String key ) { Number field = ((Number) pipe.getAttribute(key)); if (field == null) { pm.errorMessage(msg.message("trentoP.error.number") + key); throw new IllegalArgumentException(msg.message("trentoP.error.number") + key); } // return the Number return field; }
java
private Number setFeatureField( SimpleFeature pipe, String key ) { Number field = ((Number) pipe.getAttribute(key)); if (field == null) { pm.errorMessage(msg.message("trentoP.error.number") + key); throw new IllegalArgumentException(msg.message("trentoP.error.number") + key); } // return the Number return field; }
[ "private", "Number", "setFeatureField", "(", "SimpleFeature", "pipe", ",", "String", "key", ")", "{", "Number", "field", "=", "(", "(", "Number", ")", "pipe", ".", "getAttribute", "(", "key", ")", ")", ";", "if", "(", "field", "==", "null", ")", "{", ...
Check if there is the field in a SimpleFeature and if it's a Number. @param pipe the feature. @param key the key string of the field. @return the Number associated at this key.
[ "Check", "if", "there", "is", "the", "field", "in", "a", "SimpleFeature", "and", "if", "it", "s", "a", "Number", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/trento_p/net/Pipe.java#L576-L585
liyiorg/weixin-popular
src/main/java/weixin/popular/api/BizwifiAPI.java
BizwifiAPI.barSet
public static BaseResult barSet(String accessToken, BarSet barSet) { return barSet(accessToken, JsonUtil.toJSONString(barSet)); }
java
public static BaseResult barSet(String accessToken, BarSet barSet) { return barSet(accessToken, JsonUtil.toJSONString(barSet)); }
[ "public", "static", "BaseResult", "barSet", "(", "String", "accessToken", ",", "BarSet", "barSet", ")", "{", "return", "barSet", "(", "accessToken", ",", "JsonUtil", ".", "toJSONString", "(", "barSet", ")", ")", ";", "}" ]
设置微信首页欢迎语 设置微信首页欢迎语,可选择“欢迎光临XXX”或“已连接XXXWiFi”,XXX为公众号名称或门店名称。 @param accessToken accessToken @param barSet barSet @return BaseResult
[ "设置微信首页欢迎语", "设置微信首页欢迎语,可选择“欢迎光临XXX”或“已连接XXXWiFi”,XXX为公众号名称或门店名称。" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/BizwifiAPI.java#L509-L511
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/creational/builder/mapped/FileMappedKeyDirector.java
FileMappedKeyDirector.crawl
protected void crawl(File file, MappedKeyEngineer<K,V> engineer) { if (!file.exists()) { Debugger.println(file + " does not exist."); return; } if (file.isDirectory()) { File[] files = IO.listFiles(file, listPattern); for (int i = 0; i < files.length; i++) { //recursive if(!this.mustSkip(files[i])) crawl(files[i],engineer); } } else { try { engineer.construct(file.getPath(), this.constructMapToText(file.getPath())); crawledPaths.add(file.getPath()); } catch(NoDataFoundException e) { //print warning if found not Debugger.printWarn(e); } } }
java
protected void crawl(File file, MappedKeyEngineer<K,V> engineer) { if (!file.exists()) { Debugger.println(file + " does not exist."); return; } if (file.isDirectory()) { File[] files = IO.listFiles(file, listPattern); for (int i = 0; i < files.length; i++) { //recursive if(!this.mustSkip(files[i])) crawl(files[i],engineer); } } else { try { engineer.construct(file.getPath(), this.constructMapToText(file.getPath())); crawledPaths.add(file.getPath()); } catch(NoDataFoundException e) { //print warning if found not Debugger.printWarn(e); } } }
[ "protected", "void", "crawl", "(", "File", "file", ",", "MappedKeyEngineer", "<", "K", ",", "V", ">", "engineer", ")", "{", "if", "(", "!", "file", ".", "exists", "(", ")", ")", "{", "Debugger", ".", "println", "(", "file", "+", "\" does not exist.\"",...
Director method to construct a document @param file the file the walk through @param engineer the mapped key engineer
[ "Director", "method", "to", "construct", "a", "document" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/creational/builder/mapped/FileMappedKeyDirector.java#L40-L72
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/ui/CmsInlineEditOverlay.java
CmsInlineEditOverlay.setButtonPosition
public void setButtonPosition(CmsInlineEntityWidget widget, int absoluteTop) { if (m_buttonPanel.getWidgetIndex(widget) > -1) { int buttonBarTop = CmsClientStringUtil.parseInt(m_buttonBar.getStyle().getTop()); if (absoluteTop < buttonBarTop) { absoluteTop = buttonBarTop; } int positionTop = getAvailablePosition(widget, absoluteTop) - buttonBarTop; widget.getElement().getStyle().setTop(positionTop, Unit.PX); if (CmsClientStringUtil.parseInt(m_buttonBar.getStyle().getHeight()) < (positionTop + 20)) { increaseOverlayHeight(positionTop + 20); } } }
java
public void setButtonPosition(CmsInlineEntityWidget widget, int absoluteTop) { if (m_buttonPanel.getWidgetIndex(widget) > -1) { int buttonBarTop = CmsClientStringUtil.parseInt(m_buttonBar.getStyle().getTop()); if (absoluteTop < buttonBarTop) { absoluteTop = buttonBarTop; } int positionTop = getAvailablePosition(widget, absoluteTop) - buttonBarTop; widget.getElement().getStyle().setTop(positionTop, Unit.PX); if (CmsClientStringUtil.parseInt(m_buttonBar.getStyle().getHeight()) < (positionTop + 20)) { increaseOverlayHeight(positionTop + 20); } } }
[ "public", "void", "setButtonPosition", "(", "CmsInlineEntityWidget", "widget", ",", "int", "absoluteTop", ")", "{", "if", "(", "m_buttonPanel", ".", "getWidgetIndex", "(", "widget", ")", ">", "-", "1", ")", "{", "int", "buttonBarTop", "=", "CmsClientStringUtil",...
Updates the position of the given button widget.<p> @param widget the button widget @param absoluteTop the top absolute top position
[ "Updates", "the", "position", "of", "the", "given", "button", "widget", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/ui/CmsInlineEditOverlay.java#L309-L322
metamx/java-util
src/main/java/com/metamx/common/StreamUtils.java
StreamUtils.copyWithTimeout
public static long copyWithTimeout(InputStream is, OutputStream os, long timeout) throws IOException, TimeoutException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int n; long startTime = System.currentTimeMillis(); long size = 0; while (-1 != (n = is.read(buffer))) { if (System.currentTimeMillis() - startTime > timeout) { throw new TimeoutException(String.format("Copy time has exceeded %,d millis", timeout)); } os.write(buffer, 0, n); size += n; } return size; }
java
public static long copyWithTimeout(InputStream is, OutputStream os, long timeout) throws IOException, TimeoutException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int n; long startTime = System.currentTimeMillis(); long size = 0; while (-1 != (n = is.read(buffer))) { if (System.currentTimeMillis() - startTime > timeout) { throw new TimeoutException(String.format("Copy time has exceeded %,d millis", timeout)); } os.write(buffer, 0, n); size += n; } return size; }
[ "public", "static", "long", "copyWithTimeout", "(", "InputStream", "is", ",", "OutputStream", "os", ",", "long", "timeout", ")", "throws", "IOException", ",", "TimeoutException", "{", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "DEFAULT_BUFFER_SIZE", ...
Copy from the input stream to the output stream and tries to exit if the copy exceeds the timeout. The timeout is best effort. Specifically, `is.read` will not be interrupted. @param is The input stream to read bytes from. @param os The output stream to write bytes to. @param timeout The timeout (in ms) for the copy operation @return The total size of bytes written to `os` @throws IOException @throws TimeoutException If `tiemout` is exceeded
[ "Copy", "from", "the", "input", "stream", "to", "the", "output", "stream", "and", "tries", "to", "exit", "if", "the", "copy", "exceeds", "the", "timeout", ".", "The", "timeout", "is", "best", "effort", ".", "Specifically", "is", ".", "read", "will", "not...
train
https://github.com/metamx/java-util/blob/9d204043da1136e94fb2e2d63e3543a29bf54b4d/src/main/java/com/metamx/common/StreamUtils.java#L132-L146
JoeKerouac/utils
src/main/java/com/joe/utils/cluster/redis/RedisClusterManagerFactory.java
RedisClusterManagerFactory.newInstance
public static RedisClusterManager newInstance(String host, int port, String password) { return newInstance(buildRedisConfig(host, port, password)); }
java
public static RedisClusterManager newInstance(String host, int port, String password) { return newInstance(buildRedisConfig(host, port, password)); }
[ "public", "static", "RedisClusterManager", "newInstance", "(", "String", "host", ",", "int", "port", ",", "String", "password", ")", "{", "return", "newInstance", "(", "buildRedisConfig", "(", "host", ",", "port", ",", "password", ")", ")", ";", "}" ]
创建一个新的redis实现的分布式管理器 @param host redis的主机地址,例如192.168.1.100 @param port redis的端口,例如8080 @param password 密码 @return redis实现的分布式锁管理器
[ "创建一个新的redis实现的分布式管理器" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/cluster/redis/RedisClusterManagerFactory.java#L84-L86
jparsec/jparsec
jparsec/src/main/java/org/jparsec/pattern/Patterns.java
Patterns.hasExact
public static Pattern hasExact(final int n) { Checks.checkNonNegative(n, "n < 0"); return new Pattern() { @Override public int match(CharSequence src, int begin, int end) { if ((begin + n) != end) return MISMATCH; else return n; } @Override public String toString() { return ".{" + n + "}"; } }; }
java
public static Pattern hasExact(final int n) { Checks.checkNonNegative(n, "n < 0"); return new Pattern() { @Override public int match(CharSequence src, int begin, int end) { if ((begin + n) != end) return MISMATCH; else return n; } @Override public String toString() { return ".{" + n + "}"; } }; }
[ "public", "static", "Pattern", "hasExact", "(", "final", "int", "n", ")", "{", "Checks", ".", "checkNonNegative", "(", "n", ",", "\"n < 0\"", ")", ";", "return", "new", "Pattern", "(", ")", "{", "@", "Override", "public", "int", "match", "(", "CharSequen...
Returns a {@link Pattern} object that matches if the input has exactly {@code n} characters left. Match length is {@code n} if succeed.
[ "Returns", "a", "{" ]
train
https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/pattern/Patterns.java#L146-L157
k3po/k3po
control/src/main/java/org/kaazing/k3po/control/internal/Control.java
Control.readEvent
public CommandEvent readEvent(int timeout, TimeUnit unit) throws Exception { checkConnected(); connection.setReadTimeout((int) unit.toMillis(timeout)); CommandEvent event = null; String eventType = textIn.readLine(); if (Thread.interrupted()) { throw new InterruptedException("thread interrupted during blocking read"); } if (eventType != null) { switch (eventType) { case PREPARED_EVENT: event = readPreparedEvent(); break; case STARTED_EVENT: event = readStartedEvent(); break; case ERROR_EVENT: event = readErrorEvent(); break; case FINISHED_EVENT: event = readFinishedEvent(); break; case NOTIFIED_EVENT: event = readNotifiedEvent(); break; default: throw new IllegalStateException("Invalid protocol frame: " + eventType); } } return event; }
java
public CommandEvent readEvent(int timeout, TimeUnit unit) throws Exception { checkConnected(); connection.setReadTimeout((int) unit.toMillis(timeout)); CommandEvent event = null; String eventType = textIn.readLine(); if (Thread.interrupted()) { throw new InterruptedException("thread interrupted during blocking read"); } if (eventType != null) { switch (eventType) { case PREPARED_EVENT: event = readPreparedEvent(); break; case STARTED_EVENT: event = readStartedEvent(); break; case ERROR_EVENT: event = readErrorEvent(); break; case FINISHED_EVENT: event = readFinishedEvent(); break; case NOTIFIED_EVENT: event = readNotifiedEvent(); break; default: throw new IllegalStateException("Invalid protocol frame: " + eventType); } } return event; }
[ "public", "CommandEvent", "readEvent", "(", "int", "timeout", ",", "TimeUnit", "unit", ")", "throws", "Exception", "{", "checkConnected", "(", ")", ";", "connection", ".", "setReadTimeout", "(", "(", "int", ")", "unit", ".", "toMillis", "(", "timeout", ")", ...
Reads a command event from the wire. @param timeout is the time to read from the connection. @param unit of time for the timeout. @return the CommandEvent read from the wire. @throws Exception if no event is read before the timeout.
[ "Reads", "a", "command", "event", "from", "the", "wire", "." ]
train
https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/control/src/main/java/org/kaazing/k3po/control/internal/Control.java#L176-L213
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfAction.java
PdfAction.javaScript
public static PdfAction javaScript(String code, PdfWriter writer, boolean unicode) { PdfAction js = new PdfAction(); js.put(PdfName.S, PdfName.JAVASCRIPT); if (unicode && code.length() < 50) { js.put(PdfName.JS, new PdfString(code, PdfObject.TEXT_UNICODE)); } else if (!unicode && code.length() < 100) { js.put(PdfName.JS, new PdfString(code)); } else { try { byte b[] = PdfEncodings.convertToBytes(code, unicode ? PdfObject.TEXT_UNICODE : PdfObject.TEXT_PDFDOCENCODING); PdfStream stream = new PdfStream(b); stream.flateCompress(writer.getCompressionLevel()); js.put(PdfName.JS, writer.addToBody(stream).getIndirectReference()); } catch (Exception e) { js.put(PdfName.JS, new PdfString(code)); } } return js; }
java
public static PdfAction javaScript(String code, PdfWriter writer, boolean unicode) { PdfAction js = new PdfAction(); js.put(PdfName.S, PdfName.JAVASCRIPT); if (unicode && code.length() < 50) { js.put(PdfName.JS, new PdfString(code, PdfObject.TEXT_UNICODE)); } else if (!unicode && code.length() < 100) { js.put(PdfName.JS, new PdfString(code)); } else { try { byte b[] = PdfEncodings.convertToBytes(code, unicode ? PdfObject.TEXT_UNICODE : PdfObject.TEXT_PDFDOCENCODING); PdfStream stream = new PdfStream(b); stream.flateCompress(writer.getCompressionLevel()); js.put(PdfName.JS, writer.addToBody(stream).getIndirectReference()); } catch (Exception e) { js.put(PdfName.JS, new PdfString(code)); } } return js; }
[ "public", "static", "PdfAction", "javaScript", "(", "String", "code", ",", "PdfWriter", "writer", ",", "boolean", "unicode", ")", "{", "PdfAction", "js", "=", "new", "PdfAction", "(", ")", ";", "js", ".", "put", "(", "PdfName", ".", "S", ",", "PdfName", ...
Creates a JavaScript action. If the JavaScript is smaller than 50 characters it will be placed as a string, otherwise it will be placed as a compressed stream. @param code the JavaScript code @param writer the writer for this action @param unicode select JavaScript unicode. Note that the internal Acrobat JavaScript engine does not support unicode, so this may or may not work for you @return the JavaScript action
[ "Creates", "a", "JavaScript", "action", ".", "If", "the", "JavaScript", "is", "smaller", "than", "50", "characters", "it", "will", "be", "placed", "as", "a", "string", "otherwise", "it", "will", "be", "placed", "as", "a", "compressed", "stream", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfAction.java#L292-L313
doanduyhai/Achilles
achilles-core/src/main/java/info/archinnov/achilles/internals/dsl/raw/TypedQuery.java
TypedQuery.withRowAsyncListener
public TypedQuery<ENTITY> withRowAsyncListener(Function<Row, Row> rowAsyncListener) { this.options.setRowAsyncListeners(Optional.of(asList(rowAsyncListener))); return this; }
java
public TypedQuery<ENTITY> withRowAsyncListener(Function<Row, Row> rowAsyncListener) { this.options.setRowAsyncListeners(Optional.of(asList(rowAsyncListener))); return this; }
[ "public", "TypedQuery", "<", "ENTITY", ">", "withRowAsyncListener", "(", "Function", "<", "Row", ",", "Row", ">", "rowAsyncListener", ")", "{", "this", ".", "options", ".", "setRowAsyncListeners", "(", "Optional", ".", "of", "(", "asList", "(", "rowAsyncListen...
Add the given async listener on the {@link com.datastax.driver.core.Row} object. Example of usage: <pre class="code"><code class="java"> .withRowAsyncListener(row -> { //Do something with the row object here }) </code></pre> Remark: <strong>You can inspect and read values from the row object</strong>
[ "Add", "the", "given", "async", "listener", "on", "the", "{", "@link", "com", ".", "datastax", ".", "driver", ".", "core", ".", "Row", "}", "object", ".", "Example", "of", "usage", ":", "<pre", "class", "=", "code", ">", "<code", "class", "=", "java"...
train
https://github.com/doanduyhai/Achilles/blob/8281c33100e72c993e570592ae1a5306afac6813/achilles-core/src/main/java/info/archinnov/achilles/internals/dsl/raw/TypedQuery.java#L137-L140
uber/rides-java-sdk
uber-rides/src/main/java/com/uber/sdk/rides/client/error/ErrorParser.java
ErrorParser.parseError
@Nonnull public static ApiError parseError(@Nullable String errorBody, int statusCode, @Nullable String message) { if (errorBody == null) { return new ApiError(null, statusCode, message); } Moshi moshi = new Moshi.Builder().build(); JsonAdapter<CompatibilityApiError> oldApiErrorJsonAdapter = moshi.adapter(CompatibilityApiError.class).failOnUnknown(); try { return new ApiError(oldApiErrorJsonAdapter.fromJson(errorBody), statusCode); } catch (IOException | JsonDataException exception) { // Not old type of error, move on } JsonAdapter<ApiError> apiErrorJsonAdapter = moshi.adapter(ApiError.class).failOnUnknown(); try { return apiErrorJsonAdapter.fromJson(errorBody); } catch (IOException | JsonDataException exception) { return new ApiError(null, statusCode, "Unknown Error"); } }
java
@Nonnull public static ApiError parseError(@Nullable String errorBody, int statusCode, @Nullable String message) { if (errorBody == null) { return new ApiError(null, statusCode, message); } Moshi moshi = new Moshi.Builder().build(); JsonAdapter<CompatibilityApiError> oldApiErrorJsonAdapter = moshi.adapter(CompatibilityApiError.class).failOnUnknown(); try { return new ApiError(oldApiErrorJsonAdapter.fromJson(errorBody), statusCode); } catch (IOException | JsonDataException exception) { // Not old type of error, move on } JsonAdapter<ApiError> apiErrorJsonAdapter = moshi.adapter(ApiError.class).failOnUnknown(); try { return apiErrorJsonAdapter.fromJson(errorBody); } catch (IOException | JsonDataException exception) { return new ApiError(null, statusCode, "Unknown Error"); } }
[ "@", "Nonnull", "public", "static", "ApiError", "parseError", "(", "@", "Nullable", "String", "errorBody", ",", "int", "statusCode", ",", "@", "Nullable", "String", "message", ")", "{", "if", "(", "errorBody", "==", "null", ")", "{", "return", "new", "ApiE...
Parses an error body and code into an {@link ApiError}. @param errorBody the error body from the response. @param statusCode the status code from the response. @param message the message from the response. @return the parsed {@link ApiError}.
[ "Parses", "an", "error", "body", "and", "code", "into", "an", "{", "@link", "ApiError", "}", "." ]
train
https://github.com/uber/rides-java-sdk/blob/6c75570ab7884f8ecafaad312ef471dd33f64c42/uber-rides/src/main/java/com/uber/sdk/rides/client/error/ErrorParser.java#L68-L88
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/serialization/SimpleTupleDeserializer.java
SimpleTupleDeserializer.readFields
public void readFields(ITuple tuple, Deserializer[] customDeserializers) throws IOException { readFields(tuple, readSchema, customDeserializers); }
java
public void readFields(ITuple tuple, Deserializer[] customDeserializers) throws IOException { readFields(tuple, readSchema, customDeserializers); }
[ "public", "void", "readFields", "(", "ITuple", "tuple", ",", "Deserializer", "[", "]", "customDeserializers", ")", "throws", "IOException", "{", "readFields", "(", "tuple", ",", "readSchema", ",", "customDeserializers", ")", ";", "}" ]
Read fields using the specified "readSchema" in the constructor.
[ "Read", "fields", "using", "the", "specified", "readSchema", "in", "the", "constructor", "." ]
train
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/serialization/SimpleTupleDeserializer.java#L138-L140
cloudinary/cloudinary_java
cloudinary-core/src/main/java/com/cloudinary/Api.java
Api.getStreamingProfile
public ApiResponse getStreamingProfile(String name, Map options) throws Exception { if (options == null) options = ObjectUtils.emptyMap(); List<String> uri = Arrays.asList("streaming_profiles", name); return callApi(HttpMethod.GET, uri, ObjectUtils.emptyMap(), options); }
java
public ApiResponse getStreamingProfile(String name, Map options) throws Exception { if (options == null) options = ObjectUtils.emptyMap(); List<String> uri = Arrays.asList("streaming_profiles", name); return callApi(HttpMethod.GET, uri, ObjectUtils.emptyMap(), options); }
[ "public", "ApiResponse", "getStreamingProfile", "(", "String", "name", ",", "Map", "options", ")", "throws", "Exception", "{", "if", "(", "options", "==", "null", ")", "options", "=", "ObjectUtils", ".", "emptyMap", "(", ")", ";", "List", "<", "String", ">...
Get a streaming profile information @param name the name of the profile to fetch @param options additional options @return a streaming profile @throws Exception an exception
[ "Get", "a", "streaming", "profile", "information" ]
train
https://github.com/cloudinary/cloudinary_java/blob/58ee1823180da2dea6a2eb7e5cf00d5a760f8aef/cloudinary-core/src/main/java/com/cloudinary/Api.java#L380-L387
googleads/googleads-java-lib
examples/admanager_axis/src/main/java/admanager/axis/v201808/userservice/GetCurrentUser.java
GetCurrentUser.runExample
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the UserService. UserServiceInterface userService = adManagerServices.get(session, UserServiceInterface.class); // Get the current user. User user = userService.getCurrentUser(); System.out.printf( "User with ID %d, name '%s', email '%s', and role '%s' is the current user.%n", user.getId(), user.getName(), user.getEmail(), user.getRoleName()); }
java
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the UserService. UserServiceInterface userService = adManagerServices.get(session, UserServiceInterface.class); // Get the current user. User user = userService.getCurrentUser(); System.out.printf( "User with ID %d, name '%s', email '%s', and role '%s' is the current user.%n", user.getId(), user.getName(), user.getEmail(), user.getRoleName()); }
[ "public", "static", "void", "runExample", "(", "AdManagerServices", "adManagerServices", ",", "AdManagerSession", "session", ")", "throws", "RemoteException", "{", "// Get the UserService.", "UserServiceInterface", "userService", "=", "adManagerServices", ".", "get", "(", ...
Runs the example. @param adManagerServices the services factory. @param session the session. @throws ApiException if the API request failed with one or more service errors. @throws RemoteException if the API request failed due to other errors.
[ "Runs", "the", "example", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201808/userservice/GetCurrentUser.java#L49-L60
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/StandardContextSpaceService.java
StandardContextSpaceService.fireSpaceCreated
protected void fireSpaceCreated(Space space, boolean isLocalCreation) { for (final SpaceRepositoryListener listener : this.listeners.getListeners(SpaceRepositoryListener.class)) { listener.spaceCreated(space, isLocalCreation); } }
java
protected void fireSpaceCreated(Space space, boolean isLocalCreation) { for (final SpaceRepositoryListener listener : this.listeners.getListeners(SpaceRepositoryListener.class)) { listener.spaceCreated(space, isLocalCreation); } }
[ "protected", "void", "fireSpaceCreated", "(", "Space", "space", ",", "boolean", "isLocalCreation", ")", "{", "for", "(", "final", "SpaceRepositoryListener", "listener", ":", "this", ".", "listeners", ".", "getListeners", "(", "SpaceRepositoryListener", ".", "class",...
Notifies the listeners on the space creation. @param space reference to the created space. @param isLocalCreation indicates if the space was initially created on the current kernel.
[ "Notifies", "the", "listeners", "on", "the", "space", "creation", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/StandardContextSpaceService.java#L346-L350
Erudika/para
para-client/src/main/java/com/erudika/para/client/ParaClient.java
ParaClient.resourcePermissions
public Map<String, Map<String, List<String>>> resourcePermissions() { return getEntity(invokeGet("_permissions", null), Map.class); }
java
public Map<String, Map<String, List<String>>> resourcePermissions() { return getEntity(invokeGet("_permissions", null), Map.class); }
[ "public", "Map", "<", "String", ",", "Map", "<", "String", ",", "List", "<", "String", ">", ">", ">", "resourcePermissions", "(", ")", "{", "return", "getEntity", "(", "invokeGet", "(", "\"_permissions\"", ",", "null", ")", ",", "Map", ".", "class", ")...
Returns the permissions for all subjects and resources for current app. @return a map of subject ids to resource names to a list of allowed methods
[ "Returns", "the", "permissions", "for", "all", "subjects", "and", "resources", "for", "current", "app", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-client/src/main/java/com/erudika/para/client/ParaClient.java#L1411-L1413
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/publickey/AbstractKnownHostsKeyVerification.java
AbstractKnownHostsKeyVerification.allowHost
public void allowHost(String host, SshPublicKey pk, boolean always) throws SshException { // Put the host into the allowed hosts list, overiding any previous // entry if (hashHosts) { SshHmac sha1 = (SshHmac) ComponentManager.getInstance() .supportedHMacsCS().getInstance("hmac-sha1"); byte[] hashSalt = new byte[sha1.getMacLength()]; ComponentManager.getInstance().getRND().nextBytes(hashSalt); sha1.init(hashSalt); sha1.update(host.getBytes()); byte[] theHash = sha1.doFinal(); String names = HASH_MAGIC + Base64.encodeBytes(hashSalt, false) + HASH_DELIM + Base64.encodeBytes(theHash, false); putAllowedKey(names, pk, always); } else { putAllowedKey(host, pk, always); } // allowedHosts.put(host, pk); // If we always want to allow then save the host file with the // new details if (always) { try { saveHostFile(); } catch (IOException ex) { throw new SshException("knownhosts file could not be saved! " + ex.getMessage(), SshException.INTERNAL_ERROR); } } }
java
public void allowHost(String host, SshPublicKey pk, boolean always) throws SshException { // Put the host into the allowed hosts list, overiding any previous // entry if (hashHosts) { SshHmac sha1 = (SshHmac) ComponentManager.getInstance() .supportedHMacsCS().getInstance("hmac-sha1"); byte[] hashSalt = new byte[sha1.getMacLength()]; ComponentManager.getInstance().getRND().nextBytes(hashSalt); sha1.init(hashSalt); sha1.update(host.getBytes()); byte[] theHash = sha1.doFinal(); String names = HASH_MAGIC + Base64.encodeBytes(hashSalt, false) + HASH_DELIM + Base64.encodeBytes(theHash, false); putAllowedKey(names, pk, always); } else { putAllowedKey(host, pk, always); } // allowedHosts.put(host, pk); // If we always want to allow then save the host file with the // new details if (always) { try { saveHostFile(); } catch (IOException ex) { throw new SshException("knownhosts file could not be saved! " + ex.getMessage(), SshException.INTERNAL_ERROR); } } }
[ "public", "void", "allowHost", "(", "String", "host", ",", "SshPublicKey", "pk", ",", "boolean", "always", ")", "throws", "SshException", "{", "// Put the host into the allowed hosts list, overiding any previous", "// entry", "if", "(", "hashHosts", ")", "{", "SshHmac",...
<p> Allows a host key, optionally recording the key to the known_hosts file. </p> @param host the name of the host @param pk the public key to allow @param always true if the key should be written to the known_hosts file @throws InvalidHostFileException if the host file cannot be written @since 0.2.0
[ "<p", ">", "Allows", "a", "host", "key", "optionally", "recording", "the", "key", "to", "the", "known_hosts", "file", ".", "<", "/", "p", ">" ]
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/publickey/AbstractKnownHostsKeyVerification.java#L312-L347
Alexey1Gavrilov/ExpectIt
expectit-core/src/main/java/net/sf/expectit/matcher/SimpleResult.java
SimpleResult.failure
public static Result failure(String input, boolean canStopMatching) { return new SimpleResult(false, input, null, null, canStopMatching); }
java
public static Result failure(String input, boolean canStopMatching) { return new SimpleResult(false, input, null, null, canStopMatching); }
[ "public", "static", "Result", "failure", "(", "String", "input", ",", "boolean", "canStopMatching", ")", "{", "return", "new", "SimpleResult", "(", "false", ",", "input", ",", "null", ",", "null", ",", "canStopMatching", ")", ";", "}" ]
Creates an instance of an unsuccessful match. @param input the input string. @param canStopMatching indicates whether matching operation can be stopped. @return the result object.
[ "Creates", "an", "instance", "of", "an", "unsuccessful", "match", "." ]
train
https://github.com/Alexey1Gavrilov/ExpectIt/blob/5acbe1f8f895fe1dbd63e29bf3ab8e5bbf0873c3/expectit-core/src/main/java/net/sf/expectit/matcher/SimpleResult.java#L146-L148
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java
SerializationUtils.fromJson
public static <T> T fromJson(JsonNode json, Class<T> clazz) { return fromJson(json, clazz, null); }
java
public static <T> T fromJson(JsonNode json, Class<T> clazz) { return fromJson(json, clazz, null); }
[ "public", "static", "<", "T", ">", "T", "fromJson", "(", "JsonNode", "json", ",", "Class", "<", "T", ">", "clazz", ")", "{", "return", "fromJson", "(", "json", ",", "clazz", ",", "null", ")", ";", "}" ]
Deserialize a {@link JsonNode}. @param json @param clazz @return @since 0.6.2
[ "Deserialize", "a", "{", "@link", "JsonNode", "}", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java#L714-L716