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
tractionsoftware/gwt-traction
src/main/java/com/tractionsoftware/gwt/user/server/UTCDateTimeUtils.java
UTCDateTimeUtils.getDateBoxValue
public static final Long getDateBoxValue(TimeZone zone, Date date) { if (date == null) return null; // use a Calendar in the specified timezone to figure out the // date and then convert to GMT Calendar cal = GregorianCalendar.getInstance(zone); cal.setTime(date); Calendar gmt = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT")); // copy the year, month, and day gmt.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); // zero everything else out (for midnight) gmt.set(Calendar.HOUR_OF_DAY, 0); gmt.set(Calendar.MINUTE, 0); gmt.set(Calendar.SECOND, 0); gmt.set(Calendar.MILLISECOND, 0); // midnight at GMT on the date specified return gmt.getTimeInMillis(); }
java
public static final Long getDateBoxValue(TimeZone zone, Date date) { if (date == null) return null; // use a Calendar in the specified timezone to figure out the // date and then convert to GMT Calendar cal = GregorianCalendar.getInstance(zone); cal.setTime(date); Calendar gmt = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT")); // copy the year, month, and day gmt.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); // zero everything else out (for midnight) gmt.set(Calendar.HOUR_OF_DAY, 0); gmt.set(Calendar.MINUTE, 0); gmt.set(Calendar.SECOND, 0); gmt.set(Calendar.MILLISECOND, 0); // midnight at GMT on the date specified return gmt.getTimeInMillis(); }
[ "public", "static", "final", "Long", "getDateBoxValue", "(", "TimeZone", "zone", ",", "Date", "date", ")", "{", "if", "(", "date", "==", "null", ")", "return", "null", ";", "// use a Calendar in the specified timezone to figure out the", "// date and then convert to GMT...
Returns the value for the UTCDateBox for a specified {@link TimeZone} and {@link Date}. @param zone The {@link TimeZone} in which the Date will be rendered. @param date The Date which should be displayed in the UTCTimeBox @return the value for the UTCDateBox or null if the supplied date is null
[ "Returns", "the", "value", "for", "the", "UTCDateBox", "for", "a", "specified", "{", "@link", "TimeZone", "}", "and", "{", "@link", "Date", "}", "." ]
train
https://github.com/tractionsoftware/gwt-traction/blob/efc1423c619439763fb064b777b7235e9ce414a3/src/main/java/com/tractionsoftware/gwt/user/server/UTCDateTimeUtils.java#L80-L102
byoutline/MockServer
src/main/java/com/byoutline/mockserver/HttpMockServer.java
HttpMockServer.startMockApiServer
public static HttpMockServer startMockApiServer(@Nonnull ConfigReader configReader, @Nonnull NetworkType simulatedNetworkType) { try { String configJson = new String(readInitialData(configReader.getMainConfigFile())); JSONObject jsonObj = configJson.isEmpty() ? new JSONObject() : new JSONObject(configJson); sMockServer = new HttpMockServer(jsonObj, configReader, simulatedNetworkType); return sMockServer; } catch (IOException e) { LOGGER.log(Level.SEVERE, "MockServer error:", e); } catch (JSONException e) { LOGGER.log(Level.SEVERE, "MockServer error:", e); } return null; }
java
public static HttpMockServer startMockApiServer(@Nonnull ConfigReader configReader, @Nonnull NetworkType simulatedNetworkType) { try { String configJson = new String(readInitialData(configReader.getMainConfigFile())); JSONObject jsonObj = configJson.isEmpty() ? new JSONObject() : new JSONObject(configJson); sMockServer = new HttpMockServer(jsonObj, configReader, simulatedNetworkType); return sMockServer; } catch (IOException e) { LOGGER.log(Level.SEVERE, "MockServer error:", e); } catch (JSONException e) { LOGGER.log(Level.SEVERE, "MockServer error:", e); } return null; }
[ "public", "static", "HttpMockServer", "startMockApiServer", "(", "@", "Nonnull", "ConfigReader", "configReader", ",", "@", "Nonnull", "NetworkType", "simulatedNetworkType", ")", "{", "try", "{", "String", "configJson", "=", "new", "String", "(", "readInitialData", "...
Starts mock server and keeps reference to it. @param configReader wrapper for platform specific bits @param simulatedNetworkType delay time before response is sent.
[ "Starts", "mock", "server", "and", "keeps", "reference", "to", "it", "." ]
train
https://github.com/byoutline/MockServer/blob/90ab245e2eebffc88d04c2893ddbd193e67dc66e/src/main/java/com/byoutline/mockserver/HttpMockServer.java#L55-L68
Jasig/uPortal
uPortal-security/uPortal-security-permissions/src/main/java/org/apereo/portal/security/provider/AuthorizationImpl.java
AuthorizationImpl.newPrincipal
@Override public IAuthorizationPrincipal newPrincipal(String key, Class type) { final Tuple<String, Class> principalKey = new Tuple<>(key, type); final Element element = this.principalCache.get(principalKey); // principalCache is self populating, it can never return a null entry return (IAuthorizationPrincipal) element.getObjectValue(); }
java
@Override public IAuthorizationPrincipal newPrincipal(String key, Class type) { final Tuple<String, Class> principalKey = new Tuple<>(key, type); final Element element = this.principalCache.get(principalKey); // principalCache is self populating, it can never return a null entry return (IAuthorizationPrincipal) element.getObjectValue(); }
[ "@", "Override", "public", "IAuthorizationPrincipal", "newPrincipal", "(", "String", "key", ",", "Class", "type", ")", "{", "final", "Tuple", "<", "String", ",", "Class", ">", "principalKey", "=", "new", "Tuple", "<>", "(", "key", ",", "type", ")", ";", ...
Factory method for IAuthorizationPrincipal. First check the principal cache, and if not present, create the principal and cache it. @return org.apereo.portal.security.IAuthorizationPrincipal @param key java.lang.String @param type java.lang.Class
[ "Factory", "method", "for", "IAuthorizationPrincipal", ".", "First", "check", "the", "principal", "cache", "and", "if", "not", "present", "create", "the", "principal", "and", "cache", "it", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-permissions/src/main/java/org/apereo/portal/security/provider/AuthorizationImpl.java#L928-L934
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java
AppServiceEnvironmentsInner.listMultiRolePoolsAsync
public Observable<Page<WorkerPoolResourceInner>> listMultiRolePoolsAsync(final String resourceGroupName, final String name) { return listMultiRolePoolsWithServiceResponseAsync(resourceGroupName, name) .map(new Func1<ServiceResponse<Page<WorkerPoolResourceInner>>, Page<WorkerPoolResourceInner>>() { @Override public Page<WorkerPoolResourceInner> call(ServiceResponse<Page<WorkerPoolResourceInner>> response) { return response.body(); } }); }
java
public Observable<Page<WorkerPoolResourceInner>> listMultiRolePoolsAsync(final String resourceGroupName, final String name) { return listMultiRolePoolsWithServiceResponseAsync(resourceGroupName, name) .map(new Func1<ServiceResponse<Page<WorkerPoolResourceInner>>, Page<WorkerPoolResourceInner>>() { @Override public Page<WorkerPoolResourceInner> call(ServiceResponse<Page<WorkerPoolResourceInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "WorkerPoolResourceInner", ">", ">", "listMultiRolePoolsAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "name", ")", "{", "return", "listMultiRolePoolsWithServiceResponseAsync", "(", "resourceGroupName...
Get all multi-role pools. Get all multi-role pools. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;WorkerPoolResourceInner&gt; object
[ "Get", "all", "multi", "-", "role", "pools", ".", "Get", "all", "multi", "-", "role", "pools", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L2095-L2103
logic-ng/LogicNG
src/main/java/org/logicng/solvers/sat/CleaneLingSolver.java
CleaneLingSolver.addOcc
private void addOcc(final int lit, final CLClause c) { assert this.dense; occs(lit).add(c); touch(lit); }
java
private void addOcc(final int lit, final CLClause c) { assert this.dense; occs(lit).add(c); touch(lit); }
[ "private", "void", "addOcc", "(", "final", "int", "lit", ",", "final", "CLClause", "c", ")", "{", "assert", "this", ".", "dense", ";", "occs", "(", "lit", ")", ".", "add", "(", "c", ")", ";", "touch", "(", "lit", ")", ";", "}" ]
Adds a clause to a literal's occurrence list. @param lit the literal @param c the clause
[ "Adds", "a", "clause", "to", "a", "literal", "s", "occurrence", "list", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/sat/CleaneLingSolver.java#L601-L605
nguyenq/tess4j
src/main/java/net/sourceforge/tess4j/Tesseract1.java
Tesseract1.setTessVariable
@Override public void setTessVariable(String key, String value) { prop.setProperty(key, value); }
java
@Override public void setTessVariable(String key, String value) { prop.setProperty(key, value); }
[ "@", "Override", "public", "void", "setTessVariable", "(", "String", "key", ",", "String", "value", ")", "{", "prop", ".", "setProperty", "(", "key", ",", "value", ")", ";", "}" ]
Set the value of Tesseract's internal parameter. @param key variable name, e.g., <code>tessedit_create_hocr</code>, <code>tessedit_char_whitelist</code>, etc. @param value value for corresponding variable, e.g., "1", "0", "0123456789", etc.
[ "Set", "the", "value", "of", "Tesseract", "s", "internal", "parameter", "." ]
train
https://github.com/nguyenq/tess4j/blob/cfcd4a8a44042f150b4aaf7bdf5ffc485a2236e1/src/main/java/net/sourceforge/tess4j/Tesseract1.java#L148-L151
UrielCh/ovh-java-sdk
ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java
ApiOvhDomain.serviceName_email_obfuscated_refresh_POST
public void serviceName_email_obfuscated_refresh_POST(String serviceName, OvhDomainContactTypeEnum[] contactType) throws IOException { String qPath = "/domain/{serviceName}/email/obfuscated/refresh"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "contactType", contactType); exec(qPath, "POST", sb.toString(), o); }
java
public void serviceName_email_obfuscated_refresh_POST(String serviceName, OvhDomainContactTypeEnum[] contactType) throws IOException { String qPath = "/domain/{serviceName}/email/obfuscated/refresh"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "contactType", contactType); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "serviceName_email_obfuscated_refresh_POST", "(", "String", "serviceName", ",", "OvhDomainContactTypeEnum", "[", "]", "contactType", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/domain/{serviceName}/email/obfuscated/refresh\"", ";", "String...
Regenerate the obfuscated email address REST: POST /domain/{serviceName}/email/obfuscated/refresh @param contactType [required] Contact type @param serviceName [required] The internal name of your domain @deprecated
[ "Regenerate", "the", "obfuscated", "email", "address" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java#L1532-L1538
eclipse/hawkbit
hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetTypeManagement.java
JpaDistributionSetTypeManagement.assertSoftwareModuleTypeQuota
private void assertSoftwareModuleTypeQuota(final long id, final int requested) { QuotaHelper.assertAssignmentQuota(id, requested, quotaManagement.getMaxSoftwareModuleTypesPerDistributionSetType(), SoftwareModuleType.class, DistributionSetType.class, distributionSetTypeRepository::countSmTypesById); }
java
private void assertSoftwareModuleTypeQuota(final long id, final int requested) { QuotaHelper.assertAssignmentQuota(id, requested, quotaManagement.getMaxSoftwareModuleTypesPerDistributionSetType(), SoftwareModuleType.class, DistributionSetType.class, distributionSetTypeRepository::countSmTypesById); }
[ "private", "void", "assertSoftwareModuleTypeQuota", "(", "final", "long", "id", ",", "final", "int", "requested", ")", "{", "QuotaHelper", ".", "assertAssignmentQuota", "(", "id", ",", "requested", ",", "quotaManagement", ".", "getMaxSoftwareModuleTypesPerDistributionSe...
Enforces the quota specifiying the maximum number of {@link SoftwareModuleType}s per {@link DistributionSetType}. @param id of the distribution set type @param requested number of software module types to check @throws QuotaExceededException if the software module type quota is exceeded
[ "Enforces", "the", "quota", "specifiying", "the", "maximum", "number", "of", "{", "@link", "SoftwareModuleType", "}", "s", "per", "{", "@link", "DistributionSetType", "}", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetTypeManagement.java#L169-L173
mojohaus/jaxb2-maven-plugin
src/main/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilities.java
FileSystemUtilities.listFiles
@SuppressWarnings("all") public static List<File> listFiles(final File fileOrDir, final List<Filter<File>> fileFilters, final Log log) { return listFiles(fileOrDir, fileFilters, false, log); }
java
@SuppressWarnings("all") public static List<File> listFiles(final File fileOrDir, final List<Filter<File>> fileFilters, final Log log) { return listFiles(fileOrDir, fileFilters, false, log); }
[ "@", "SuppressWarnings", "(", "\"all\"", ")", "public", "static", "List", "<", "File", ">", "listFiles", "(", "final", "File", "fileOrDir", ",", "final", "List", "<", "Filter", "<", "File", ">", ">", "fileFilters", ",", "final", "Log", "log", ")", "{", ...
If the supplied fileOrDir is a File, it is added to the returned List if any of the filters Match. If the supplied fileOrDir is a Directory, it is listed and any of the files immediately within the fileOrDir directory are returned within the resulting List provided that they match any of the supplied filters. @param fileOrDir A File or Directory. @param fileFilters A List of filter of which at least one must match to add the File (or child Files, in case of a directory) to the resulting List. @param log The active Maven Log @return A List holding the supplied File (or child Files, in case fileOrDir is a Directory) given that at least one Filter accepts them.
[ "If", "the", "supplied", "fileOrDir", "is", "a", "File", "it", "is", "added", "to", "the", "returned", "List", "if", "any", "of", "the", "filters", "Match", ".", "If", "the", "supplied", "fileOrDir", "is", "a", "Directory", "it", "is", "listed", "and", ...
train
https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilities.java#L564-L569
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java
ULocale.setKeywordValue
public static String setKeywordValue(String localeID, String keyword, String value) { LocaleIDParser parser = new LocaleIDParser(localeID); parser.setKeywordValue(keyword, value); return parser.getName(); }
java
public static String setKeywordValue(String localeID, String keyword, String value) { LocaleIDParser parser = new LocaleIDParser(localeID); parser.setKeywordValue(keyword, value); return parser.getName(); }
[ "public", "static", "String", "setKeywordValue", "(", "String", "localeID", ",", "String", "keyword", ",", "String", "value", ")", "{", "LocaleIDParser", "parser", "=", "new", "LocaleIDParser", "(", "localeID", ")", ";", "parser", ".", "setKeywordValue", "(", ...
Given a locale id, a keyword, and a value, return a new locale id with an updated keyword and value. If the keyword is null, this removes all keywords from the locale id. Otherwise, if the value is null, this removes the value for this keyword from the locale id. Otherwise, this adds/replaces the value for this keyword in the locale id. The keyword and value must not be empty. <p>Related: {@link #getBaseName(String)} returns the locale ID string with all keywords removed. @param localeID the locale id to modify @param keyword the keyword to add/remove, or null to remove all keywords. @param value the value to add/set, or null to remove this particular keyword. @return the updated locale id
[ "Given", "a", "locale", "id", "a", "keyword", "and", "a", "value", "return", "a", "new", "locale", "id", "with", "an", "updated", "keyword", "and", "value", ".", "If", "the", "keyword", "is", "null", "this", "removes", "all", "keywords", "from", "the", ...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java#L1249-L1253
alkacon/opencms-core
src/org/opencms/gwt/CmsVfsService.java
CmsVfsService.addPageInfo
protected static CmsListInfoBean addPageInfo(CmsObject cms, CmsResource resource, CmsListInfoBean listInfo) throws CmsException { listInfo.setResourceState(resource.getState()); String title = cms.readPropertyObject( resource, CmsPropertyDefinition.PROPERTY_TITLE, false, OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)).getValue(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(title)) { listInfo.setTitle(title); } else { listInfo.setTitle(resource.getName()); } listInfo.setSubTitle(cms.getSitePath(resource)); listInfo.setIsFolder(Boolean.valueOf(resource.isFolder())); String resTypeName = OpenCms.getResourceManager().getResourceType(resource).getTypeName(); CmsExplorerTypeSettings cmsExplorerTypeSettings = OpenCms.getWorkplaceManager().getExplorerTypeSetting( resTypeName); if (null == cmsExplorerTypeSettings) { CmsMessageContainer errMsg = Messages.get().container( Messages.ERR_EXPLORER_TYPE_SETTINGS_FOR_RESOURCE_TYPE_NOT_FOUND_3, resource.getRootPath(), resTypeName, Integer.valueOf(resource.getTypeId())); throw new CmsConfigurationException(errMsg); } String key = cmsExplorerTypeSettings.getKey(); Locale currentLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); CmsMessages messages = OpenCms.getWorkplaceManager().getMessages(currentLocale); String resTypeNiceName = messages.key(key); listInfo.addAdditionalInfo( messages.key(org.opencms.workplace.commons.Messages.GUI_LABEL_TYPE_0), resTypeNiceName); listInfo.setResourceType(resTypeName); listInfo.setBigIconClasses( CmsIconUtil.getIconClasses(CmsIconUtil.getDisplayType(cms, resource), resource.getName(), false)); // set the default file and detail type info String detailType = CmsResourceIcon.getDefaultFileOrDetailType(cms, resource); if (detailType != null) { listInfo.setSmallIconClasses(CmsIconUtil.getIconClasses(detailType, null, true)); } return listInfo; }
java
protected static CmsListInfoBean addPageInfo(CmsObject cms, CmsResource resource, CmsListInfoBean listInfo) throws CmsException { listInfo.setResourceState(resource.getState()); String title = cms.readPropertyObject( resource, CmsPropertyDefinition.PROPERTY_TITLE, false, OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)).getValue(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(title)) { listInfo.setTitle(title); } else { listInfo.setTitle(resource.getName()); } listInfo.setSubTitle(cms.getSitePath(resource)); listInfo.setIsFolder(Boolean.valueOf(resource.isFolder())); String resTypeName = OpenCms.getResourceManager().getResourceType(resource).getTypeName(); CmsExplorerTypeSettings cmsExplorerTypeSettings = OpenCms.getWorkplaceManager().getExplorerTypeSetting( resTypeName); if (null == cmsExplorerTypeSettings) { CmsMessageContainer errMsg = Messages.get().container( Messages.ERR_EXPLORER_TYPE_SETTINGS_FOR_RESOURCE_TYPE_NOT_FOUND_3, resource.getRootPath(), resTypeName, Integer.valueOf(resource.getTypeId())); throw new CmsConfigurationException(errMsg); } String key = cmsExplorerTypeSettings.getKey(); Locale currentLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); CmsMessages messages = OpenCms.getWorkplaceManager().getMessages(currentLocale); String resTypeNiceName = messages.key(key); listInfo.addAdditionalInfo( messages.key(org.opencms.workplace.commons.Messages.GUI_LABEL_TYPE_0), resTypeNiceName); listInfo.setResourceType(resTypeName); listInfo.setBigIconClasses( CmsIconUtil.getIconClasses(CmsIconUtil.getDisplayType(cms, resource), resource.getName(), false)); // set the default file and detail type info String detailType = CmsResourceIcon.getDefaultFileOrDetailType(cms, resource); if (detailType != null) { listInfo.setSmallIconClasses(CmsIconUtil.getIconClasses(detailType, null, true)); } return listInfo; }
[ "protected", "static", "CmsListInfoBean", "addPageInfo", "(", "CmsObject", "cms", ",", "CmsResource", "resource", ",", "CmsListInfoBean", "listInfo", ")", "throws", "CmsException", "{", "listInfo", ".", "setResourceState", "(", "resource", ".", "getState", "(", ")",...
Gets page information of a resource and adds it to the given list info bean.<p> @param cms the CMS context @param resource the resource @param listInfo the list info bean to add the information to @return the list info bean @throws CmsException if the resource info can not be read
[ "Gets", "page", "information", "of", "a", "resource", "and", "adds", "it", "to", "the", "given", "list", "info", "bean", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/gwt/CmsVfsService.java#L325-L369
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/SAXProcessor.java
SAXProcessor.strDistance
public int strDistance(char[] a, char[] b) throws SAXException { if (a.length == b.length) { int distance = 0; for (int i = 0; i < a.length; i++) { int tDist = Math.abs(Character.getNumericValue(a[i]) - Character.getNumericValue(b[i])); distance += tDist; } return distance; } else { throw new SAXException("Unable to compute SAX distance, string lengths are not equal"); } }
java
public int strDistance(char[] a, char[] b) throws SAXException { if (a.length == b.length) { int distance = 0; for (int i = 0; i < a.length; i++) { int tDist = Math.abs(Character.getNumericValue(a[i]) - Character.getNumericValue(b[i])); distance += tDist; } return distance; } else { throw new SAXException("Unable to compute SAX distance, string lengths are not equal"); } }
[ "public", "int", "strDistance", "(", "char", "[", "]", "a", ",", "char", "[", "]", "b", ")", "throws", "SAXException", "{", "if", "(", "a", ".", "length", "==", "b", ".", "length", ")", "{", "int", "distance", "=", "0", ";", "for", "(", "int", ...
Compute the distance between the two strings, this function use the numbers associated with ASCII codes, i.e. distance between a and b would be 1. @param a The first string. @param b The second string. @return The pairwise distance. @throws SAXException if length are differ.
[ "Compute", "the", "distance", "between", "the", "two", "strings", "this", "function", "use", "the", "numbers", "associated", "with", "ASCII", "codes", "i", ".", "e", ".", "distance", "between", "a", "and", "b", "would", "be", "1", "." ]
train
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/SAXProcessor.java#L329-L341
netty/netty
transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java
AbstractEpollStreamChannel.spliceTo
public final ChannelFuture spliceTo(final AbstractEpollStreamChannel ch, final int len, final ChannelPromise promise) { if (ch.eventLoop() != eventLoop()) { throw new IllegalArgumentException("EventLoops are not the same."); } checkPositiveOrZero(len, "len"); if (ch.config().getEpollMode() != EpollMode.LEVEL_TRIGGERED || config().getEpollMode() != EpollMode.LEVEL_TRIGGERED) { throw new IllegalStateException("spliceTo() supported only when using " + EpollMode.LEVEL_TRIGGERED); } checkNotNull(promise, "promise"); if (!isOpen()) { promise.tryFailure(SPLICE_TO_CLOSED_CHANNEL_EXCEPTION); } else { addToSpliceQueue(new SpliceInChannelTask(ch, len, promise)); failSpliceIfClosed(promise); } return promise; }
java
public final ChannelFuture spliceTo(final AbstractEpollStreamChannel ch, final int len, final ChannelPromise promise) { if (ch.eventLoop() != eventLoop()) { throw new IllegalArgumentException("EventLoops are not the same."); } checkPositiveOrZero(len, "len"); if (ch.config().getEpollMode() != EpollMode.LEVEL_TRIGGERED || config().getEpollMode() != EpollMode.LEVEL_TRIGGERED) { throw new IllegalStateException("spliceTo() supported only when using " + EpollMode.LEVEL_TRIGGERED); } checkNotNull(promise, "promise"); if (!isOpen()) { promise.tryFailure(SPLICE_TO_CLOSED_CHANNEL_EXCEPTION); } else { addToSpliceQueue(new SpliceInChannelTask(ch, len, promise)); failSpliceIfClosed(promise); } return promise; }
[ "public", "final", "ChannelFuture", "spliceTo", "(", "final", "AbstractEpollStreamChannel", "ch", ",", "final", "int", "len", ",", "final", "ChannelPromise", "promise", ")", "{", "if", "(", "ch", ".", "eventLoop", "(", ")", "!=", "eventLoop", "(", ")", ")", ...
Splice from this {@link AbstractEpollStreamChannel} to another {@link AbstractEpollStreamChannel}. The {@code len} is the number of bytes to splice. If using {@link Integer#MAX_VALUE} it will splice until the {@link ChannelFuture} was canceled or it was failed. Please note: <ul> <li>both channels need to be registered to the same {@link EventLoop}, otherwise an {@link IllegalArgumentException} is thrown. </li> <li>{@link EpollChannelConfig#getEpollMode()} must be {@link EpollMode#LEVEL_TRIGGERED} for this and the target {@link AbstractEpollStreamChannel}</li> </ul>
[ "Splice", "from", "this", "{", "@link", "AbstractEpollStreamChannel", "}", "to", "another", "{", "@link", "AbstractEpollStreamChannel", "}", ".", "The", "{", "@code", "len", "}", "is", "the", "number", "of", "bytes", "to", "splice", ".", "If", "using", "{", ...
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L162-L180
knowm/XChange
xchange-core/src/main/java/org/knowm/xchange/dto/marketdata/OrderBook.java
OrderBook.ordersEqual
public boolean ordersEqual(OrderBook ob) { if (ob == null) { return false; } Date timestamp = new Date(); OrderBook thisOb = new OrderBook(timestamp, this.getAsks(), this.getBids()); OrderBook thatOb = new OrderBook(timestamp, ob.getAsks(), ob.getBids()); return thisOb.equals(thatOb); }
java
public boolean ordersEqual(OrderBook ob) { if (ob == null) { return false; } Date timestamp = new Date(); OrderBook thisOb = new OrderBook(timestamp, this.getAsks(), this.getBids()); OrderBook thatOb = new OrderBook(timestamp, ob.getAsks(), ob.getBids()); return thisOb.equals(thatOb); }
[ "public", "boolean", "ordersEqual", "(", "OrderBook", "ob", ")", "{", "if", "(", "ob", "==", "null", ")", "{", "return", "false", ";", "}", "Date", "timestamp", "=", "new", "Date", "(", ")", ";", "OrderBook", "thisOb", "=", "new", "OrderBook", "(", "...
Identical to {@link #equals(Object) equals} method except that this ignores different timestamps. In other words, this version of equals returns true if the order internal to the OrderBooks are equal but their timestamps are unequal. It returns false if any order between the two are different. @param ob @return
[ "Identical", "to", "{", "@link", "#equals", "(", "Object", ")", "equals", "}", "method", "except", "that", "this", "ignores", "different", "timestamps", ".", "In", "other", "words", "this", "version", "of", "equals", "returns", "true", "if", "the", "order", ...
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-core/src/main/java/org/knowm/xchange/dto/marketdata/OrderBook.java#L243-L253
ironjacamar/ironjacamar
embedded/src/main/java/org/ironjacamar/embedded/junit4/IronJacamar.java
IronJacamar.resolveBean
private Object resolveBean(String name, Class<?> type) { try { return embedded.lookup(name, type); } catch (Throwable t) { return null; } }
java
private Object resolveBean(String name, Class<?> type) { try { return embedded.lookup(name, type); } catch (Throwable t) { return null; } }
[ "private", "Object", "resolveBean", "(", "String", "name", ",", "Class", "<", "?", ">", "type", ")", "{", "try", "{", "return", "embedded", ".", "lookup", "(", "name", ",", "type", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "return", ...
Resolve a bean @param name The name @param type The type @return The value
[ "Resolve", "a", "bean" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/embedded/src/main/java/org/ironjacamar/embedded/junit4/IronJacamar.java#L640-L650
apptik/jus
android/jus-android/src/main/java/io/apptik/comm/jus/ui/ImageLoader.java
ImageLoader.get
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight, ScaleType scaleType, final Object tag) { // only fulfill requests that were initiated from the main threadId. throwIfNotOnMainThread(); final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType); // Try to look up the request in the cache of remote images. Bitmap cachedBitmap = imageCache.getBitmap(cacheKey); if (cachedBitmap != null) { // Return the cached bitmap. ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null); imageListener.onResponse(container, true); return container; } // The bitmap did not exist in the cache, fetch it! ImageContainer imageContainer = new ImageContainer(null, requestUrl, cacheKey, imageListener); // Update the caller to let them know that they should use the default bitmap. // Note this can be done from the ImageView but then it would be invalidated twice in case // of a cache imageListener.onResponse(imageContainer, true); // Check to see if a request is already in-flight. BatchedImageRequest request = inFlightRequests.get(cacheKey); if (request != null) { // If it is, add this request to the list of listeners. request.addContainer(imageContainer); return imageContainer; } // The request is not already in flight. Send the new request to the network and // track it. ImageRequest newRequest = makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType, cacheKey, tag); requestQueue.add(newRequest); inFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer)); return imageContainer; }
java
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight, ScaleType scaleType, final Object tag) { // only fulfill requests that were initiated from the main threadId. throwIfNotOnMainThread(); final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType); // Try to look up the request in the cache of remote images. Bitmap cachedBitmap = imageCache.getBitmap(cacheKey); if (cachedBitmap != null) { // Return the cached bitmap. ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null); imageListener.onResponse(container, true); return container; } // The bitmap did not exist in the cache, fetch it! ImageContainer imageContainer = new ImageContainer(null, requestUrl, cacheKey, imageListener); // Update the caller to let them know that they should use the default bitmap. // Note this can be done from the ImageView but then it would be invalidated twice in case // of a cache imageListener.onResponse(imageContainer, true); // Check to see if a request is already in-flight. BatchedImageRequest request = inFlightRequests.get(cacheKey); if (request != null) { // If it is, add this request to the list of listeners. request.addContainer(imageContainer); return imageContainer; } // The request is not already in flight. Send the new request to the network and // track it. ImageRequest newRequest = makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType, cacheKey, tag); requestQueue.add(newRequest); inFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer)); return imageContainer; }
[ "public", "ImageContainer", "get", "(", "String", "requestUrl", ",", "ImageListener", "imageListener", ",", "int", "maxWidth", ",", "int", "maxHeight", ",", "ScaleType", "scaleType", ",", "final", "Object", "tag", ")", "{", "// only fulfill requests that were initiate...
Issues a bitmap request with the given URL if that image is not available in the cache, and returns a bitmap container that contains all of the data relating to the request (as well as the default image if the requested image is not available). @param requestUrl The url of the remote image @param imageListener The listener to call when the remote image is loaded @param maxWidth The maximum width of the returned image. @param maxHeight The maximum height of the returned image. @param scaleType The ImageViews ScaleType used to calculate the needed image size. @return A container object that contains all of the properties of the request, as well as the currently available image (default if remote is not loaded).
[ "Issues", "a", "bitmap", "request", "with", "the", "given", "URL", "if", "that", "image", "is", "not", "available", "in", "the", "cache", "and", "returns", "a", "bitmap", "container", "that", "contains", "all", "of", "the", "data", "relating", "to", "the",...
train
https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/android/jus-android/src/main/java/io/apptik/comm/jus/ui/ImageLoader.java#L264-L306
lestard/advanced-bindings
src/main/java/eu/lestard/advanced_bindings/api/NumberBindings.java
NumberBindings.divideSafe
public static NumberBinding divideSafe(ObservableValue<Number> dividend, ObservableValue<Number> divisor) { return divideSafe(dividend, divisor, new SimpleDoubleProperty(0)); }
java
public static NumberBinding divideSafe(ObservableValue<Number> dividend, ObservableValue<Number> divisor) { return divideSafe(dividend, divisor, new SimpleDoubleProperty(0)); }
[ "public", "static", "NumberBinding", "divideSafe", "(", "ObservableValue", "<", "Number", ">", "dividend", ",", "ObservableValue", "<", "Number", ">", "divisor", ")", "{", "return", "divideSafe", "(", "dividend", ",", "divisor", ",", "new", "SimpleDoubleProperty",...
An number binding of a division that won't throw an {@link java.lang.ArithmeticException} when a division by zero happens. See {@link #divideSafe(javafx.beans.value.ObservableIntegerValue, javafx.beans.value.ObservableIntegerValue)} for more informations. @param dividend the observable value used as dividend @param divisor the observable value used as divisor @return the resulting number binding
[ "An", "number", "binding", "of", "a", "division", "that", "won", "t", "throw", "an", "{", "@link", "java", ".", "lang", ".", "ArithmeticException", "}", "when", "a", "division", "by", "zero", "happens", ".", "See", "{", "@link", "#divideSafe", "(", "java...
train
https://github.com/lestard/advanced-bindings/blob/054a5dde261c29f862b971765fa3da3704a13ab4/src/main/java/eu/lestard/advanced_bindings/api/NumberBindings.java#L64-L66
elki-project/elki
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/DiSH.java
DiSH.run
public Clustering<SubspaceModel> run(Database db, Relation<V> relation) { if(mu >= relation.size()) { throw new AbortException("Parameter mu is chosen unreasonably large. This won't yield meaningful results."); } DiSHClusterOrder opticsResult = new Instance(db, relation).run(); if(LOG.isVerbose()) { LOG.verbose("Compute Clusters."); } return computeClusters(relation, opticsResult); }
java
public Clustering<SubspaceModel> run(Database db, Relation<V> relation) { if(mu >= relation.size()) { throw new AbortException("Parameter mu is chosen unreasonably large. This won't yield meaningful results."); } DiSHClusterOrder opticsResult = new Instance(db, relation).run(); if(LOG.isVerbose()) { LOG.verbose("Compute Clusters."); } return computeClusters(relation, opticsResult); }
[ "public", "Clustering", "<", "SubspaceModel", ">", "run", "(", "Database", "db", ",", "Relation", "<", "V", ">", "relation", ")", "{", "if", "(", "mu", ">=", "relation", ".", "size", "(", ")", ")", "{", "throw", "new", "AbortException", "(", "\"Paramet...
Performs the DiSH algorithm on the given database. @param relation Relation to process
[ "Performs", "the", "DiSH", "algorithm", "on", "the", "given", "database", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/DiSH.java#L148-L158
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/networking/nio/NioPipeline.java
NioPipeline.addTaskAndWakeup
final void addTaskAndWakeup(Runnable task) { // in this loop we are going to either send the task to the owner // or store the delayed task to be picked up as soon as the migration // completes for (; ; ) { NioThread localOwner = owner; if (localOwner != null) { // there is an owner, lets send the task. localOwner.addTaskAndWakeup(task); return; } // there is no owner, so we put the task on the delayedTaskStack TaskNode old = delayedTaskStack.get(); TaskNode update = new TaskNode(task, old); if (delayedTaskStack.compareAndSet(old, update)) { break; } } NioThread localOwner = owner; if (localOwner != null) { // an owner was set, but we have no guarantee that he has seen our task. // So lets try to reschedule the delayed tasks to make sure they get executed. restoreTasks(localOwner, delayedTaskStack.getAndSet(null), true); } }
java
final void addTaskAndWakeup(Runnable task) { // in this loop we are going to either send the task to the owner // or store the delayed task to be picked up as soon as the migration // completes for (; ; ) { NioThread localOwner = owner; if (localOwner != null) { // there is an owner, lets send the task. localOwner.addTaskAndWakeup(task); return; } // there is no owner, so we put the task on the delayedTaskStack TaskNode old = delayedTaskStack.get(); TaskNode update = new TaskNode(task, old); if (delayedTaskStack.compareAndSet(old, update)) { break; } } NioThread localOwner = owner; if (localOwner != null) { // an owner was set, but we have no guarantee that he has seen our task. // So lets try to reschedule the delayed tasks to make sure they get executed. restoreTasks(localOwner, delayedTaskStack.getAndSet(null), true); } }
[ "final", "void", "addTaskAndWakeup", "(", "Runnable", "task", ")", "{", "// in this loop we are going to either send the task to the owner", "// or store the delayed task to be picked up as soon as the migration", "// completes", "for", "(", ";", ";", ")", "{", "NioThread", "loca...
Adds a task to be executed on the {@link NioThread owner}. <p> This task is scheduled on the task queue of the owning {@link NioThread}. <p> If the pipeline is currently migrating, this method will make sure the task ends up at the new owner. <p> It is extremely important that this task takes very little time because otherwise it could cause a lot of problems in the IOSystem. <p> This method can be called by any thread. It is a pretty expensive method because it will cause the {@link Selector#wakeup()} method to be called. @param task the task to add.
[ "Adds", "a", "task", "to", "be", "executed", "on", "the", "{", "@link", "NioThread", "owner", "}", ".", "<p", ">", "This", "task", "is", "scheduled", "on", "the", "task", "queue", "of", "the", "owning", "{", "@link", "NioThread", "}", ".", "<p", ">",...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/networking/nio/NioPipeline.java#L181-L207
alkacon/opencms-core
src/org/opencms/ui/login/CmsLoginUI.java
CmsLoginUI.openLoginTarget
public void openLoginTarget(String loginTarget, boolean isPublicPC) { // login was successful, remove login init data from session VaadinService.getCurrentRequest().getWrappedSession().removeAttribute(INIT_DATA_SESSION_ATTR); m_targetOpener.openTarget(loginTarget, isPublicPC); }
java
public void openLoginTarget(String loginTarget, boolean isPublicPC) { // login was successful, remove login init data from session VaadinService.getCurrentRequest().getWrappedSession().removeAttribute(INIT_DATA_SESSION_ATTR); m_targetOpener.openTarget(loginTarget, isPublicPC); }
[ "public", "void", "openLoginTarget", "(", "String", "loginTarget", ",", "boolean", "isPublicPC", ")", "{", "// login was successful, remove login init data from session", "VaadinService", ".", "getCurrentRequest", "(", ")", ".", "getWrappedSession", "(", ")", ".", "remove...
Opens the login target for a logged in user.<p> @param loginTarget the login target @param isPublicPC the public PC flag
[ "Opens", "the", "login", "target", "for", "a", "logged", "in", "user", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/login/CmsLoginUI.java#L457-L462
airlift/slice
src/main/java/io/airlift/slice/SliceUtf8.java
SliceUtf8.countCodePoints
public static int countCodePoints(Slice utf8, int offset, int length) { checkPositionIndexes(offset, offset + length, utf8.length()); // Quick exit if empty string if (length == 0) { return 0; } int continuationBytesCount = 0; // Length rounded to 8 bytes int length8 = length & 0x7FFF_FFF8; for (; offset < length8; offset += 8) { // Count bytes which are NOT the start of a code point continuationBytesCount += countContinuationBytes(utf8.getLongUnchecked(offset)); } // Enough bytes left for 32 bits? if (offset + 4 < length) { // Count bytes which are NOT the start of a code point continuationBytesCount += countContinuationBytes(utf8.getIntUnchecked(offset)); offset += 4; } // Do the rest one by one for (; offset < length; offset++) { // Count bytes which are NOT the start of a code point continuationBytesCount += countContinuationBytes(utf8.getByteUnchecked(offset)); } verify(continuationBytesCount <= length); return length - continuationBytesCount; }
java
public static int countCodePoints(Slice utf8, int offset, int length) { checkPositionIndexes(offset, offset + length, utf8.length()); // Quick exit if empty string if (length == 0) { return 0; } int continuationBytesCount = 0; // Length rounded to 8 bytes int length8 = length & 0x7FFF_FFF8; for (; offset < length8; offset += 8) { // Count bytes which are NOT the start of a code point continuationBytesCount += countContinuationBytes(utf8.getLongUnchecked(offset)); } // Enough bytes left for 32 bits? if (offset + 4 < length) { // Count bytes which are NOT the start of a code point continuationBytesCount += countContinuationBytes(utf8.getIntUnchecked(offset)); offset += 4; } // Do the rest one by one for (; offset < length; offset++) { // Count bytes which are NOT the start of a code point continuationBytesCount += countContinuationBytes(utf8.getByteUnchecked(offset)); } verify(continuationBytesCount <= length); return length - continuationBytesCount; }
[ "public", "static", "int", "countCodePoints", "(", "Slice", "utf8", ",", "int", "offset", ",", "int", "length", ")", "{", "checkPositionIndexes", "(", "offset", ",", "offset", "+", "length", ",", "utf8", ".", "length", "(", ")", ")", ";", "// Quick exit if...
Counts the code points within UTF-8 encoded slice up to {@code length}. <p> Note: This method does not explicitly check for valid UTF-8, and may return incorrect results or throw an exception for invalid UTF-8.
[ "Counts", "the", "code", "points", "within", "UTF", "-", "8", "encoded", "slice", "up", "to", "{" ]
train
https://github.com/airlift/slice/blob/7166cb0319e3655f8ba15f5a7ccf3d2f721c1242/src/main/java/io/airlift/slice/SliceUtf8.java#L114-L145
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/apache/logging/log4j/spi/AbstractLogger.java
AbstractLogger.enter
protected EntryMessage enter(final String fqcn, final Message message) { EntryMessage flowMessage = null; if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) { logMessageSafely(fqcn, Level.TRACE, ENTRY_MARKER, flowMessage = flowMessageFactory.newEntryMessage(message), null); } return flowMessage; }
java
protected EntryMessage enter(final String fqcn, final Message message) { EntryMessage flowMessage = null; if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) { logMessageSafely(fqcn, Level.TRACE, ENTRY_MARKER, flowMessage = flowMessageFactory.newEntryMessage(message), null); } return flowMessage; }
[ "protected", "EntryMessage", "enter", "(", "final", "String", "fqcn", ",", "final", "Message", "message", ")", "{", "EntryMessage", "flowMessage", "=", "null", ";", "if", "(", "isEnabled", "(", "Level", ".", "TRACE", ",", "ENTRY_MARKER", ",", "(", "Object", ...
Logs entry to a method with location information. @param fqcn The fully qualified class name of the <b>caller</b>. @param message the Message. @since 2.6
[ "Logs", "entry", "to", "a", "method", "with", "location", "information", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/apache/logging/log4j/spi/AbstractLogger.java#L571-L578
twotoasters/RecyclerViewLib
library/src/main/java/com/twotoasters/android/support/v7/widget/PositionMap.java
PositionMap.put
public void put(int key, E value) { int i = ContainerHelpers.binarySearch(mKeys, mSize, key); if (i >= 0) { mValues[i] = value; } else { i = ~i; if (i < mSize && mValues[i] == DELETED) { mKeys[i] = key; mValues[i] = value; return; } if (mGarbage && mSize >= mKeys.length) { gc(); // Search again because indices may have changed. i = ~ContainerHelpers.binarySearch(mKeys, mSize, key); } if (mSize >= mKeys.length) { int n = idealIntArraySize(mSize + 1); int[] nkeys = new int[n]; Object[] nvalues = new Object[n]; // Log.e("SparseArray", "grow " + mKeys.length + " to " + n); System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); System.arraycopy(mValues, 0, nvalues, 0, mValues.length); mKeys = nkeys; mValues = nvalues; } if (mSize - i != 0) { // Log.e("SparseArray", "move " + (mSize - i)); System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); System.arraycopy(mValues, i, mValues, i + 1, mSize - i); } mKeys[i] = key; mValues[i] = value; mSize++; } }
java
public void put(int key, E value) { int i = ContainerHelpers.binarySearch(mKeys, mSize, key); if (i >= 0) { mValues[i] = value; } else { i = ~i; if (i < mSize && mValues[i] == DELETED) { mKeys[i] = key; mValues[i] = value; return; } if (mGarbage && mSize >= mKeys.length) { gc(); // Search again because indices may have changed. i = ~ContainerHelpers.binarySearch(mKeys, mSize, key); } if (mSize >= mKeys.length) { int n = idealIntArraySize(mSize + 1); int[] nkeys = new int[n]; Object[] nvalues = new Object[n]; // Log.e("SparseArray", "grow " + mKeys.length + " to " + n); System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); System.arraycopy(mValues, 0, nvalues, 0, mValues.length); mKeys = nkeys; mValues = nvalues; } if (mSize - i != 0) { // Log.e("SparseArray", "move " + (mSize - i)); System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); System.arraycopy(mValues, i, mValues, i + 1, mSize - i); } mKeys[i] = key; mValues[i] = value; mSize++; } }
[ "public", "void", "put", "(", "int", "key", ",", "E", "value", ")", "{", "int", "i", "=", "ContainerHelpers", ".", "binarySearch", "(", "mKeys", ",", "mSize", ",", "key", ")", ";", "if", "(", "i", ">=", "0", ")", "{", "mValues", "[", "i", "]", ...
Adds a mapping from the specified key to the specified value, replacing the previous mapping from the specified key if there was one.
[ "Adds", "a", "mapping", "from", "the", "specified", "key", "to", "the", "specified", "value", "replacing", "the", "previous", "mapping", "from", "the", "specified", "key", "if", "there", "was", "one", "." ]
train
https://github.com/twotoasters/RecyclerViewLib/blob/2379fd5bbf57d4dfc8b28046b7ace950905c75f0/library/src/main/java/com/twotoasters/android/support/v7/widget/PositionMap.java#L181-L226
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/MPP8Reader.java
MPP8Reader.processAssignmentData
private void processAssignmentData() throws IOException { DirectoryEntry assnDir = (DirectoryEntry) m_projectDir.getEntry("TBkndAssn"); FixFix assnFixedData = new FixFix(204, new DocumentInputStream(((DocumentEntry) assnDir.getEntry("FixFix 0")))); if (assnFixedData.getDiff() != 0 || (assnFixedData.getSize() % 238 == 0 && testAssignmentTasks(assnFixedData) == false)) { assnFixedData = new FixFix(238, new DocumentInputStream(((DocumentEntry) assnDir.getEntry("FixFix 0")))); } int count = assnFixedData.getItemCount(); FixDeferFix assnVarData = null; for (int loop = 0; loop < count; loop++) { if (assnVarData == null) { assnVarData = new FixDeferFix(new DocumentInputStream(((DocumentEntry) assnDir.getEntry("FixDeferFix 0")))); } byte[] data = assnFixedData.getByteArrayValue(loop); // // Check that the deleted flag isn't set // if (MPPUtility.getByte(data, 168) != 0x02) { Task task = m_file.getTaskByUniqueID(Integer.valueOf(MPPUtility.getInt(data, 16))); Resource resource = m_file.getResourceByUniqueID(Integer.valueOf(MPPUtility.getInt(data, 20))); if (task != null && resource != null) { ResourceAssignment assignment = task.addResourceAssignment(resource); assignment.setActualCost(NumberHelper.getDouble(((double) MPPUtility.getLong6(data, 138)) / 100)); assignment.setActualWork(MPPUtility.getDuration(((double) MPPUtility.getLong6(data, 96)) / 100, TimeUnit.HOURS)); assignment.setCost(NumberHelper.getDouble(((double) MPPUtility.getLong6(data, 132)) / 100)); //assignment.setDelay(); // Not sure what this field maps on to in MSP assignment.setFinish(MPPUtility.getTimestamp(data, 28)); assignment.setOvertimeWork(MPPUtility.getDuration(((double) MPPUtility.getLong6(data, 90)) / 100, TimeUnit.HOURS)); //assignment.setPlannedCost(); // Not sure what this field maps on to in MSP //assignment.setPlannedWork(); // Not sure what this field maps on to in MSP assignment.setRemainingWork(MPPUtility.getDuration(((double) MPPUtility.getLong6(data, 114)) / 100, TimeUnit.HOURS)); assignment.setStart(MPPUtility.getTimestamp(data, 24)); assignment.setUniqueID(Integer.valueOf(MPPUtility.getInt(data, 0))); assignment.setUnits(Double.valueOf(((double) MPPUtility.getShort(data, 80)) / 100)); assignment.setWork(MPPUtility.getDuration(((double) MPPUtility.getLong6(data, 84)) / 100, TimeUnit.HOURS)); m_eventManager.fireAssignmentReadEvent(assignment); } } } }
java
private void processAssignmentData() throws IOException { DirectoryEntry assnDir = (DirectoryEntry) m_projectDir.getEntry("TBkndAssn"); FixFix assnFixedData = new FixFix(204, new DocumentInputStream(((DocumentEntry) assnDir.getEntry("FixFix 0")))); if (assnFixedData.getDiff() != 0 || (assnFixedData.getSize() % 238 == 0 && testAssignmentTasks(assnFixedData) == false)) { assnFixedData = new FixFix(238, new DocumentInputStream(((DocumentEntry) assnDir.getEntry("FixFix 0")))); } int count = assnFixedData.getItemCount(); FixDeferFix assnVarData = null; for (int loop = 0; loop < count; loop++) { if (assnVarData == null) { assnVarData = new FixDeferFix(new DocumentInputStream(((DocumentEntry) assnDir.getEntry("FixDeferFix 0")))); } byte[] data = assnFixedData.getByteArrayValue(loop); // // Check that the deleted flag isn't set // if (MPPUtility.getByte(data, 168) != 0x02) { Task task = m_file.getTaskByUniqueID(Integer.valueOf(MPPUtility.getInt(data, 16))); Resource resource = m_file.getResourceByUniqueID(Integer.valueOf(MPPUtility.getInt(data, 20))); if (task != null && resource != null) { ResourceAssignment assignment = task.addResourceAssignment(resource); assignment.setActualCost(NumberHelper.getDouble(((double) MPPUtility.getLong6(data, 138)) / 100)); assignment.setActualWork(MPPUtility.getDuration(((double) MPPUtility.getLong6(data, 96)) / 100, TimeUnit.HOURS)); assignment.setCost(NumberHelper.getDouble(((double) MPPUtility.getLong6(data, 132)) / 100)); //assignment.setDelay(); // Not sure what this field maps on to in MSP assignment.setFinish(MPPUtility.getTimestamp(data, 28)); assignment.setOvertimeWork(MPPUtility.getDuration(((double) MPPUtility.getLong6(data, 90)) / 100, TimeUnit.HOURS)); //assignment.setPlannedCost(); // Not sure what this field maps on to in MSP //assignment.setPlannedWork(); // Not sure what this field maps on to in MSP assignment.setRemainingWork(MPPUtility.getDuration(((double) MPPUtility.getLong6(data, 114)) / 100, TimeUnit.HOURS)); assignment.setStart(MPPUtility.getTimestamp(data, 24)); assignment.setUniqueID(Integer.valueOf(MPPUtility.getInt(data, 0))); assignment.setUnits(Double.valueOf(((double) MPPUtility.getShort(data, 80)) / 100)); assignment.setWork(MPPUtility.getDuration(((double) MPPUtility.getLong6(data, 84)) / 100, TimeUnit.HOURS)); m_eventManager.fireAssignmentReadEvent(assignment); } } } }
[ "private", "void", "processAssignmentData", "(", ")", "throws", "IOException", "{", "DirectoryEntry", "assnDir", "=", "(", "DirectoryEntry", ")", "m_projectDir", ".", "getEntry", "(", "\"TBkndAssn\"", ")", ";", "FixFix", "assnFixedData", "=", "new", "FixFix", "(",...
This method extracts and collates resource assignment data. @throws IOException
[ "This", "method", "extracts", "and", "collates", "resource", "assignment", "data", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPP8Reader.java#L1095-L1145
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/axes/AxesWalker.java
AxesWalker.callVisitors
public void callVisitors(ExpressionOwner owner, XPathVisitor visitor) { if(visitor.visitStep(owner, this)) { callPredicateVisitors(visitor); if(null != m_nextWalker) { m_nextWalker.callVisitors(this, visitor); } } }
java
public void callVisitors(ExpressionOwner owner, XPathVisitor visitor) { if(visitor.visitStep(owner, this)) { callPredicateVisitors(visitor); if(null != m_nextWalker) { m_nextWalker.callVisitors(this, visitor); } } }
[ "public", "void", "callVisitors", "(", "ExpressionOwner", "owner", ",", "XPathVisitor", "visitor", ")", "{", "if", "(", "visitor", ".", "visitStep", "(", "owner", ",", "this", ")", ")", "{", "callPredicateVisitors", "(", "visitor", ")", ";", "if", "(", "nu...
This will traverse the heararchy, calling the visitor for each member. If the called visitor method returns false, the subtree should not be called. @param owner The owner of the visitor, where that path may be rewritten if needed. @param visitor The visitor whose appropriate method will be called.
[ "This", "will", "traverse", "the", "heararchy", "calling", "the", "visitor", "for", "each", "member", ".", "If", "the", "called", "visitor", "method", "returns", "false", "the", "subtree", "should", "not", "be", "called", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/axes/AxesWalker.java#L520-L530
soi-toolkit/soi-toolkit-mule
commons/components/commons-mule/src/main/java/org/soitoolkit/commons/mule/ftp/FtpUtil.java
FtpUtil.initEndpointDirectory
public static void initEndpointDirectory(MuleContext muleContext, String endpointName) throws Exception { logger.info("Init directory for endpoint: {}", endpointName); FTPClient ftpClient = null; try { ftpClient = getFtpClient(muleContext, endpointName); EndpointURI endpointURI = getImmutableEndpoint(muleContext, endpointName).getEndpointURI(); String path = endpointURI.getPath(); try { if (path.startsWith("/~/")) { path = path.substring(3); // Strip off the leading "/~/" to apply the command to the home-folder } else if (path.startsWith("/")) { path = path.substring(1); // Strip off the leading "/" to apply the command to the home-folder } recursiveDeleteDirectory(ftpClient, path); recursiveCreateDirectory(ftpClient, path); } catch (IOException e) { if (logger.isErrorEnabled()) logger.error("Failed to recursivly delete endpoint " + endpointName, e); } } finally { if (ftpClient != null) { ftpClient.disconnect(); } } }
java
public static void initEndpointDirectory(MuleContext muleContext, String endpointName) throws Exception { logger.info("Init directory for endpoint: {}", endpointName); FTPClient ftpClient = null; try { ftpClient = getFtpClient(muleContext, endpointName); EndpointURI endpointURI = getImmutableEndpoint(muleContext, endpointName).getEndpointURI(); String path = endpointURI.getPath(); try { if (path.startsWith("/~/")) { path = path.substring(3); // Strip off the leading "/~/" to apply the command to the home-folder } else if (path.startsWith("/")) { path = path.substring(1); // Strip off the leading "/" to apply the command to the home-folder } recursiveDeleteDirectory(ftpClient, path); recursiveCreateDirectory(ftpClient, path); } catch (IOException e) { if (logger.isErrorEnabled()) logger.error("Failed to recursivly delete endpoint " + endpointName, e); } } finally { if (ftpClient != null) { ftpClient.disconnect(); } } }
[ "public", "static", "void", "initEndpointDirectory", "(", "MuleContext", "muleContext", ",", "String", "endpointName", ")", "throws", "Exception", "{", "logger", ".", "info", "(", "\"Init directory for endpoint: {}\"", ",", "endpointName", ")", ";", "FTPClient", "ftpC...
Ensures that the directory exists and is writable by deleting the directory and then recreate it. @param muleContext @param endpointName @throws Exception
[ "Ensures", "that", "the", "directory", "exists", "and", "is", "writable", "by", "deleting", "the", "directory", "and", "then", "recreate", "it", "." ]
train
https://github.com/soi-toolkit/soi-toolkit-mule/blob/e891350dbf55e6307be94d193d056bdb785b37d3/commons/components/commons-mule/src/main/java/org/soitoolkit/commons/mule/ftp/FtpUtil.java#L54-L84
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java
AsynchronousRequest.getCharacterSpecialization
public void getCharacterSpecialization(String API, String name, Callback<CharacterSpecialization> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ParamType.API, API), new ParamChecker(ParamType.CHAR, name)); gw2API.getCharacterSpecialization(name, API).enqueue(callback); }
java
public void getCharacterSpecialization(String API, String name, Callback<CharacterSpecialization> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ParamType.API, API), new ParamChecker(ParamType.CHAR, name)); gw2API.getCharacterSpecialization(name, API).enqueue(callback); }
[ "public", "void", "getCharacterSpecialization", "(", "String", "API", ",", "String", "name", ",", "Callback", "<", "CharacterSpecialization", ">", "callback", ")", "throws", "GuildWars2Exception", ",", "NullPointerException", "{", "isParamValid", "(", "new", "ParamChe...
For more info on Character Specialization API go <a href="https://wiki.guildwars2.com/wiki/API:2/characters#Specialization">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions @param API API key @param name character name @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws GuildWars2Exception invalid API key | empty character name @throws NullPointerException if given {@link Callback} is empty @see CharacterSpecialization character specialization info
[ "For", "more", "info", "on", "Character", "Specialization", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "characters#Specialization", ">", "here<", "/", "a", ">", "<b...
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L845-L848
mqlight/java-mqlight
mqlight/src/main/java/com/ibm/mqlight/api/impl/network/NettyNetworkService.java
NettyNetworkService.getBootstrap
private static synchronized Bootstrap getBootstrap(final boolean secure, final ChannelHandler handler) { final String methodName = "getBootstrap"; logger.entry(methodName, secure); ++useCount; if (useCount == 1) { EventLoopGroup workerGroup = new NioEventLoopGroup(); bootstrap = new Bootstrap(); bootstrap.group(workerGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000); bootstrap.handler(handler); } final Bootstrap result; if (secure) { result = bootstrap.clone(); result.handler(handler); } else { result = bootstrap; } logger.exit(methodName, result); return result; }
java
private static synchronized Bootstrap getBootstrap(final boolean secure, final ChannelHandler handler) { final String methodName = "getBootstrap"; logger.entry(methodName, secure); ++useCount; if (useCount == 1) { EventLoopGroup workerGroup = new NioEventLoopGroup(); bootstrap = new Bootstrap(); bootstrap.group(workerGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000); bootstrap.handler(handler); } final Bootstrap result; if (secure) { result = bootstrap.clone(); result.handler(handler); } else { result = bootstrap; } logger.exit(methodName, result); return result; }
[ "private", "static", "synchronized", "Bootstrap", "getBootstrap", "(", "final", "boolean", "secure", ",", "final", "ChannelHandler", "handler", ")", "{", "final", "String", "methodName", "=", "\"getBootstrap\"", ";", "logger", ".", "entry", "(", "methodName", ",",...
Request a {@link Bootstrap} for obtaining a {@link Channel} and track that the workerGroup is being used. @param secure a {@code boolean} indicating whether or not a secure channel will be required @param handler a {@link ChannelHandler} to use for serving the requests. @return a netty {@link Bootstrap} object suitable for obtaining a {@link Channel} from
[ "Request", "a", "{", "@link", "Bootstrap", "}", "for", "obtaining", "a", "{", "@link", "Channel", "}", "and", "track", "that", "the", "workerGroup", "is", "being", "used", "." ]
train
https://github.com/mqlight/java-mqlight/blob/a565dfa6044050826d1221697da9e3268b557aeb/mqlight/src/main/java/com/ibm/mqlight/api/impl/network/NettyNetworkService.java#L443-L469
Javacord/Javacord
javacord-core/src/main/java/org/javacord/core/entity/server/ServerImpl.java
ServerImpl.getOrCreateChannelCategory
public ChannelCategory getOrCreateChannelCategory(JsonNode data) { long id = Long.parseLong(data.get("id").asText()); ChannelType type = ChannelType.fromId(data.get("type").asInt()); synchronized (this) { if (type == ChannelType.CHANNEL_CATEGORY) { return getChannelCategoryById(id).orElseGet(() -> new ChannelCategoryImpl(api, this, data)); } } // Invalid channel type return null; }
java
public ChannelCategory getOrCreateChannelCategory(JsonNode data) { long id = Long.parseLong(data.get("id").asText()); ChannelType type = ChannelType.fromId(data.get("type").asInt()); synchronized (this) { if (type == ChannelType.CHANNEL_CATEGORY) { return getChannelCategoryById(id).orElseGet(() -> new ChannelCategoryImpl(api, this, data)); } } // Invalid channel type return null; }
[ "public", "ChannelCategory", "getOrCreateChannelCategory", "(", "JsonNode", "data", ")", "{", "long", "id", "=", "Long", ".", "parseLong", "(", "data", ".", "get", "(", "\"id\"", ")", ".", "asText", "(", ")", ")", ";", "ChannelType", "type", "=", "ChannelT...
Gets or creates a channel category. @param data The json data of the channel. @return The server text channel.
[ "Gets", "or", "creates", "a", "channel", "category", "." ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-core/src/main/java/org/javacord/core/entity/server/ServerImpl.java#L600-L610
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/dao/AbstractHibernateDao.java
AbstractHibernateDao.updateByHql
public int updateByHql(String secondHalfOfHql, Object[] paramValues, Type[] paramTypes){ StringBuilder queryStr = new StringBuilder(); queryStr.append("update ") .append(this.clazz.getName()) .append(" "); if (secondHalfOfHql != null){ queryStr.append(secondHalfOfHql); } Session session = this.getCurrentSession(); Query query = session.createQuery(queryStr.toString()); setupQuery(query, paramValues, paramTypes, null, null); return query.executeUpdate(); }
java
public int updateByHql(String secondHalfOfHql, Object[] paramValues, Type[] paramTypes){ StringBuilder queryStr = new StringBuilder(); queryStr.append("update ") .append(this.clazz.getName()) .append(" "); if (secondHalfOfHql != null){ queryStr.append(secondHalfOfHql); } Session session = this.getCurrentSession(); Query query = session.createQuery(queryStr.toString()); setupQuery(query, paramValues, paramTypes, null, null); return query.executeUpdate(); }
[ "public", "int", "updateByHql", "(", "String", "secondHalfOfHql", ",", "Object", "[", "]", "paramValues", ",", "Type", "[", "]", "paramTypes", ")", "{", "StringBuilder", "queryStr", "=", "new", "StringBuilder", "(", ")", ";", "queryStr", ".", "append", "(", ...
Update by criteria specified as HQL @param secondHalfOfHql @param paramValues @param paramTypes @return the number of records updated
[ "Update", "by", "criteria", "specified", "as", "HQL" ]
train
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/dao/AbstractHibernateDao.java#L455-L468
OpenLiberty/open-liberty
dev/com.ibm.ws.app.manager/src/com/ibm/ws/app/manager/AppMessageHelper.java
AppMessageHelper.formatMessage
public String formatMessage(String key, Object... params) { return Tr.formatMessage(tc, key, params); }
java
public String formatMessage(String key, Object... params) { return Tr.formatMessage(tc, key, params); }
[ "public", "String", "formatMessage", "(", "String", "key", ",", "Object", "...", "params", ")", "{", "return", "Tr", ".", "formatMessage", "(", "tc", ",", "key", ",", "params", ")", ";", "}" ]
Format a message. @param key message key for the application manager messages file. @param params message parameters. @return the translated message.
[ "Format", "a", "message", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.app.manager/src/com/ibm/ws/app/manager/AppMessageHelper.java#L48-L50
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/ComponentAccess.java
ComponentAccess.callAnnotated
public static void callAnnotated(Object o, Class<? extends Annotation> ann, boolean lazy) { try { getMethodOfInterest(o, ann).invoke(o); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex.getCause()); } catch (IllegalArgumentException ex) { if (!lazy) { throw new RuntimeException(ex.getMessage()); } } }
java
public static void callAnnotated(Object o, Class<? extends Annotation> ann, boolean lazy) { try { getMethodOfInterest(o, ann).invoke(o); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex.getCause()); } catch (IllegalArgumentException ex) { if (!lazy) { throw new RuntimeException(ex.getMessage()); } } }
[ "public", "static", "void", "callAnnotated", "(", "Object", "o", ",", "Class", "<", "?", "extends", "Annotation", ">", "ann", ",", "boolean", "lazy", ")", "{", "try", "{", "getMethodOfInterest", "(", "o", ",", "ann", ")", ".", "invoke", "(", "o", ")", ...
Call an method by Annotation. @param o the object to call. @param ann the annotation @param lazy if true, the a missing annotation is OK. if false the annotation has to be present or a Runtime exception is thrown.
[ "Call", "an", "method", "by", "Annotation", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/ComponentAccess.java#L255-L267
osiam/connector4java
src/main/java/org/osiam/client/OsiamConnector.java
OsiamConnector.getClient
public Client getClient(String clientId, AccessToken accessToken) { return getAuthService().getClient(clientId, accessToken); }
java
public Client getClient(String clientId, AccessToken accessToken) { return getAuthService().getClient(clientId, accessToken); }
[ "public", "Client", "getClient", "(", "String", "clientId", ",", "AccessToken", "accessToken", ")", "{", "return", "getAuthService", "(", ")", ".", "getClient", "(", "clientId", ",", "accessToken", ")", ";", "}" ]
Get client by the given client id. @param clientId the client id @param accessToken the access token used to access the service @return The found client @throws UnauthorizedException if the accessToken is not valid @throws ForbiddenException if access to this resource is not allowed @throws ConnectionInitializationException if the connection to the given OSIAM service could not be initialized @throws ClientNotFoundException if no client with the given id can be found @throws IllegalStateException if OSIAM's endpoint(s) are not properly configured
[ "Get", "client", "by", "the", "given", "client", "id", "." ]
train
https://github.com/osiam/connector4java/blob/a5e6ae1e706f4889d662a069fe2f3bf8e3848d12/src/main/java/org/osiam/client/OsiamConnector.java#L636-L638
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java
DomHelper.createOrUpdateElement
public Element createOrUpdateElement(Object parent, String name, String type, Style style, boolean generateId) { Element element; // check existence if (name != null) { if (!generateId) { element = Dom.getElementById(name); } else { element = getElement(parent, name); } } else { return null; } if (element == null) { // Element was not found, so create it: element = createElement(parent, name, type, style, generateId); } else { // Element was found, so update it: applyStyle(element, style); } // no luck ! if (element == null) { return null; } return element; }
java
public Element createOrUpdateElement(Object parent, String name, String type, Style style, boolean generateId) { Element element; // check existence if (name != null) { if (!generateId) { element = Dom.getElementById(name); } else { element = getElement(parent, name); } } else { return null; } if (element == null) { // Element was not found, so create it: element = createElement(parent, name, type, style, generateId); } else { // Element was found, so update it: applyStyle(element, style); } // no luck ! if (element == null) { return null; } return element; }
[ "public", "Element", "createOrUpdateElement", "(", "Object", "parent", ",", "String", "name", ",", "String", "type", ",", "Style", "style", ",", "boolean", "generateId", ")", "{", "Element", "element", ";", "// check existence", "if", "(", "name", "!=", "null"...
Create or update an element in the DOM. The id will be generated. @param parent the parent group @param name the local group name of the element (should be unique within the group) @param type the type of the element (tag name, e.g. 'image') @param style The style to apply on the element. @param generateId true if a unique id may be generated. If false, the name will be used as id and should therefore be unique @return the created or updated element or null if creation failed or name was null
[ "Create", "or", "update", "an", "element", "in", "the", "DOM", ".", "The", "id", "will", "be", "generated", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java#L162-L186
facebookarchive/hadoop-20
src/core/org/apache/hadoop/filecache/DistributedCache.java
DistributedCache.releaseCache
public static void releaseCache(URI cache, Configuration conf, long timeStamp) throws IOException { String cacheId = getKey(cache, conf, timeStamp); synchronized (cachedArchives) { CacheStatus lcacheStatus = cachedArchives.get(cacheId); if (lcacheStatus == null) { LOG.warn("Cannot find localized cache: " + cache + " (key: " + cacheId + ") in releaseCache!"); return; } lcacheStatus.refcount--; } }
java
public static void releaseCache(URI cache, Configuration conf, long timeStamp) throws IOException { String cacheId = getKey(cache, conf, timeStamp); synchronized (cachedArchives) { CacheStatus lcacheStatus = cachedArchives.get(cacheId); if (lcacheStatus == null) { LOG.warn("Cannot find localized cache: " + cache + " (key: " + cacheId + ") in releaseCache!"); return; } lcacheStatus.refcount--; } }
[ "public", "static", "void", "releaseCache", "(", "URI", "cache", ",", "Configuration", "conf", ",", "long", "timeStamp", ")", "throws", "IOException", "{", "String", "cacheId", "=", "getKey", "(", "cache", ",", "conf", ",", "timeStamp", ")", ";", "synchroniz...
This is the opposite of getlocalcache. When you are done with using the cache, you need to release the cache @param cache The cache URI to be released @param conf configuration which contains the filesystem the cache is contained in. @throws IOException
[ "This", "is", "the", "opposite", "of", "getlocalcache", ".", "When", "you", "are", "done", "with", "using", "the", "cache", "you", "need", "to", "release", "the", "cache" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/filecache/DistributedCache.java#L377-L390
JodaOrg/joda-time
src/main/java/org/joda/time/Months.java
Months.monthsBetween
public static Months monthsBetween(ReadablePartial start, ReadablePartial end) { if (start instanceof LocalDate && end instanceof LocalDate) { Chronology chrono = DateTimeUtils.getChronology(start.getChronology()); int months = chrono.months().getDifference( ((LocalDate) end).getLocalMillis(), ((LocalDate) start).getLocalMillis()); return Months.months(months); } int amount = BaseSingleFieldPeriod.between(start, end, ZERO); return Months.months(amount); }
java
public static Months monthsBetween(ReadablePartial start, ReadablePartial end) { if (start instanceof LocalDate && end instanceof LocalDate) { Chronology chrono = DateTimeUtils.getChronology(start.getChronology()); int months = chrono.months().getDifference( ((LocalDate) end).getLocalMillis(), ((LocalDate) start).getLocalMillis()); return Months.months(months); } int amount = BaseSingleFieldPeriod.between(start, end, ZERO); return Months.months(amount); }
[ "public", "static", "Months", "monthsBetween", "(", "ReadablePartial", "start", ",", "ReadablePartial", "end", ")", "{", "if", "(", "start", "instanceof", "LocalDate", "&&", "end", "instanceof", "LocalDate", ")", "{", "Chronology", "chrono", "=", "DateTimeUtils", ...
Creates a <code>Months</code> representing the number of whole months between the two specified partial datetimes. <p> The two partials must contain the same fields, for example you can specify two <code>LocalDate</code> objects. <p> This method calculates by adding months to the start date until the result is past the end date. As such, a period from the end of a "long" month to the end of a "short" month is counted as a whole month. @param start the start partial date, must not be null @param end the end partial date, must not be null @return the period in months @throws IllegalArgumentException if the partials are null or invalid
[ "Creates", "a", "<code", ">", "Months<", "/", "code", ">", "representing", "the", "number", "of", "whole", "months", "between", "the", "two", "specified", "partial", "datetimes", ".", "<p", ">", "The", "two", "partials", "must", "contain", "the", "same", "...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/Months.java#L162-L171
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/extensions/ExtensionNamespacesManager.java
ExtensionNamespacesManager.namespaceIndex
public int namespaceIndex(String namespace, Vector extensions) { for (int i = 0; i < extensions.size(); i++) { if (((ExtensionNamespaceSupport)extensions.get(i)).getNamespace().equals(namespace)) return i; } return -1; }
java
public int namespaceIndex(String namespace, Vector extensions) { for (int i = 0; i < extensions.size(); i++) { if (((ExtensionNamespaceSupport)extensions.get(i)).getNamespace().equals(namespace)) return i; } return -1; }
[ "public", "int", "namespaceIndex", "(", "String", "namespace", ",", "Vector", "extensions", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "extensions", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "(", "(", "ExtensionNam...
Get the index for a namespace entry in the extension namespace Vector, -1 if no such entry yet exists.
[ "Get", "the", "index", "for", "a", "namespace", "entry", "in", "the", "extension", "namespace", "Vector", "-", "1", "if", "no", "such", "entry", "yet", "exists", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/extensions/ExtensionNamespacesManager.java#L103-L111
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/util/RequestUtil.java
RequestUtil.putMapEntry
private static void putMapEntry( final Map<String, String[]> map, final String name, final String value ) { String[] newValues = null; final String[] oldValues = map.get( name ); if ( oldValues == null ) { newValues = new String[1]; newValues[0] = value; } else { newValues = new String[oldValues.length + 1]; System.arraycopy( oldValues, 0, newValues, 0, oldValues.length ); newValues[oldValues.length] = value; } map.put( name, newValues ); }
java
private static void putMapEntry( final Map<String, String[]> map, final String name, final String value ) { String[] newValues = null; final String[] oldValues = map.get( name ); if ( oldValues == null ) { newValues = new String[1]; newValues[0] = value; } else { newValues = new String[oldValues.length + 1]; System.arraycopy( oldValues, 0, newValues, 0, oldValues.length ); newValues[oldValues.length] = value; } map.put( name, newValues ); }
[ "private", "static", "void", "putMapEntry", "(", "final", "Map", "<", "String", ",", "String", "[", "]", ">", "map", ",", "final", "String", "name", ",", "final", "String", "value", ")", "{", "String", "[", "]", "newValues", "=", "null", ";", "final", ...
Put name and value pair in map. When name already exist, add value to array of values. @param map The map to populate @param name The parameter name @param value The parameter value
[ "Put", "name", "and", "value", "pair", "in", "map", ".", "When", "name", "already", "exist", "add", "value", "to", "array", "of", "values", "." ]
train
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/util/RequestUtil.java#L672-L688
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/system/SystemProperties.java
SystemProperties.setPropertyValue
@Nonnull public static EChange setPropertyValue (@Nonnull final String sKey, final boolean bValue) { return setPropertyValue (sKey, Boolean.toString (bValue)); }
java
@Nonnull public static EChange setPropertyValue (@Nonnull final String sKey, final boolean bValue) { return setPropertyValue (sKey, Boolean.toString (bValue)); }
[ "@", "Nonnull", "public", "static", "EChange", "setPropertyValue", "(", "@", "Nonnull", "final", "String", "sKey", ",", "final", "boolean", "bValue", ")", "{", "return", "setPropertyValue", "(", "sKey", ",", "Boolean", ".", "toString", "(", "bValue", ")", ")...
Set a system property value under consideration of an eventually present {@link SecurityManager}. @param sKey The key of the system property. May not be <code>null</code>. @param bValue The value of the system property. @return {@link EChange}
[ "Set", "a", "system", "property", "value", "under", "consideration", "of", "an", "eventually", "present", "{", "@link", "SecurityManager", "}", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/system/SystemProperties.java#L145-L149
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.createBranch
public void createBranch(Serializable projectId, String branchName, String ref) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBranch.URL; dispatch().with("branch", branchName).with("ref", ref).to(tailUrl, Void.class); }
java
public void createBranch(Serializable projectId, String branchName, String ref) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBranch.URL; dispatch().with("branch", branchName).with("ref", ref).to(tailUrl, Void.class); }
[ "public", "void", "createBranch", "(", "Serializable", "projectId", ",", "String", "branchName", ",", "String", "ref", ")", "throws", "IOException", "{", "String", "tailUrl", "=", "GitlabProject", ".", "URL", "+", "\"/\"", "+", "sanitizeProjectId", "(", "project...
Create Branch. <a href="http://doc.gitlab.com/ce/api/branches.html#create-repository-branch"> Create Repository Branch Documentation </a> @param projectId The id of the project @param branchName The name of the branch to create @param ref The branch name or commit SHA to create branch from @throws IOException on gitlab api call error
[ "Create", "Branch", ".", "<a", "href", "=", "http", ":", "//", "doc", ".", "gitlab", ".", "com", "/", "ce", "/", "api", "/", "branches", ".", "html#create", "-", "repository", "-", "branch", ">", "Create", "Repository", "Branch", "Documentation", "<", ...
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2333-L2336
roboconf/roboconf-platform
core/roboconf-plugin-script/src/main/java/net/roboconf/plugin/script/internal/templating/InstanceTemplateHelper.java
InstanceTemplateHelper.injectInstanceImports
public static void injectInstanceImports(Instance instance, File templateFile, File out) throws IOException { injectInstanceImports( instance, templateFile.getAbsolutePath(), out ); }
java
public static void injectInstanceImports(Instance instance, File templateFile, File out) throws IOException { injectInstanceImports( instance, templateFile.getAbsolutePath(), out ); }
[ "public", "static", "void", "injectInstanceImports", "(", "Instance", "instance", ",", "File", "templateFile", ",", "File", "out", ")", "throws", "IOException", "{", "injectInstanceImports", "(", "instance", ",", "templateFile", ".", "getAbsolutePath", "(", ")", "...
Reads the import values of the instances and injects them into the template file. <p> See test resources to see the associated way to write templates </p> @param instance the instance whose imports must be injected @param templateFile the template file @param out the file to write into @throws IOException if something went wrong
[ "Reads", "the", "import", "values", "of", "the", "instances", "and", "injects", "them", "into", "the", "template", "file", ".", "<p", ">", "See", "test", "resources", "to", "see", "the", "associated", "way", "to", "write", "templates", "<", "/", "p", ">"...
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-plugin-script/src/main/java/net/roboconf/plugin/script/internal/templating/InstanceTemplateHelper.java#L131-L134
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/util/MathUtils.java
MathUtils.rootMeansSquaredError
public static double rootMeansSquaredError(double[] real, double[] predicted) { double ret = 0.0; for (int i = 0; i < real.length; i++) { ret += Math.pow((real[i] - predicted[i]), 2); } return Math.sqrt(ret / real.length); }
java
public static double rootMeansSquaredError(double[] real, double[] predicted) { double ret = 0.0; for (int i = 0; i < real.length; i++) { ret += Math.pow((real[i] - predicted[i]), 2); } return Math.sqrt(ret / real.length); }
[ "public", "static", "double", "rootMeansSquaredError", "(", "double", "[", "]", "real", ",", "double", "[", "]", "predicted", ")", "{", "double", "ret", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "real", ".", "length", ";", "...
This returns the root mean squared error of two data sets @param real the real values @param predicted the predicted values @return the root means squared error for two data sets
[ "This", "returns", "the", "root", "mean", "squared", "error", "of", "two", "data", "sets" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/util/MathUtils.java#L728-L734
UrielCh/ovh-java-sdk
ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java
ApiOvhEmailexchange.organizationName_service_exchangeService_updateFlagsOnAllAccounts_POST
public void organizationName_service_exchangeService_updateFlagsOnAllAccounts_POST(String organizationName, String exchangeService) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/updateFlagsOnAllAccounts"; StringBuilder sb = path(qPath, organizationName, exchangeService); exec(qPath, "POST", sb.toString(), null); }
java
public void organizationName_service_exchangeService_updateFlagsOnAllAccounts_POST(String organizationName, String exchangeService) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/updateFlagsOnAllAccounts"; StringBuilder sb = path(qPath, organizationName, exchangeService); exec(qPath, "POST", sb.toString(), null); }
[ "public", "void", "organizationName_service_exchangeService_updateFlagsOnAllAccounts_POST", "(", "String", "organizationName", ",", "String", "exchangeService", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/exchange/{organizationName}/service/{exchangeService}/...
Update spam and virus flags on all active accounts REST: POST /email/exchange/{organizationName}/service/{exchangeService}/updateFlagsOnAllAccounts @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service
[ "Update", "spam", "and", "virus", "flags", "on", "all", "active", "accounts" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L294-L298
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/FreesoundClient.java
FreesoundClient.buildAuthorisationCredential
private String buildAuthorisationCredential(final Query<?, ?> query) { String credential = null; if (query instanceof OAuthQuery) { final String oauthToken = ((OAuthQuery) query).getOauthToken(); credential = String.format("Bearer %s", oauthToken); } else if (query instanceof AccessTokenQuery) { // Don't set the Authorization header } else { credential = String.format("Token %s", clientSecret); } return credential; }
java
private String buildAuthorisationCredential(final Query<?, ?> query) { String credential = null; if (query instanceof OAuthQuery) { final String oauthToken = ((OAuthQuery) query).getOauthToken(); credential = String.format("Bearer %s", oauthToken); } else if (query instanceof AccessTokenQuery) { // Don't set the Authorization header } else { credential = String.format("Token %s", clientSecret); } return credential; }
[ "private", "String", "buildAuthorisationCredential", "(", "final", "Query", "<", "?", ",", "?", ">", "query", ")", "{", "String", "credential", "=", "null", ";", "if", "(", "query", "instanceof", "OAuthQuery", ")", "{", "final", "String", "oauthToken", "=", ...
Build the credential that will be passed in the 'Authorization' HTTP header as part of the API call. The nature of the credential will depend on the query being made. @param query The query being made @return The string to pass in the Authorization header (or null if none)
[ "Build", "the", "credential", "that", "will", "be", "passed", "in", "the", "Authorization", "HTTP", "header", "as", "part", "of", "the", "API", "call", ".", "The", "nature", "of", "the", "credential", "will", "depend", "on", "the", "query", "being", "made"...
train
https://github.com/Sonoport/freesound-java/blob/ab029e25de068c6f8cc028bc7f916938fd97c036/src/main/java/com/sonoport/freesound/FreesoundClient.java#L189-L201
code4everything/util
src/main/java/com/zhazhapan/util/FileExecutor.java
FileExecutor.read
public static String read(InputStream is, int off, int len) throws IOException { byte[] bs = new byte[len]; is.read(bs, off, len); return new String(bs); }
java
public static String read(InputStream is, int off, int len) throws IOException { byte[] bs = new byte[len]; is.read(bs, off, len); return new String(bs); }
[ "public", "static", "String", "read", "(", "InputStream", "is", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "byte", "[", "]", "bs", "=", "new", "byte", "[", "len", "]", ";", "is", ".", "read", "(", "bs", ",", "off", "...
读取输入流,需手动关闭流 @param is 输入流 @param off 偏移 @param len 长度 @return 内容 @throws IOException 异常
[ "读取输入流,需手动关闭流" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/FileExecutor.java#L355-L359
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/support/TimerSupport.java
TimerSupport.register
public void register(int interval, @NonNull OnTickListener onTickListener, boolean intermediate) { mDefaultTimer.register(interval, onTickListener, intermediate); }
java
public void register(int interval, @NonNull OnTickListener onTickListener, boolean intermediate) { mDefaultTimer.register(interval, onTickListener, intermediate); }
[ "public", "void", "register", "(", "int", "interval", ",", "@", "NonNull", "OnTickListener", "onTickListener", ",", "boolean", "intermediate", ")", "{", "mDefaultTimer", ".", "register", "(", "interval", ",", "onTickListener", ",", "intermediate", ")", ";", "}" ...
onTickListener will store as weak reference, don't use anonymous class here @param interval how many seconds of interval that the listener will be called in @param onTickListener listener @param intermediate whether execute onTick intermediately
[ "onTickListener", "will", "store", "as", "weak", "reference", "don", "t", "use", "anonymous", "class", "here" ]
train
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/support/TimerSupport.java#L66-L68
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/br/br_configuresyslog.java
br_configuresyslog.configuresyslog
public static br_configuresyslog configuresyslog(nitro_service client, br_configuresyslog resource) throws Exception { return ((br_configuresyslog[]) resource.perform_operation(client, "configuresyslog"))[0]; }
java
public static br_configuresyslog configuresyslog(nitro_service client, br_configuresyslog resource) throws Exception { return ((br_configuresyslog[]) resource.perform_operation(client, "configuresyslog"))[0]; }
[ "public", "static", "br_configuresyslog", "configuresyslog", "(", "nitro_service", "client", ",", "br_configuresyslog", "resource", ")", "throws", "Exception", "{", "return", "(", "(", "br_configuresyslog", "[", "]", ")", "resource", ".", "perform_operation", "(", "...
<pre> Use this operation to configure Syslog Server settings on Repeater Instances. </pre>
[ "<pre", ">", "Use", "this", "operation", "to", "configure", "Syslog", "Server", "settings", "on", "Repeater", "Instances", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/br/br_configuresyslog.java#L126-L129
VoltDB/voltdb
src/frontend/org/voltcore/messaging/HostMessenger.java
HostMessenger.generateMailboxId
public long generateMailboxId(Long mailboxId) { final long hsId = mailboxId == null ? getHSIdForLocalSite(m_nextSiteId.getAndIncrement()) : mailboxId; addMailbox(hsId, new Mailbox() { @Override public void send(long hsId, VoltMessage message) { } @Override public void send(long[] hsIds, VoltMessage message) { } @Override public void deliver(VoltMessage message) { networkLog.info("No-op mailbox(" + CoreUtils.hsIdToString(hsId) + ") dropped message " + message); } @Override public void deliverFront(VoltMessage message) { } @Override public VoltMessage recv() { return null; } @Override public VoltMessage recvBlocking() { return null; } @Override public VoltMessage recvBlocking(long timeout) { return null; } @Override public VoltMessage recv(Subject[] s) { return null; } @Override public VoltMessage recvBlocking(Subject[] s) { return null; } @Override public VoltMessage recvBlocking(Subject[] s, long timeout) { return null; } @Override public long getHSId() { return 0L; } @Override public void setHSId(long hsId) { } }); return hsId; }
java
public long generateMailboxId(Long mailboxId) { final long hsId = mailboxId == null ? getHSIdForLocalSite(m_nextSiteId.getAndIncrement()) : mailboxId; addMailbox(hsId, new Mailbox() { @Override public void send(long hsId, VoltMessage message) { } @Override public void send(long[] hsIds, VoltMessage message) { } @Override public void deliver(VoltMessage message) { networkLog.info("No-op mailbox(" + CoreUtils.hsIdToString(hsId) + ") dropped message " + message); } @Override public void deliverFront(VoltMessage message) { } @Override public VoltMessage recv() { return null; } @Override public VoltMessage recvBlocking() { return null; } @Override public VoltMessage recvBlocking(long timeout) { return null; } @Override public VoltMessage recv(Subject[] s) { return null; } @Override public VoltMessage recvBlocking(Subject[] s) { return null; } @Override public VoltMessage recvBlocking(Subject[] s, long timeout) { return null; } @Override public long getHSId() { return 0L; } @Override public void setHSId(long hsId) { } }); return hsId; }
[ "public", "long", "generateMailboxId", "(", "Long", "mailboxId", ")", "{", "final", "long", "hsId", "=", "mailboxId", "==", "null", "?", "getHSIdForLocalSite", "(", "m_nextSiteId", ".", "getAndIncrement", "(", ")", ")", ":", "mailboxId", ";", "addMailbox", "("...
/* Generate a slot for the mailbox and put a noop box there. Can also supply a value
[ "/", "*", "Generate", "a", "slot", "for", "the", "mailbox", "and", "put", "a", "noop", "box", "there", ".", "Can", "also", "supply", "a", "value" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/messaging/HostMessenger.java#L1494-L1555
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/index/preprocessed/fastoptics/RandomProjectedNeighborsAndDensities.java
RandomProjectedNeighborsAndDensities.splitRandomly
public int splitRandomly(ArrayModifiableDBIDs ind, int begin, int end, DoubleDataStore tpro, Random rand) { final int nele = end - begin; DBIDArrayIter it = ind.iter(); // pick random splitting element based on position double rs = tpro.doubleValue(it.seek(begin + rand.nextInt(nele))); int minInd = begin, maxInd = end - 1; // permute elements such that all points smaller than the splitting // element are on the right and the others on the left in the array while(minInd < maxInd) { double currEle = tpro.doubleValue(it.seek(minInd)); if(currEle > rs) { while(minInd < maxInd && tpro.doubleValue(it.seek(maxInd)) > rs) { maxInd--; } if(minInd == maxInd) { break; } ind.swap(minInd, maxInd); maxInd--; } minInd++; } // if all elements are the same split in the middle if(minInd == end - 1) { minInd = (begin + end) >>> 1; } return minInd; }
java
public int splitRandomly(ArrayModifiableDBIDs ind, int begin, int end, DoubleDataStore tpro, Random rand) { final int nele = end - begin; DBIDArrayIter it = ind.iter(); // pick random splitting element based on position double rs = tpro.doubleValue(it.seek(begin + rand.nextInt(nele))); int minInd = begin, maxInd = end - 1; // permute elements such that all points smaller than the splitting // element are on the right and the others on the left in the array while(minInd < maxInd) { double currEle = tpro.doubleValue(it.seek(minInd)); if(currEle > rs) { while(minInd < maxInd && tpro.doubleValue(it.seek(maxInd)) > rs) { maxInd--; } if(minInd == maxInd) { break; } ind.swap(minInd, maxInd); maxInd--; } minInd++; } // if all elements are the same split in the middle if(minInd == end - 1) { minInd = (begin + end) >>> 1; } return minInd; }
[ "public", "int", "splitRandomly", "(", "ArrayModifiableDBIDs", "ind", ",", "int", "begin", ",", "int", "end", ",", "DoubleDataStore", "tpro", ",", "Random", "rand", ")", "{", "final", "int", "nele", "=", "end", "-", "begin", ";", "DBIDArrayIter", "it", "="...
Split the data set randomly. @param ind Object index @param begin Interval begin @param end Interval end @param tpro Projection @param rand Random generator @return Splitting point
[ "Split", "the", "data", "set", "randomly", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/index/preprocessed/fastoptics/RandomProjectedNeighborsAndDensities.java#L288-L315
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java
CommonOps_DDF2.elementDiv
public static void elementDiv( DMatrix2x2 a , DMatrix2x2 b) { a.a11 /= b.a11; a.a12 /= b.a12; a.a21 /= b.a21; a.a22 /= b.a22; }
java
public static void elementDiv( DMatrix2x2 a , DMatrix2x2 b) { a.a11 /= b.a11; a.a12 /= b.a12; a.a21 /= b.a21; a.a22 /= b.a22; }
[ "public", "static", "void", "elementDiv", "(", "DMatrix2x2", "a", ",", "DMatrix2x2", "b", ")", "{", "a", ".", "a11", "/=", "b", ".", "a11", ";", "a", ".", "a12", "/=", "b", ".", "a12", ";", "a", ".", "a21", "/=", "b", ".", "a21", ";", "a", "....
<p>Performs an element by element division operation:<br> <br> a<sub>ij</sub> = a<sub>ij</sub> / b<sub>ij</sub> <br> </p> @param a The left matrix in the division operation. Modified. @param b The right matrix in the division operation. Not modified.
[ "<p", ">", "Performs", "an", "element", "by", "element", "division", "operation", ":", "<br", ">", "<br", ">", "a<sub", ">", "ij<", "/", "sub", ">", "=", "a<sub", ">", "ij<", "/", "sub", ">", "/", "b<sub", ">", "ij<", "/", "sub", ">", "<br", ">",...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java#L920-L923
carewebframework/carewebframework-core
org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/util/TreeUtil.java
TreeUtil.findNode
public static Treenode findNode(Treeview tree, String path, boolean create, MatchMode matchMode) { return findNode(tree, path, create, Treenode.class, matchMode); }
java
public static Treenode findNode(Treeview tree, String path, boolean create, MatchMode matchMode) { return findNode(tree, path, create, Treenode.class, matchMode); }
[ "public", "static", "Treenode", "findNode", "(", "Treeview", "tree", ",", "String", "path", ",", "boolean", "create", ",", "MatchMode", "matchMode", ")", "{", "return", "findNode", "(", "tree", ",", "path", ",", "create", ",", "Treenode", ".", "class", ","...
Returns the tree item associated with the specified \-delimited path. @param tree Tree to search. @param path \-delimited path to search. @param create If true, tree nodes are created if they do not already exist. @param matchMode The match mode. @return The tree item corresponding to the specified path, or null if not found.
[ "Returns", "the", "tree", "item", "associated", "with", "the", "specified", "\\", "-", "delimited", "path", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/util/TreeUtil.java#L120-L122
b3dgs/lionengine
lionengine-audio-wav/src/main/java/com/b3dgs/lionengine/audio/wav/WavImpl.java
WavImpl.updateVolume
private static void updateVolume(DataLine dataLine, int volume) { if (dataLine.isControlSupported(Type.MASTER_GAIN)) { final FloatControl gainControl = (FloatControl) dataLine.getControl(Type.MASTER_GAIN); final double gain = UtilMath.clamp(volume / 100.0, 0.0, 100.0); final double dB = Math.log(gain) / Math.log(10.0) * 20.0; gainControl.setValue((float) dB); } }
java
private static void updateVolume(DataLine dataLine, int volume) { if (dataLine.isControlSupported(Type.MASTER_GAIN)) { final FloatControl gainControl = (FloatControl) dataLine.getControl(Type.MASTER_GAIN); final double gain = UtilMath.clamp(volume / 100.0, 0.0, 100.0); final double dB = Math.log(gain) / Math.log(10.0) * 20.0; gainControl.setValue((float) dB); } }
[ "private", "static", "void", "updateVolume", "(", "DataLine", "dataLine", ",", "int", "volume", ")", "{", "if", "(", "dataLine", ".", "isControlSupported", "(", "Type", ".", "MASTER_GAIN", ")", ")", "{", "final", "FloatControl", "gainControl", "=", "(", "Flo...
Update the sound volume. @param dataLine Audio source data. @param volume The audio playback volume value.
[ "Update", "the", "sound", "volume", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-audio-wav/src/main/java/com/b3dgs/lionengine/audio/wav/WavImpl.java#L159-L168
nextreports/nextreports-engine
src/ro/nextreports/engine/util/ParameterUtil.java
ParameterUtil.getUsedNotHiddenParametersMap
public static Map<String, QueryParameter> getUsedNotHiddenParametersMap(Report report) { return getUsedParametersMap(report, false, false); }
java
public static Map<String, QueryParameter> getUsedNotHiddenParametersMap(Report report) { return getUsedParametersMap(report, false, false); }
[ "public", "static", "Map", "<", "String", ",", "QueryParameter", ">", "getUsedNotHiddenParametersMap", "(", "Report", "report", ")", "{", "return", "getUsedParametersMap", "(", "report", ",", "false", ",", "false", ")", ";", "}" ]
Get used parameters map where the key is the parameter name and the value is the parameter Not all the report parameters have to be used, some may only be defined for further usage. The result will not contain the hidden parameters. @param report next report object @return used not-hidden parameters map
[ "Get", "used", "parameters", "map", "where", "the", "key", "is", "the", "parameter", "name", "and", "the", "value", "is", "the", "parameter", "Not", "all", "the", "report", "parameters", "have", "to", "be", "used", "some", "may", "only", "be", "defined", ...
train
https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/util/ParameterUtil.java#L655-L657
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/mult/VectorVectorMult_DDRM.java
VectorVectorMult_DDRM.innerProdA
public static double innerProdA(DMatrixD1 x, DMatrixD1 A , DMatrixD1 y ) { int n = A.numRows; int m = A.numCols; if( x.getNumElements() != n ) throw new IllegalArgumentException("Unexpected number of elements in x"); if( y.getNumElements() != m ) throw new IllegalArgumentException("Unexpected number of elements in y"); double result = 0; for( int i = 0; i < m; i++ ) { double total = 0; for( int j = 0; j < n; j++ ) { total += x.get(j)*A.unsafe_get(j,i); } result += total*y.get(i); } return result; }
java
public static double innerProdA(DMatrixD1 x, DMatrixD1 A , DMatrixD1 y ) { int n = A.numRows; int m = A.numCols; if( x.getNumElements() != n ) throw new IllegalArgumentException("Unexpected number of elements in x"); if( y.getNumElements() != m ) throw new IllegalArgumentException("Unexpected number of elements in y"); double result = 0; for( int i = 0; i < m; i++ ) { double total = 0; for( int j = 0; j < n; j++ ) { total += x.get(j)*A.unsafe_get(j,i); } result += total*y.get(i); } return result; }
[ "public", "static", "double", "innerProdA", "(", "DMatrixD1", "x", ",", "DMatrixD1", "A", ",", "DMatrixD1", "y", ")", "{", "int", "n", "=", "A", ".", "numRows", ";", "int", "m", "=", "A", ".", "numCols", ";", "if", "(", "x", ".", "getNumElements", ...
<p> return = x<sup>T</sup>*A*y </p> @param x A vector with n elements. Not modified. @param A A matrix with n by m elements. Not modified. @param y A vector with m elements. Not modified. @return The results.
[ "<p", ">", "return", "=", "x<sup", ">", "T<", "/", "sup", ">", "*", "A", "*", "y", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/mult/VectorVectorMult_DDRM.java#L72-L95
powermock/powermock
powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java
Whitebox.getInternalState
public static <T> T getInternalState(Object object, Class<T> fieldType) { return WhiteboxImpl.getInternalState(object, fieldType); }
java
public static <T> T getInternalState(Object object, Class<T> fieldType) { return WhiteboxImpl.getInternalState(object, fieldType); }
[ "public", "static", "<", "T", ">", "T", "getInternalState", "(", "Object", "object", ",", "Class", "<", "T", ">", "fieldType", ")", "{", "return", "WhiteboxImpl", ".", "getInternalState", "(", "object", ",", "fieldType", ")", ";", "}" ]
Get the value of a field using reflection based on the fields type. This method will traverse the super class hierarchy until the first field of type <tt>fieldType</tt> is found. The value of this field will be returned. @param object the object to modify @param fieldType the type of the field
[ "Get", "the", "value", "of", "a", "field", "using", "reflection", "based", "on", "the", "fields", "type", ".", "This", "method", "will", "traverse", "the", "super", "class", "hierarchy", "until", "the", "first", "field", "of", "type", "<tt", ">", "fieldTyp...
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java#L346-L349
eurekaclinical/protempa
protempa-framework/src/main/java/org/protempa/proposition/PropositionUtil.java
PropositionUtil.binarySearch
public static PrimitiveParameter binarySearch( List<PrimitiveParameter> params, long timestamp) { /* * The conditions for using index versus iterator are grabbed from the * JDK source code. */ if (params.size() < 5000 || params instanceof RandomAccess) { return indexedBinarySearch(params, timestamp); } else { return iteratorBinarySearch(params, timestamp); } }
java
public static PrimitiveParameter binarySearch( List<PrimitiveParameter> params, long timestamp) { /* * The conditions for using index versus iterator are grabbed from the * JDK source code. */ if (params.size() < 5000 || params instanceof RandomAccess) { return indexedBinarySearch(params, timestamp); } else { return iteratorBinarySearch(params, timestamp); } }
[ "public", "static", "PrimitiveParameter", "binarySearch", "(", "List", "<", "PrimitiveParameter", ">", "params", ",", "long", "timestamp", ")", "{", "/*\n * The conditions for using index versus iterator are grabbed from the\n * JDK source code.\n */", "if", ...
Binary search for a primitive parameter by timestamp. @param list a <code>List</code> of <code>PrimitiveParameter</code> objects all with the same paramId, cannot be <code>null</code>. @param tstamp the timestamp we're interested in finding. @return a <code>PrimitiveParameter</code>, or null if not found.
[ "Binary", "search", "for", "a", "primitive", "parameter", "by", "timestamp", "." ]
train
https://github.com/eurekaclinical/protempa/blob/5a620d1a407c7a5426d1cf17d47b97717cf71634/protempa-framework/src/main/java/org/protempa/proposition/PropositionUtil.java#L440-L451
alkacon/opencms-core
src/org/opencms/ui/dialogs/history/diff/CmsValueDiff.java
CmsValueDiff.buildWholeFileDiffView
private Component buildWholeFileDiffView(CmsObject cms, CmsFile file1, CmsFile file2) { String encoding = "UTF-8"; try { CmsXmlContent content1 = CmsXmlContentFactory.unmarshal(cms, file1); encoding = content1.getEncoding(); } catch (CmsException e) { String rootPath = file1.getRootPath(); LOG.error( "Could not unmarshal file " + rootPath + " for determining encoding: " + e.getLocalizedMessage(), e); } String text1 = decode(file1.getContents(), encoding); String text2 = decode(file2.getContents(), encoding); CmsTextDiffPanel diffPanel = new CmsTextDiffPanel(text1, text2, false, true); return diffPanel; }
java
private Component buildWholeFileDiffView(CmsObject cms, CmsFile file1, CmsFile file2) { String encoding = "UTF-8"; try { CmsXmlContent content1 = CmsXmlContentFactory.unmarshal(cms, file1); encoding = content1.getEncoding(); } catch (CmsException e) { String rootPath = file1.getRootPath(); LOG.error( "Could not unmarshal file " + rootPath + " for determining encoding: " + e.getLocalizedMessage(), e); } String text1 = decode(file1.getContents(), encoding); String text2 = decode(file2.getContents(), encoding); CmsTextDiffPanel diffPanel = new CmsTextDiffPanel(text1, text2, false, true); return diffPanel; }
[ "private", "Component", "buildWholeFileDiffView", "(", "CmsObject", "cms", ",", "CmsFile", "file1", ",", "CmsFile", "file2", ")", "{", "String", "encoding", "=", "\"UTF-8\"", ";", "try", "{", "CmsXmlContent", "content1", "=", "CmsXmlContentFactory", ".", "unmarsha...
Builds the diff view for the XML text.<p> @param cms the CMS context @param file1 the first file @param file2 the second file @return the diff view
[ "Builds", "the", "diff", "view", "for", "the", "XML", "text", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/history/diff/CmsValueDiff.java#L196-L213
respoke/respoke-sdk-android
respokeSDK/src/main/java/com/digium/respokesdk/RespokeClient.java
RespokeClient.postConnectError
private void postConnectError(final ConnectCompletionListener completionListener, final String errorMessage) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (null != completionListener) { completionListener.onError(errorMessage); } } }); }
java
private void postConnectError(final ConnectCompletionListener completionListener, final String errorMessage) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (null != completionListener) { completionListener.onError(errorMessage); } } }); }
[ "private", "void", "postConnectError", "(", "final", "ConnectCompletionListener", "completionListener", ",", "final", "String", "errorMessage", ")", "{", "new", "Handler", "(", "Looper", ".", "getMainLooper", "(", ")", ")", ".", "post", "(", "new", "Runnable", "...
A convenience method for posting errors to a ConnectCompletionListener @param completionListener The listener to notify @param errorMessage The human-readable error message that occurred
[ "A", "convenience", "method", "for", "posting", "errors", "to", "a", "ConnectCompletionListener" ]
train
https://github.com/respoke/respoke-sdk-android/blob/34a15f0558d29b1f1bc8481bbc5c505e855e05ef/respokeSDK/src/main/java/com/digium/respokesdk/RespokeClient.java#L1072-L1081
hageldave/ImagingKit
ImagingKit_Core/src/main/java/hageldave/imagingkit/core/util/ImagePanel.java
ImagePanel.checkerStrokeForSize
protected static final Stroke checkerStrokeForSize(int size) { return new BasicStroke(size, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL, 1, new float[]{0,size*2}, 0); }
java
protected static final Stroke checkerStrokeForSize(int size) { return new BasicStroke(size, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL, 1, new float[]{0,size*2}, 0); }
[ "protected", "static", "final", "Stroke", "checkerStrokeForSize", "(", "int", "size", ")", "{", "return", "new", "BasicStroke", "(", "size", ",", "BasicStroke", ".", "CAP_SQUARE", ",", "BasicStroke", ".", "JOIN_BEVEL", ",", "1", ",", "new", "float", "[", "]"...
Creates a stroke for a checkerboard pattern with specified size. <br> This is used by {@link #setCheckerSize(int)} @param size width of the stroke @return the stroke @since 1.4
[ "Creates", "a", "stroke", "for", "a", "checkerboard", "pattern", "with", "specified", "size", ".", "<br", ">", "This", "is", "used", "by", "{" ]
train
https://github.com/hageldave/ImagingKit/blob/3837c7d550a12cf4dc5718b644ced94b97f52668/ImagingKit_Core/src/main/java/hageldave/imagingkit/core/util/ImagePanel.java#L330-L332
js-lib-com/commons
src/main/java/js/util/Classes.java
Classes.newInstance
@SuppressWarnings("unchecked") public static <T> T newInstance(String className, Object... arguments) { return (T)newInstance(Classes.forName(className), arguments); }
java
@SuppressWarnings("unchecked") public static <T> T newInstance(String className, Object... arguments) { return (T)newInstance(Classes.forName(className), arguments); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "newInstance", "(", "String", "className", ",", "Object", "...", "arguments", ")", "{", "return", "(", "T", ")", "newInstance", "(", "Classes", ".", "forName", "(",...
Create a new instance. Handy utility for hidden classes creation. Constructor accepting given arguments, if any, must exists. @param className fully qualified class name, @param arguments variable number of arguments to be passed to constructor. @param <T> instance type. @return newly created instance. @throws NoSuchBeingException if class or constructor not found.
[ "Create", "a", "new", "instance", ".", "Handy", "utility", "for", "hidden", "classes", "creation", ".", "Constructor", "accepting", "given", "arguments", "if", "any", "must", "exists", "." ]
train
https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Classes.java#L1317-L1321
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/Request.java
Request.executeMyFriendsRequestAsync
@Deprecated public static RequestAsyncTask executeMyFriendsRequestAsync(Session session, GraphUserListCallback callback) { return newMyFriendsRequest(session, callback).executeAsync(); }
java
@Deprecated public static RequestAsyncTask executeMyFriendsRequestAsync(Session session, GraphUserListCallback callback) { return newMyFriendsRequest(session, callback).executeAsync(); }
[ "@", "Deprecated", "public", "static", "RequestAsyncTask", "executeMyFriendsRequestAsync", "(", "Session", "session", ",", "GraphUserListCallback", "callback", ")", "{", "return", "newMyFriendsRequest", "(", "session", ",", "callback", ")", ".", "executeAsync", "(", "...
Starts a new Request configured to retrieve a user's friend list. <p/> This should only be called from the UI thread. This method is deprecated. Prefer to call Request.newMyFriendsRequest(...).executeAsync(); @param session the Session to use, or null; if non-null, the session must be in an opened state @param callback a callback that will be called when the request is completed to handle success or error conditions @return a RequestAsyncTask that is executing the request
[ "Starts", "a", "new", "Request", "configured", "to", "retrieve", "a", "user", "s", "friend", "list", ".", "<p", "/", ">", "This", "should", "only", "be", "called", "from", "the", "UI", "thread", "." ]
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L1133-L1136
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/shapes/edge/EdgeIntensityPolygon.java
EdgeIntensityPolygon.computeEdge
public boolean computeEdge(Polygon2D_F64 polygon , boolean ccw ) { averageInside = 0; averageOutside = 0; double tangentSign = ccw ? 1 : -1; int totalSides = 0; for (int i = polygon.size()-1,j=0; j < polygon.size(); i=j,j++) { Point2D_F64 a = polygon.get(i); Point2D_F64 b = polygon.get(j); double dx = b.x-a.x; double dy = b.y-a.y; double t = Math.sqrt(dx*dx + dy*dy); dx /= t; dy /= t; // see if the side is too small if( t < 3*cornerOffset ) { offsetA.set(a); offsetB.set(b); } else { offsetA.x = a.x + cornerOffset * dx; offsetA.y = a.y + cornerOffset * dy; offsetB.x = b.x - cornerOffset * dx; offsetB.y = b.y - cornerOffset * dy; } double tanX = -dy*tangentDistance*tangentSign; double tanY = dx*tangentDistance*tangentSign; scorer.computeAverageDerivative(offsetA, offsetB, tanX,tanY); if( scorer.getSamplesInside() > 0 ) { totalSides++; averageInside += scorer.getAverageUp() / tangentDistance; averageOutside += scorer.getAverageDown() / tangentDistance; } } if( totalSides > 0 ) { averageInside /= totalSides; averageOutside /= totalSides; } else { averageInside = averageOutside = 0; return false; } return true; }
java
public boolean computeEdge(Polygon2D_F64 polygon , boolean ccw ) { averageInside = 0; averageOutside = 0; double tangentSign = ccw ? 1 : -1; int totalSides = 0; for (int i = polygon.size()-1,j=0; j < polygon.size(); i=j,j++) { Point2D_F64 a = polygon.get(i); Point2D_F64 b = polygon.get(j); double dx = b.x-a.x; double dy = b.y-a.y; double t = Math.sqrt(dx*dx + dy*dy); dx /= t; dy /= t; // see if the side is too small if( t < 3*cornerOffset ) { offsetA.set(a); offsetB.set(b); } else { offsetA.x = a.x + cornerOffset * dx; offsetA.y = a.y + cornerOffset * dy; offsetB.x = b.x - cornerOffset * dx; offsetB.y = b.y - cornerOffset * dy; } double tanX = -dy*tangentDistance*tangentSign; double tanY = dx*tangentDistance*tangentSign; scorer.computeAverageDerivative(offsetA, offsetB, tanX,tanY); if( scorer.getSamplesInside() > 0 ) { totalSides++; averageInside += scorer.getAverageUp() / tangentDistance; averageOutside += scorer.getAverageDown() / tangentDistance; } } if( totalSides > 0 ) { averageInside /= totalSides; averageOutside /= totalSides; } else { averageInside = averageOutside = 0; return false; } return true; }
[ "public", "boolean", "computeEdge", "(", "Polygon2D_F64", "polygon", ",", "boolean", "ccw", ")", "{", "averageInside", "=", "0", ";", "averageOutside", "=", "0", ";", "double", "tangentSign", "=", "ccw", "?", "1", ":", "-", "1", ";", "int", "totalSides", ...
Checks to see if its a valid polygon or a false positive by looking at edge intensity @param polygon The polygon being tested @param ccw True if the polygon is counter clockwise @return true if it could compute the edge intensity, otherwise false
[ "Checks", "to", "see", "if", "its", "a", "valid", "polygon", "or", "a", "false", "positive", "by", "looking", "at", "edge", "intensity" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/edge/EdgeIntensityPolygon.java#L95-L146
gallandarakhneorg/afc
core/maths/mathgen/src/main/java/org/arakhne/afc/math/MathUtil.java
MathUtil.isEpsilonEqual
@Pure @Inline(value = "MathUtil.isEpsilonEqual($1, $2, Double.NaN)", imported = {MathUtil.class}) public static boolean isEpsilonEqual(double v1, double v2) { return isEpsilonEqual(v1, v2, Double.NaN); }
java
@Pure @Inline(value = "MathUtil.isEpsilonEqual($1, $2, Double.NaN)", imported = {MathUtil.class}) public static boolean isEpsilonEqual(double v1, double v2) { return isEpsilonEqual(v1, v2, Double.NaN); }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"MathUtil.isEpsilonEqual($1, $2, Double.NaN)\"", ",", "imported", "=", "{", "MathUtil", ".", "class", "}", ")", "public", "static", "boolean", "isEpsilonEqual", "(", "double", "v1", ",", "double", "v2", ")", "{"...
Replies if the given values are near. @param v1 first value. @param v2 second value. @return <code>true</code> if the given {@code v1} is near {@code v2}, otherwise <code>false</code>. @see Math#ulp(double)
[ "Replies", "if", "the", "given", "values", "are", "near", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgen/src/main/java/org/arakhne/afc/math/MathUtil.java#L151-L155
facebookarchive/hadoop-20
src/core/org/apache/hadoop/util/ServletUtil.java
ServletUtil.percentageGraph
public static String percentageGraph(int perc, int width) throws IOException { assert perc >= 0; assert perc <= 100; StringBuilder builder = new StringBuilder(); builder.append("<table border=\"1px\" width=\""); builder.append(width); builder.append("px\"><tr>"); if(perc > 0) { builder.append("<td cellspacing=\"0\" class=\"perc_filled\" width=\""); builder.append(perc); builder.append("%\"></td>"); }if(perc < 100) { builder.append("<td cellspacing=\"0\" class=\"perc_nonfilled\" width=\""); builder.append(100 - perc); builder.append("%\"></td>"); } builder.append("</tr></table>"); return builder.toString(); }
java
public static String percentageGraph(int perc, int width) throws IOException { assert perc >= 0; assert perc <= 100; StringBuilder builder = new StringBuilder(); builder.append("<table border=\"1px\" width=\""); builder.append(width); builder.append("px\"><tr>"); if(perc > 0) { builder.append("<td cellspacing=\"0\" class=\"perc_filled\" width=\""); builder.append(perc); builder.append("%\"></td>"); }if(perc < 100) { builder.append("<td cellspacing=\"0\" class=\"perc_nonfilled\" width=\""); builder.append(100 - perc); builder.append("%\"></td>"); } builder.append("</tr></table>"); return builder.toString(); }
[ "public", "static", "String", "percentageGraph", "(", "int", "perc", ",", "int", "width", ")", "throws", "IOException", "{", "assert", "perc", ">=", "0", ";", "assert", "perc", "<=", "100", ";", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ...
Generate the percentage graph and returns HTML representation string of the same. @param perc The percentage value for which graph is to be generated @param width The width of the display table @return HTML String representation of the percentage graph @throws IOException
[ "Generate", "the", "percentage", "graph", "and", "returns", "HTML", "representation", "string", "of", "the", "same", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/util/ServletUtil.java#L76-L92
kikinteractive/ice
ice/src/main/java/com/kik/config/ice/ConfigSystem.java
ConfigSystem.configModuleWithOverrides
public static <C> Module configModuleWithOverrides(final Class<C> configInterface, OverrideConsumer<C> overrideConsumer) { checkNotNull(configInterface); checkNotNull(overrideConsumer); return configModuleWithOverrides(configInterface, Optional.empty(), Optional.ofNullable(overrideConsumer)); }
java
public static <C> Module configModuleWithOverrides(final Class<C> configInterface, OverrideConsumer<C> overrideConsumer) { checkNotNull(configInterface); checkNotNull(overrideConsumer); return configModuleWithOverrides(configInterface, Optional.empty(), Optional.ofNullable(overrideConsumer)); }
[ "public", "static", "<", "C", ">", "Module", "configModuleWithOverrides", "(", "final", "Class", "<", "C", ">", "configInterface", ",", "OverrideConsumer", "<", "C", ">", "overrideConsumer", ")", "{", "checkNotNull", "(", "configInterface", ")", ";", "checkNotNu...
Generates a Guice Module for use with Injector creation. THe generate Guice module binds a number of support classes to service a dynamically generate implementation of the provided configuration interface. This method further overrides the annotated defaults on the configuration class as per the code in the given overrideConsumer @param <C> The configuration interface type to be implemented @param configInterface The configuration interface @param overrideConsumer a lambda which is given an instance of {@link OverrideModule} which can be used to build type-safe overrides for the default configuration of the config. @return a module to install in your Guice Injector
[ "Generates", "a", "Guice", "Module", "for", "use", "with", "Injector", "creation", ".", "THe", "generate", "Guice", "module", "binds", "a", "number", "of", "support", "classes", "to", "service", "a", "dynamically", "generate", "implementation", "of", "the", "p...
train
https://github.com/kikinteractive/ice/blob/0c58d7bf2d9f6504892d0768d6022fcfa6df7514/ice/src/main/java/com/kik/config/ice/ConfigSystem.java#L107-L112
infinispan/infinispan
query/src/main/java/org/infinispan/query/backend/QueryInterceptor.java
QueryInterceptor.removeFromIndexes
private void removeFromIndexes(Object value, Object key, TransactionContext transactionContext) { performSearchWork(value, keyToString(key), WorkType.DELETE, transactionContext); }
java
private void removeFromIndexes(Object value, Object key, TransactionContext transactionContext) { performSearchWork(value, keyToString(key), WorkType.DELETE, transactionContext); }
[ "private", "void", "removeFromIndexes", "(", "Object", "value", ",", "Object", "key", ",", "TransactionContext", "transactionContext", ")", "{", "performSearchWork", "(", "value", ",", "keyToString", "(", "key", ")", ",", "WorkType", ".", "DELETE", ",", "transac...
Method that will be called when data needs to be removed from Lucene.
[ "Method", "that", "will", "be", "called", "when", "data", "needs", "to", "be", "removed", "from", "Lucene", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/query/src/main/java/org/infinispan/query/backend/QueryInterceptor.java#L365-L367
aws/aws-sdk-java
aws-java-sdk-lexmodelbuilding/src/main/java/com/amazonaws/services/lexmodelbuilding/model/BotChannelAssociation.java
BotChannelAssociation.withBotConfiguration
public BotChannelAssociation withBotConfiguration(java.util.Map<String, String> botConfiguration) { setBotConfiguration(botConfiguration); return this; }
java
public BotChannelAssociation withBotConfiguration(java.util.Map<String, String> botConfiguration) { setBotConfiguration(botConfiguration); return this; }
[ "public", "BotChannelAssociation", "withBotConfiguration", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "botConfiguration", ")", "{", "setBotConfiguration", "(", "botConfiguration", ")", ";", "return", "this", ";", "}" ]
<p> Provides information necessary to communicate with the messaging platform. </p> @param botConfiguration Provides information necessary to communicate with the messaging platform. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Provides", "information", "necessary", "to", "communicate", "with", "the", "messaging", "platform", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-lexmodelbuilding/src/main/java/com/amazonaws/services/lexmodelbuilding/model/BotChannelAssociation.java#L453-L456
sagiegurari/fax4j
src/main/java/org/fax4j/util/DefaultProcessExecutor.java
DefaultProcessExecutor.executeProcessImpl
@Override protected ProcessOutput executeProcessImpl(ConfigurationHolder configurationHolder,String command) throws IOException,InterruptedException { //parse command List<String> commandList=this.parseCommand(configurationHolder,command); //invoke process ProcessBuilder processBuilder=new ProcessBuilder(commandList); Process process=processBuilder.start(); //read output InputStream inputStream=process.getInputStream(); OutputReadThread outputThread=new OutputReadThread(inputStream); outputThread.start(); inputStream=process.getErrorStream(); OutputReadThread errorThread=new OutputReadThread(inputStream); errorThread.start(); //wait for process to end int exitCode=process.waitFor(); //get output String outputText=outputThread.getText(); String errorText=errorThread.getText(); //create output ProcessOutput processOutput=new ProcessOutput(outputText,errorText,exitCode); return processOutput; }
java
@Override protected ProcessOutput executeProcessImpl(ConfigurationHolder configurationHolder,String command) throws IOException,InterruptedException { //parse command List<String> commandList=this.parseCommand(configurationHolder,command); //invoke process ProcessBuilder processBuilder=new ProcessBuilder(commandList); Process process=processBuilder.start(); //read output InputStream inputStream=process.getInputStream(); OutputReadThread outputThread=new OutputReadThread(inputStream); outputThread.start(); inputStream=process.getErrorStream(); OutputReadThread errorThread=new OutputReadThread(inputStream); errorThread.start(); //wait for process to end int exitCode=process.waitFor(); //get output String outputText=outputThread.getText(); String errorText=errorThread.getText(); //create output ProcessOutput processOutput=new ProcessOutput(outputText,errorText,exitCode); return processOutput; }
[ "@", "Override", "protected", "ProcessOutput", "executeProcessImpl", "(", "ConfigurationHolder", "configurationHolder", ",", "String", "command", ")", "throws", "IOException", ",", "InterruptedException", "{", "//parse command", "List", "<", "String", ">", "commandList", ...
This function executes the given command and returns the process output. @param configurationHolder The configuration holder used when invoking the process @param command The command to execute @return The process output @throws IOException Any IO exception @throws InterruptedException If thread interrupted during waitFor for the process
[ "This", "function", "executes", "the", "given", "command", "and", "returns", "the", "process", "output", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/util/DefaultProcessExecutor.java#L43-L72
apereo/person-directory
person-directory-impl/src/main/java/org/apereo/services/persondir/support/web/RequestAttributeSourceFilter.java
RequestAttributeSourceFilter.addRequestCookies
protected void addRequestCookies(final HttpServletRequest httpServletRequest, final Map<String, List<Object>> attributes) { final Cookie[] cookies = httpServletRequest.getCookies(); if (cookies == null) { return; } for (final Cookie cookie : cookies) { final String cookieName = cookie.getName(); if (this.cookieAttributeMapping.containsKey(cookieName)) { for (final String attributeName : this.cookieAttributeMapping.get(cookieName)) { attributes.put(attributeName, list(cookie.getValue())); } } } }
java
protected void addRequestCookies(final HttpServletRequest httpServletRequest, final Map<String, List<Object>> attributes) { final Cookie[] cookies = httpServletRequest.getCookies(); if (cookies == null) { return; } for (final Cookie cookie : cookies) { final String cookieName = cookie.getName(); if (this.cookieAttributeMapping.containsKey(cookieName)) { for (final String attributeName : this.cookieAttributeMapping.get(cookieName)) { attributes.put(attributeName, list(cookie.getValue())); } } } }
[ "protected", "void", "addRequestCookies", "(", "final", "HttpServletRequest", "httpServletRequest", ",", "final", "Map", "<", "String", ",", "List", "<", "Object", ">", ">", "attributes", ")", "{", "final", "Cookie", "[", "]", "cookies", "=", "httpServletRequest...
Add request cookies to the attributes map @param httpServletRequest Http Servlet Request @param attributes Map of attributes to add additional attributes to from the Http Request
[ "Add", "request", "cookies", "to", "the", "attributes", "map" ]
train
https://github.com/apereo/person-directory/blob/331200c0878aec202b8aff12a732402d6ba7681f/person-directory-impl/src/main/java/org/apereo/services/persondir/support/web/RequestAttributeSourceFilter.java#L436-L450
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/service/AbstractDynamicService.java
AbstractDynamicService.whenState
protected static void whenState(final Endpoint endpoint, final LifecycleState wanted, Action1<LifecycleState> then) { endpoint .states() .filter(new Func1<LifecycleState, Boolean>() { @Override public Boolean call(LifecycleState state) { return state == wanted; } }) .take(1) .subscribe(then); }
java
protected static void whenState(final Endpoint endpoint, final LifecycleState wanted, Action1<LifecycleState> then) { endpoint .states() .filter(new Func1<LifecycleState, Boolean>() { @Override public Boolean call(LifecycleState state) { return state == wanted; } }) .take(1) .subscribe(then); }
[ "protected", "static", "void", "whenState", "(", "final", "Endpoint", "endpoint", ",", "final", "LifecycleState", "wanted", ",", "Action1", "<", "LifecycleState", ">", "then", ")", "{", "endpoint", ".", "states", "(", ")", ".", "filter", "(", "new", "Func1",...
Waits until the endpoint goes into the given state, calls the action and then unsubscribes. @param endpoint the endpoint to monitor. @param wanted the wanted state. @param then the action to execute when the state is reached.
[ "Waits", "until", "the", "endpoint", "goes", "into", "the", "given", "state", "calls", "the", "action", "and", "then", "unsubscribes", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/service/AbstractDynamicService.java#L219-L230
infinispan/infinispan
server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/DistributedCacheConfigurationAdd.java
DistributedCacheConfigurationAdd.processModelNode
@Override void processModelNode(OperationContext context, String containerName, ModelNode cache, ConfigurationBuilder builder, List<Dependency<?>> dependencies) throws OperationFailedException { // process the basic clustered configuration super.processModelNode(context, containerName, cache, builder, dependencies); final int owners = DistributedCacheConfigurationResource.OWNERS.resolveModelAttribute(context, cache).asInt(); final int segments = DistributedCacheConfigurationResource.SEGMENTS.resolveModelAttribute(context, cache).asInt(); final float capacityFactor = (float) DistributedCacheConfigurationResource.CAPACITY_FACTOR.resolveModelAttribute(context, cache).asDouble(); final long lifespan = DistributedCacheConfigurationResource.L1_LIFESPAN.resolveModelAttribute(context, cache).asLong(); // process the additional distributed attributes and elements builder.clustering().hash() .numOwners(owners) .numSegments(segments) .capacityFactor(capacityFactor) ; if (lifespan > 0) { // is disabled by default in L1ConfigurationBuilder builder.clustering().l1().enable().lifespan(lifespan); } else { builder.clustering().l1().disable(); } }
java
@Override void processModelNode(OperationContext context, String containerName, ModelNode cache, ConfigurationBuilder builder, List<Dependency<?>> dependencies) throws OperationFailedException { // process the basic clustered configuration super.processModelNode(context, containerName, cache, builder, dependencies); final int owners = DistributedCacheConfigurationResource.OWNERS.resolveModelAttribute(context, cache).asInt(); final int segments = DistributedCacheConfigurationResource.SEGMENTS.resolveModelAttribute(context, cache).asInt(); final float capacityFactor = (float) DistributedCacheConfigurationResource.CAPACITY_FACTOR.resolveModelAttribute(context, cache).asDouble(); final long lifespan = DistributedCacheConfigurationResource.L1_LIFESPAN.resolveModelAttribute(context, cache).asLong(); // process the additional distributed attributes and elements builder.clustering().hash() .numOwners(owners) .numSegments(segments) .capacityFactor(capacityFactor) ; if (lifespan > 0) { // is disabled by default in L1ConfigurationBuilder builder.clustering().l1().enable().lifespan(lifespan); } else { builder.clustering().l1().disable(); } }
[ "@", "Override", "void", "processModelNode", "(", "OperationContext", "context", ",", "String", "containerName", ",", "ModelNode", "cache", ",", "ConfigurationBuilder", "builder", ",", "List", "<", "Dependency", "<", "?", ">", ">", "dependencies", ")", "throws", ...
Implementation of abstract method processModelNode suitable for distributed cache @param context @param containerName @param builder @param dependencies @return
[ "Implementation", "of", "abstract", "method", "processModelNode", "suitable", "for", "distributed", "cache" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/DistributedCacheConfigurationAdd.java#L63-L89
aspectran/aspectran
core/src/main/java/com/aspectran/core/util/ReflectionUtils.java
ReflectionUtils.getTypeDifferenceWeight
public static float getTypeDifferenceWeight(Class<?> paramType, Object destArg) { if (!TypeUtils.isAssignableValue(paramType, destArg)) { return Float.MAX_VALUE; } return getTypeDifferenceWeight(paramType, (destArg != null ? destArg.getClass() : null)); }
java
public static float getTypeDifferenceWeight(Class<?> paramType, Object destArg) { if (!TypeUtils.isAssignableValue(paramType, destArg)) { return Float.MAX_VALUE; } return getTypeDifferenceWeight(paramType, (destArg != null ? destArg.getClass() : null)); }
[ "public", "static", "float", "getTypeDifferenceWeight", "(", "Class", "<", "?", ">", "paramType", ",", "Object", "destArg", ")", "{", "if", "(", "!", "TypeUtils", ".", "isAssignableValue", "(", "paramType", ",", "destArg", ")", ")", "{", "return", "Float", ...
Algorithm that judges the match between the declared parameter types of a candidate method and a specific list of arguments that this method is supposed to be invoked with. @param paramType the parameter type to match @param destArg the argument to match @return the type difference weight
[ "Algorithm", "that", "judges", "the", "match", "between", "the", "declared", "parameter", "types", "of", "a", "candidate", "method", "and", "a", "specific", "list", "of", "arguments", "that", "this", "method", "is", "supposed", "to", "be", "invoked", "with", ...
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/ReflectionUtils.java#L119-L124
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/reflect/ClassReflectionIndex.java
ClassReflectionIndex.getMethod
public Method getMethod(Class<?> returnType, String name, Class<?>... paramTypes) { final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name); if (nameMap == null) { return null; } final Map<Class<?>, Method> paramsMap = nameMap.get(createParamList(paramTypes)); if (paramsMap == null) { return null; } return paramsMap.get(returnType); }
java
public Method getMethod(Class<?> returnType, String name, Class<?>... paramTypes) { final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name); if (nameMap == null) { return null; } final Map<Class<?>, Method> paramsMap = nameMap.get(createParamList(paramTypes)); if (paramsMap == null) { return null; } return paramsMap.get(returnType); }
[ "public", "Method", "getMethod", "(", "Class", "<", "?", ">", "returnType", ",", "String", "name", ",", "Class", "<", "?", ">", "...", "paramTypes", ")", "{", "final", "Map", "<", "ParamList", ",", "Map", "<", "Class", "<", "?", ">", ",", "Method", ...
Get a method declared on this object. @param returnType the method return type @param name the name of the method @param paramTypes the parameter types of the method @return the method, or {@code null} if no method of that description exists
[ "Get", "a", "method", "declared", "on", "this", "object", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/reflect/ClassReflectionIndex.java#L205-L215
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.packEntry
public static void packEntry(File fileToPack, File destZipFile, final String fileName) { packEntry(fileToPack, destZipFile, new NameMapper() { public String map(String name) { return fileName; } }); }
java
public static void packEntry(File fileToPack, File destZipFile, final String fileName) { packEntry(fileToPack, destZipFile, new NameMapper() { public String map(String name) { return fileName; } }); }
[ "public", "static", "void", "packEntry", "(", "File", "fileToPack", ",", "File", "destZipFile", ",", "final", "String", "fileName", ")", "{", "packEntry", "(", "fileToPack", ",", "destZipFile", ",", "new", "NameMapper", "(", ")", "{", "public", "String", "ma...
Compresses the given file into a ZIP file. <p> The ZIP file must not be a directory and its parent directory must exist. @param fileToPack file that needs to be zipped. @param destZipFile ZIP file that will be created or overwritten. @param fileName the name for the file inside the archive
[ "Compresses", "the", "given", "file", "into", "a", "ZIP", "file", ".", "<p", ">", "The", "ZIP", "file", "must", "not", "be", "a", "directory", "and", "its", "parent", "directory", "must", "exist", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L1459-L1465
albfernandez/itext2
src/main/java/com/lowagie/text/rtf/RtfWriter2.java
RtfWriter2.importRtfFragment
public void importRtfFragment(InputStream documentSource, RtfImportMappings mappings) throws IOException, DocumentException { importRtfFragment(documentSource, mappings, null); }
java
public void importRtfFragment(InputStream documentSource, RtfImportMappings mappings) throws IOException, DocumentException { importRtfFragment(documentSource, mappings, null); }
[ "public", "void", "importRtfFragment", "(", "InputStream", "documentSource", ",", "RtfImportMappings", "mappings", ")", "throws", "IOException", ",", "DocumentException", "{", "importRtfFragment", "(", "documentSource", ",", "mappings", ",", "null", ")", ";", "}" ]
Adds a fragment of an RTF document to the current RTF document being generated. Since this fragment doesn't contain font or color tables, all fonts and colors are mapped to the default font and color. If the font and color mappings are known, they can be specified via the mappings parameter. @param documentSource The InputStream to read the RTF fragment from. @param mappings The RtfImportMappings that contain font and color mappings to apply to the fragment. @throws IOException On errors reading the RTF fragment. @throws DocumentException On errors adding to this RTF fragment. @since 2.1.0
[ "Adds", "a", "fragment", "of", "an", "RTF", "document", "to", "the", "current", "RTF", "document", "being", "generated", ".", "Since", "this", "fragment", "doesn", "t", "contain", "font", "or", "color", "tables", "all", "fonts", "and", "colors", "are", "ma...
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/rtf/RtfWriter2.java#L311-L313
JodaOrg/joda-time
src/main/java/org/joda/time/DateTimeZone.java
DateTimeZone.getMillisKeepLocal
public long getMillisKeepLocal(DateTimeZone newZone, long oldInstant) { if (newZone == null) { newZone = DateTimeZone.getDefault(); } if (newZone == this) { return oldInstant; } long instantLocal = convertUTCToLocal(oldInstant); return newZone.convertLocalToUTC(instantLocal, false, oldInstant); }
java
public long getMillisKeepLocal(DateTimeZone newZone, long oldInstant) { if (newZone == null) { newZone = DateTimeZone.getDefault(); } if (newZone == this) { return oldInstant; } long instantLocal = convertUTCToLocal(oldInstant); return newZone.convertLocalToUTC(instantLocal, false, oldInstant); }
[ "public", "long", "getMillisKeepLocal", "(", "DateTimeZone", "newZone", ",", "long", "oldInstant", ")", "{", "if", "(", "newZone", "==", "null", ")", "{", "newZone", "=", "DateTimeZone", ".", "getDefault", "(", ")", ";", "}", "if", "(", "newZone", "==", ...
Gets the millisecond instant in another zone keeping the same local time. <p> The conversion is performed by converting the specified UTC millis to local millis in this zone, then converting back to UTC millis in the new zone. @param newZone the new zone, null means default @param oldInstant the UTC millisecond instant to convert @return the UTC millisecond instant with the same local time in the new zone
[ "Gets", "the", "millisecond", "instant", "in", "another", "zone", "keeping", "the", "same", "local", "time", ".", "<p", ">", "The", "conversion", "is", "performed", "by", "converting", "the", "specified", "UTC", "millis", "to", "local", "millis", "in", "this...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/DateTimeZone.java#L1059-L1068
code4everything/util
src/main/java/com/zhazhapan/util/Checker.java
Checker.checkNull
public static Short checkNull(Short value, short elseValue) { return checkNull(value, Short.valueOf(elseValue)); }
java
public static Short checkNull(Short value, short elseValue) { return checkNull(value, Short.valueOf(elseValue)); }
[ "public", "static", "Short", "checkNull", "(", "Short", "value", ",", "short", "elseValue", ")", "{", "return", "checkNull", "(", "value", ",", "Short", ".", "valueOf", "(", "elseValue", ")", ")", ";", "}" ]
检查Short是否为null @param value 值 @param elseValue 为null返回的值 @return {@link Short} @since 1.0.8
[ "检查Short是否为null" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/Checker.java#L1349-L1351
jenkinsci/java-client-api
jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java
JenkinsServer.createView
public JenkinsServer createView(FolderJob folder, String viewName, String viewXml, Boolean crumbFlag) throws IOException { client.post_xml(UrlUtils.toBaseUrl(folder) + "createView?name=" + EncodingUtils.formParameter(viewName), viewXml, crumbFlag); return this; }
java
public JenkinsServer createView(FolderJob folder, String viewName, String viewXml, Boolean crumbFlag) throws IOException { client.post_xml(UrlUtils.toBaseUrl(folder) + "createView?name=" + EncodingUtils.formParameter(viewName), viewXml, crumbFlag); return this; }
[ "public", "JenkinsServer", "createView", "(", "FolderJob", "folder", ",", "String", "viewName", ",", "String", "viewXml", ",", "Boolean", "crumbFlag", ")", "throws", "IOException", "{", "client", ".", "post_xml", "(", "UrlUtils", ".", "toBaseUrl", "(", "folder",...
Create a view on the server using the provided xml and in the provided folder. @param folder the folder. @param viewName the view name. @param viewXml the view xml. @param crumbFlag <code>true</code> to add <b>crumbIssuer</b> <code>false</code> otherwise. @throws IOException in case of an error.
[ "Create", "a", "view", "on", "the", "server", "using", "the", "provided", "xml", "and", "in", "the", "provided", "folder", "." ]
train
https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L442-L447
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/filter/derivative/DerivativeLaplacian.java
DerivativeLaplacian.process
public static void process(GrayU8 orig, GrayS16 deriv, @Nullable ImageBorder_S32<GrayU8> border ) { deriv.reshape(orig.width,orig.height); if( BoofConcurrency.USE_CONCURRENT ) { DerivativeLaplacian_Inner_MT.process(orig,deriv); } else { DerivativeLaplacian_Inner.process(orig,deriv); } if( border != null ) { border.setImage(orig); ConvolveJustBorder_General_SB.convolve(kernel_I32, border,deriv); } }
java
public static void process(GrayU8 orig, GrayS16 deriv, @Nullable ImageBorder_S32<GrayU8> border ) { deriv.reshape(orig.width,orig.height); if( BoofConcurrency.USE_CONCURRENT ) { DerivativeLaplacian_Inner_MT.process(orig,deriv); } else { DerivativeLaplacian_Inner.process(orig,deriv); } if( border != null ) { border.setImage(orig); ConvolveJustBorder_General_SB.convolve(kernel_I32, border,deriv); } }
[ "public", "static", "void", "process", "(", "GrayU8", "orig", ",", "GrayS16", "deriv", ",", "@", "Nullable", "ImageBorder_S32", "<", "GrayU8", ">", "border", ")", "{", "deriv", ".", "reshape", "(", "orig", ".", "width", ",", "orig", ".", "height", ")", ...
Computes the Laplacian of input image. @param orig Input image. Not modified. @param deriv Where the Laplacian is written to. Modified.
[ "Computes", "the", "Laplacian", "of", "input", "image", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/filter/derivative/DerivativeLaplacian.java#L74-L87
Ordinastie/MalisisCore
src/main/java/net/malisis/core/network/MalisisNetwork.java
MalisisNetwork.sendToPlayersWatchingChunk
public void sendToPlayersWatchingChunk(IMessage message, Chunk chunk) { EntityUtils.getPlayersWatchingChunk(chunk).forEach(p -> sendTo(message, p)); }
java
public void sendToPlayersWatchingChunk(IMessage message, Chunk chunk) { EntityUtils.getPlayersWatchingChunk(chunk).forEach(p -> sendTo(message, p)); }
[ "public", "void", "sendToPlayersWatchingChunk", "(", "IMessage", "message", ",", "Chunk", "chunk", ")", "{", "EntityUtils", ".", "getPlayersWatchingChunk", "(", "chunk", ")", ".", "forEach", "(", "p", "->", "sendTo", "(", "message", ",", "p", ")", ")", ";", ...
Send the {@link IMessage} to all the players currently watching that specific chunk.<br> The {@link IMessageHandler} for the message type should be on the CLIENT side. @param message the message @param chunk the chunk
[ "Send", "the", "{", "@link", "IMessage", "}", "to", "all", "the", "players", "currently", "watching", "that", "specific", "chunk", ".", "<br", ">", "The", "{", "@link", "IMessageHandler", "}", "for", "the", "message", "type", "should", "be", "on", "the", ...
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/network/MalisisNetwork.java#L84-L87
marklogic/marklogic-sesame
marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClientImpl.java
MarkLogicClientImpl.performSPARQLQuery
public InputStream performSPARQLQuery(String queryString, SPARQLQueryBindingSet bindings, long start, long pageLength, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException { return performSPARQLQuery(queryString, bindings, new InputStreamHandle(), start, pageLength, tx, includeInferred, baseURI); }
java
public InputStream performSPARQLQuery(String queryString, SPARQLQueryBindingSet bindings, long start, long pageLength, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException { return performSPARQLQuery(queryString, bindings, new InputStreamHandle(), start, pageLength, tx, includeInferred, baseURI); }
[ "public", "InputStream", "performSPARQLQuery", "(", "String", "queryString", ",", "SPARQLQueryBindingSet", "bindings", ",", "long", "start", ",", "long", "pageLength", ",", "Transaction", "tx", ",", "boolean", "includeInferred", ",", "String", "baseURI", ")", "throw...
executes SPARQLQuery @param queryString @param bindings @param start @param pageLength @param tx @param includeInferred @param baseURI @return @throws JsonProcessingException
[ "executes", "SPARQLQuery" ]
train
https://github.com/marklogic/marklogic-sesame/blob/d5b668ed2b3d5e90c9f1d5096012813c272062a2/marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClientImpl.java#L135-L137
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java
ApiOvhHostingprivateDatabase.serviceName_config_update_POST
public OvhConfiguration serviceName_config_update_POST(String serviceName, OvhSafeKeyValue<String>[] parameters) throws IOException { String qPath = "/hosting/privateDatabase/{serviceName}/config/update"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "parameters", parameters); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhConfiguration.class); }
java
public OvhConfiguration serviceName_config_update_POST(String serviceName, OvhSafeKeyValue<String>[] parameters) throws IOException { String qPath = "/hosting/privateDatabase/{serviceName}/config/update"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "parameters", parameters); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhConfiguration.class); }
[ "public", "OvhConfiguration", "serviceName_config_update_POST", "(", "String", "serviceName", ",", "OvhSafeKeyValue", "<", "String", ">", "[", "]", "parameters", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/privateDatabase/{serviceName}/config/upda...
Update the configuration REST: POST /hosting/privateDatabase/{serviceName}/config/update @param parameters [required] Array of instance configuration parameters @param serviceName [required] The internal name of your private database
[ "Update", "the", "configuration" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java#L716-L723
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/cp/internal/session/AbstractProxySessionManager.java
AbstractProxySessionManager.releaseSession
public final void releaseSession(RaftGroupId groupId, long id, int count) { SessionState session = sessions.get(groupId); if (session != null && session.id == id) { session.release(count); } }
java
public final void releaseSession(RaftGroupId groupId, long id, int count) { SessionState session = sessions.get(groupId); if (session != null && session.id == id) { session.release(count); } }
[ "public", "final", "void", "releaseSession", "(", "RaftGroupId", "groupId", ",", "long", "id", ",", "int", "count", ")", "{", "SessionState", "session", "=", "sessions", ".", "get", "(", "groupId", ")", ";", "if", "(", "session", "!=", "null", "&&", "ses...
Decrements acquire count of the session. Returns silently if no session exists for the given id.
[ "Decrements", "acquire", "count", "of", "the", "session", ".", "Returns", "silently", "if", "no", "session", "exists", "for", "the", "given", "id", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cp/internal/session/AbstractProxySessionManager.java#L145-L150
dyu/protostuff-1.0.x
protostuff-core/src/main/java/com/dyuproject/protostuff/ProtostuffIOUtil.java
ProtostuffIOUtil.mergeFrom
public static <T> void mergeFrom(byte[] data, T message, Schema<T> schema) { IOUtil.mergeFrom(data, 0, data.length, message, schema, true); }
java
public static <T> void mergeFrom(byte[] data, T message, Schema<T> schema) { IOUtil.mergeFrom(data, 0, data.length, message, schema, true); }
[ "public", "static", "<", "T", ">", "void", "mergeFrom", "(", "byte", "[", "]", "data", ",", "T", "message", ",", "Schema", "<", "T", ">", "schema", ")", "{", "IOUtil", ".", "mergeFrom", "(", "data", ",", "0", ",", "data", ".", "length", ",", "mes...
Merges the {@code message} with the byte array using the given {@code schema}.
[ "Merges", "the", "{" ]
train
https://github.com/dyu/protostuff-1.0.x/blob/d7c964ec20da3fe44699d86ee95c2677ddffde96/protostuff-core/src/main/java/com/dyuproject/protostuff/ProtostuffIOUtil.java#L94-L97
Bandwidth/java-bandwidth
src/main/java/com/bandwidth/sdk/BandwidthClient.java
BandwidthClient.setupRequest
protected HttpUriRequest setupRequest(final String path, final String method, final Map<String, Object> params) { final HttpUriRequest request = buildMethod(method, path, params); request.addHeader(new BasicHeader("Accept", "application/json")); request.addHeader(new BasicHeader("Accept-Charset", "utf-8")); request.setHeader(new BasicHeader("Authorization", "Basic " + new String(Base64.encodeBase64((this.token + ":" + this.secret).getBytes())))); return request; }
java
protected HttpUriRequest setupRequest(final String path, final String method, final Map<String, Object> params) { final HttpUriRequest request = buildMethod(method, path, params); request.addHeader(new BasicHeader("Accept", "application/json")); request.addHeader(new BasicHeader("Accept-Charset", "utf-8")); request.setHeader(new BasicHeader("Authorization", "Basic " + new String(Base64.encodeBase64((this.token + ":" + this.secret).getBytes())))); return request; }
[ "protected", "HttpUriRequest", "setupRequest", "(", "final", "String", "path", ",", "final", "String", "method", ",", "final", "Map", "<", "String", ",", "Object", ">", "params", ")", "{", "final", "HttpUriRequest", "request", "=", "buildMethod", "(", "method"...
Helper method to build the request to the server. @param path the path. @param method the method. @param params the parameters. @return the request.
[ "Helper", "method", "to", "build", "the", "request", "to", "the", "server", "." ]
train
https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/BandwidthClient.java#L539-L545
mikepenz/Android-Iconics
library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java
IconicsDrawable.sizeDp
@NonNull public IconicsDrawable sizeDp(@Dimension(unit = DP) int sizeDp) { return sizePx(Utils.convertDpToPx(mContext, sizeDp)); }
java
@NonNull public IconicsDrawable sizeDp(@Dimension(unit = DP) int sizeDp) { return sizePx(Utils.convertDpToPx(mContext, sizeDp)); }
[ "@", "NonNull", "public", "IconicsDrawable", "sizeDp", "(", "@", "Dimension", "(", "unit", "=", "DP", ")", "int", "sizeDp", ")", "{", "return", "sizePx", "(", "Utils", ".", "convertDpToPx", "(", "mContext", ",", "sizeDp", ")", ")", ";", "}" ]
Set the size of the drawable. @param sizeDp The size in density-independent pixels (dp). @return The current IconicsDrawable for chaining.
[ "Set", "the", "size", "of", "the", "drawable", "." ]
train
https://github.com/mikepenz/Android-Iconics/blob/0b2c8f7d07b6d2715a417563c66311e7e1fcc7d8/library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java#L644-L647
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPFriendlyURLEntryPersistenceImpl.java
CPFriendlyURLEntryPersistenceImpl.findByUUID_G
@Override public CPFriendlyURLEntry findByUUID_G(String uuid, long groupId) throws NoSuchCPFriendlyURLEntryException { CPFriendlyURLEntry cpFriendlyURLEntry = fetchByUUID_G(uuid, groupId); if (cpFriendlyURLEntry == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPFriendlyURLEntryException(msg.toString()); } return cpFriendlyURLEntry; }
java
@Override public CPFriendlyURLEntry findByUUID_G(String uuid, long groupId) throws NoSuchCPFriendlyURLEntryException { CPFriendlyURLEntry cpFriendlyURLEntry = fetchByUUID_G(uuid, groupId); if (cpFriendlyURLEntry == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPFriendlyURLEntryException(msg.toString()); } return cpFriendlyURLEntry; }
[ "@", "Override", "public", "CPFriendlyURLEntry", "findByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "throws", "NoSuchCPFriendlyURLEntryException", "{", "CPFriendlyURLEntry", "cpFriendlyURLEntry", "=", "fetchByUUID_G", "(", "uuid", ",", "groupId", ")", ...
Returns the cp friendly url entry where uuid = &#63; and groupId = &#63; or throws a {@link NoSuchCPFriendlyURLEntryException} if it could not be found. @param uuid the uuid @param groupId the group ID @return the matching cp friendly url entry @throws NoSuchCPFriendlyURLEntryException if a matching cp friendly url entry could not be found
[ "Returns", "the", "cp", "friendly", "url", "entry", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "or", "throws", "a", "{", "@link", "NoSuchCPFriendlyURLEntryException", "}", "if", "it", "could", "not", "be", "found", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPFriendlyURLEntryPersistenceImpl.java#L671-L697
CenturyLinkCloud/mdw
mdw-workflow/src/com/centurylink/mdw/workflow/adapter/TextAdapterActivity.java
TextAdapterActivity.handleConnectionException
protected void handleConnectionException(int errorCode, Throwable originalCause) throws ActivityException { InternalEvent message = InternalEvent.createActivityStartMessage(getActivityId(), getProcessInstanceId(), getWorkTransitionInstanceId(), getMasterRequestId(), COMPCODE_AUTO_RETRY); ScheduledEventQueue eventQueue = ScheduledEventQueue.getSingleton(); int retry_interval = this.getRetryInterval(); Date scheduledTime = new Date(DatabaseAccess.getCurrentTime()+retry_interval*1000); super.loginfo("The activity failed, set to retry at " + StringHelper.dateToString(scheduledTime)); eventQueue.scheduleInternalEvent(ScheduledEvent.INTERNAL_EVENT_PREFIX+this.getActivityInstanceId(), scheduledTime, message.toString(), "procinst:"+this.getProcessInstanceId().toString()); this.setReturnCode(COMPCODE_AUTO_RETRY); // the above is to prevent engine from making transitions (typically to exception handler) throw new ActivityException(errorCode, originalCause.getMessage(), originalCause); }
java
protected void handleConnectionException(int errorCode, Throwable originalCause) throws ActivityException { InternalEvent message = InternalEvent.createActivityStartMessage(getActivityId(), getProcessInstanceId(), getWorkTransitionInstanceId(), getMasterRequestId(), COMPCODE_AUTO_RETRY); ScheduledEventQueue eventQueue = ScheduledEventQueue.getSingleton(); int retry_interval = this.getRetryInterval(); Date scheduledTime = new Date(DatabaseAccess.getCurrentTime()+retry_interval*1000); super.loginfo("The activity failed, set to retry at " + StringHelper.dateToString(scheduledTime)); eventQueue.scheduleInternalEvent(ScheduledEvent.INTERNAL_EVENT_PREFIX+this.getActivityInstanceId(), scheduledTime, message.toString(), "procinst:"+this.getProcessInstanceId().toString()); this.setReturnCode(COMPCODE_AUTO_RETRY); // the above is to prevent engine from making transitions (typically to exception handler) throw new ActivityException(errorCode, originalCause.getMessage(), originalCause); }
[ "protected", "void", "handleConnectionException", "(", "int", "errorCode", ",", "Throwable", "originalCause", ")", "throws", "ActivityException", "{", "InternalEvent", "message", "=", "InternalEvent", ".", "createActivityStartMessage", "(", "getActivityId", "(", ")", ",...
Typically you should not override this method. ConnectionPoolAdapter does override this with internal MDW logic. @param errorCode @throws ActivityException
[ "Typically", "you", "should", "not", "override", "this", "method", ".", "ConnectionPoolAdapter", "does", "override", "this", "with", "internal", "MDW", "logic", "." ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/src/com/centurylink/mdw/workflow/adapter/TextAdapterActivity.java#L414-L428
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/RouteTablesInner.java
RouteTablesInner.getByResourceGroup
public RouteTableInner getByResourceGroup(String resourceGroupName, String routeTableName, String expand) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, routeTableName, expand).toBlocking().single().body(); }
java
public RouteTableInner getByResourceGroup(String resourceGroupName, String routeTableName, String expand) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, routeTableName, expand).toBlocking().single().body(); }
[ "public", "RouteTableInner", "getByResourceGroup", "(", "String", "resourceGroupName", ",", "String", "routeTableName", ",", "String", "expand", ")", "{", "return", "getByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "routeTableName", ",", "expand",...
Gets the specified route table. @param resourceGroupName The name of the resource group. @param routeTableName The name of the route table. @param expand Expands referenced resources. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the RouteTableInner object if successful.
[ "Gets", "the", "specified", "route", "table", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/RouteTablesInner.java#L356-L358
amaembo/streamex
src/main/java/one/util/streamex/DoubleStreamEx.java
DoubleStreamEx.minByLong
public OptionalDouble minByLong(DoubleToLongFunction keyExtractor) { return collect(PrimitiveBox::new, (box, d) -> { long key = keyExtractor.applyAsLong(d); if (!box.b || box.l > key) { box.b = true; box.l = key; box.d = d; } }, PrimitiveBox.MIN_LONG).asDouble(); }
java
public OptionalDouble minByLong(DoubleToLongFunction keyExtractor) { return collect(PrimitiveBox::new, (box, d) -> { long key = keyExtractor.applyAsLong(d); if (!box.b || box.l > key) { box.b = true; box.l = key; box.d = d; } }, PrimitiveBox.MIN_LONG).asDouble(); }
[ "public", "OptionalDouble", "minByLong", "(", "DoubleToLongFunction", "keyExtractor", ")", "{", "return", "collect", "(", "PrimitiveBox", "::", "new", ",", "(", "box", ",", "d", ")", "->", "{", "long", "key", "=", "keyExtractor", ".", "applyAsLong", "(", "d"...
Returns the minimum element of this stream according to the provided key extractor function. <p> This is a terminal operation. @param keyExtractor a non-interfering, stateless function @return an {@code OptionalDouble} describing the first element of this stream for which the lowest value was returned by key extractor, or an empty {@code OptionalDouble} if the stream is empty @since 0.1.2
[ "Returns", "the", "minimum", "element", "of", "this", "stream", "according", "to", "the", "provided", "key", "extractor", "function", "." ]
train
https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/DoubleStreamEx.java#L925-L934
OpenLiberty/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/util/xml/XmlUtils.java
XmlUtils.getChildTextList
public static List getChildTextList(Element elem, String childTagName) { NodeList nodeList = elem.getElementsByTagName(childTagName); int len = nodeList.getLength(); if (len == 0) { return Collections.EMPTY_LIST; } List list = new ArrayList(len); for (int i = 0; i < len; i++) { list.add(getElementText((Element)nodeList.item(i))); } return list; }
java
public static List getChildTextList(Element elem, String childTagName) { NodeList nodeList = elem.getElementsByTagName(childTagName); int len = nodeList.getLength(); if (len == 0) { return Collections.EMPTY_LIST; } List list = new ArrayList(len); for (int i = 0; i < len; i++) { list.add(getElementText((Element)nodeList.item(i))); } return list; }
[ "public", "static", "List", "getChildTextList", "(", "Element", "elem", ",", "String", "childTagName", ")", "{", "NodeList", "nodeList", "=", "elem", ".", "getElementsByTagName", "(", "childTagName", ")", ";", "int", "len", "=", "nodeList", ".", "getLength", "...
Return list of content Strings of all child elements with given tag name. @param elem @param childTagName @return List
[ "Return", "list", "of", "content", "Strings", "of", "all", "child", "elements", "with", "given", "tag", "name", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/util/xml/XmlUtils.java#L87-L103
sculptor/sculptor
sculptor-eclipse/org.sculptor.dsl.ui/src/org/sculptor/dsl/ui/resource/MavenClasspathUriResolver.java
MavenClasspathUriResolver.findResourceInWorkspace
@Override protected URI findResourceInWorkspace(IJavaProject javaProject, URI classpathUri) throws CoreException { if (javaProject.exists()) { String packagePath = classpathUri.trimSegments(1).path(); String fileName = classpathUri.lastSegment(); IPath filePath = new Path(fileName); String packageName = isEmpty(packagePath) ? "" : packagePath.substring(1).replace('/', '.'); for (IPackageFragmentRoot packageFragmentRoot : javaProject.getAllPackageFragmentRoots()) { IPackageFragment packageFragment = packageFragmentRoot.getPackageFragment(packageName); if (isMavenResourceDirectory(packageFragment)) { IResource packageFragmentResource = packageFragment.getResource(); if (packageFragmentResource instanceof IContainer) { IFile file = ((IContainer) packageFragmentResource).getFile(filePath); if (file.exists()) { return createPlatformResourceURI(file); } } } } } return super.findResourceInWorkspace(javaProject, classpathUri); }
java
@Override protected URI findResourceInWorkspace(IJavaProject javaProject, URI classpathUri) throws CoreException { if (javaProject.exists()) { String packagePath = classpathUri.trimSegments(1).path(); String fileName = classpathUri.lastSegment(); IPath filePath = new Path(fileName); String packageName = isEmpty(packagePath) ? "" : packagePath.substring(1).replace('/', '.'); for (IPackageFragmentRoot packageFragmentRoot : javaProject.getAllPackageFragmentRoots()) { IPackageFragment packageFragment = packageFragmentRoot.getPackageFragment(packageName); if (isMavenResourceDirectory(packageFragment)) { IResource packageFragmentResource = packageFragment.getResource(); if (packageFragmentResource instanceof IContainer) { IFile file = ((IContainer) packageFragmentResource).getFile(filePath); if (file.exists()) { return createPlatformResourceURI(file); } } } } } return super.findResourceInWorkspace(javaProject, classpathUri); }
[ "@", "Override", "protected", "URI", "findResourceInWorkspace", "(", "IJavaProject", "javaProject", ",", "URI", "classpathUri", ")", "throws", "CoreException", "{", "if", "(", "javaProject", ".", "exists", "(", ")", ")", "{", "String", "packagePath", "=", "class...
Before forwarding to {@link JdtClasspathUriResolver#findResourceInWorkspace(IJavaProject, URI)} this methods uses {@link #isMavenResourceDirectory(IPackageFragment)} to check if the given classpath URI references a resource in an excluded Maven resource directory.
[ "Before", "forwarding", "to", "{" ]
train
https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-eclipse/org.sculptor.dsl.ui/src/org/sculptor/dsl/ui/resource/MavenClasspathUriResolver.java#L60-L81
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionCategoryPersistenceImpl.java
CPOptionCategoryPersistenceImpl.findByGroupId
@Override public List<CPOptionCategory> findByGroupId(long groupId) { return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
@Override public List<CPOptionCategory> findByGroupId(long groupId) { return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
[ "@", "Override", "public", "List", "<", "CPOptionCategory", ">", "findByGroupId", "(", "long", "groupId", ")", "{", "return", "findByGroupId", "(", "groupId", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ";", "}" ]
Returns all the cp option categories where groupId = &#63;. @param groupId the group ID @return the matching cp option categories
[ "Returns", "all", "the", "cp", "option", "categories", "where", "groupId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionCategoryPersistenceImpl.java#L1517-L1520
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Asserter.java
Asserter.assertCurrentActivity
public void assertCurrentActivity(String message, String name, boolean isNewInstance) { assertCurrentActivity(message, name); Activity activity = activityUtils.getCurrentActivity(); if(activity != null){ assertCurrentActivity(message, activity.getClass(), isNewInstance); } }
java
public void assertCurrentActivity(String message, String name, boolean isNewInstance) { assertCurrentActivity(message, name); Activity activity = activityUtils.getCurrentActivity(); if(activity != null){ assertCurrentActivity(message, activity.getClass(), isNewInstance); } }
[ "public", "void", "assertCurrentActivity", "(", "String", "message", ",", "String", "name", ",", "boolean", "isNewInstance", ")", "{", "assertCurrentActivity", "(", "message", ",", "name", ")", ";", "Activity", "activity", "=", "activityUtils", ".", "getCurrentAct...
Asserts that an expected {@link Activity} is currently active one, with the possibility to verify that the expected {@code Activity} is a new instance of the {@code Activity}. @param message the message that should be displayed if the assert fails @param name the name of the {@code Activity} that is expected to be active e.g. {@code "MyActivity"} @param isNewInstance {@code true} if the expected {@code Activity} is a new instance of the {@code Activity}
[ "Asserts", "that", "an", "expected", "{", "@link", "Activity", "}", "is", "currently", "active", "one", "with", "the", "possibility", "to", "verify", "that", "the", "expected", "{", "@code", "Activity", "}", "is", "a", "new", "instance", "of", "the", "{", ...
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Asserter.java#L85-L92
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java
ProxyRegistry.getOrCreateProxy
public DistributedObject getOrCreateProxy(String name, boolean publishEvent) { DistributedObjectFuture proxyFuture = getOrCreateProxyFuture(name, publishEvent, true); return proxyFuture.get(); }
java
public DistributedObject getOrCreateProxy(String name, boolean publishEvent) { DistributedObjectFuture proxyFuture = getOrCreateProxyFuture(name, publishEvent, true); return proxyFuture.get(); }
[ "public", "DistributedObject", "getOrCreateProxy", "(", "String", "name", ",", "boolean", "publishEvent", ")", "{", "DistributedObjectFuture", "proxyFuture", "=", "getOrCreateProxyFuture", "(", "name", ",", "publishEvent", ",", "true", ")", ";", "return", "proxyFuture...
Retrieves a DistributedObject proxy or creates it if it is not available. DistributedObject will be initialized by calling {@link InitializingObject#initialize()}, if it implements {@link InitializingObject}. @param name The name of the DistributedObject proxy object to retrieve or create. @param publishEvent true if a DistributedObjectEvent should be fired. @return The DistributedObject instance.
[ "Retrieves", "a", "DistributedObject", "proxy", "or", "creates", "it", "if", "it", "is", "not", "available", ".", "DistributedObject", "will", "be", "initialized", "by", "calling", "{", "@link", "InitializingObject#initialize", "()", "}", "if", "it", "implements",...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/impl/proxyservice/impl/ProxyRegistry.java#L159-L162
alkacon/opencms-core
src/org/opencms/ade/configuration/CmsADEManager.java
CmsADEManager.saveElementList
private void saveElementList(CmsObject cms, List<CmsContainerElementBean> elementList, String listKey) throws CmsException { // limit the favorite list size to avoid the additional info size limit if (elementList.size() > DEFAULT_ELEMENT_LIST_SIZE) { elementList = elementList.subList(0, DEFAULT_ELEMENT_LIST_SIZE); } JSONArray data = new JSONArray(); Set<String> excludedSettings = new HashSet<String>(); // do not store the template contexts, since dragging an element into the page which might be invisible // doesn't make sense excludedSettings.add(CmsTemplateContextInfo.SETTING); for (CmsContainerElementBean element : elementList) { data.put(elementToJson(element, excludedSettings)); } CmsUser user = cms.getRequestContext().getCurrentUser(); user.setAdditionalInfo(listKey, data.toString()); cms.writeUser(user); }
java
private void saveElementList(CmsObject cms, List<CmsContainerElementBean> elementList, String listKey) throws CmsException { // limit the favorite list size to avoid the additional info size limit if (elementList.size() > DEFAULT_ELEMENT_LIST_SIZE) { elementList = elementList.subList(0, DEFAULT_ELEMENT_LIST_SIZE); } JSONArray data = new JSONArray(); Set<String> excludedSettings = new HashSet<String>(); // do not store the template contexts, since dragging an element into the page which might be invisible // doesn't make sense excludedSettings.add(CmsTemplateContextInfo.SETTING); for (CmsContainerElementBean element : elementList) { data.put(elementToJson(element, excludedSettings)); } CmsUser user = cms.getRequestContext().getCurrentUser(); user.setAdditionalInfo(listKey, data.toString()); cms.writeUser(user); }
[ "private", "void", "saveElementList", "(", "CmsObject", "cms", ",", "List", "<", "CmsContainerElementBean", ">", "elementList", ",", "String", "listKey", ")", "throws", "CmsException", "{", "// limit the favorite list size to avoid the additional info size limit", "if", "("...
Saves an element list to the user additional infos.<p> @param cms the cms context @param elementList the element list @param listKey the list key @throws CmsException if something goes wrong
[ "Saves", "an", "element", "list", "to", "the", "user", "additional", "infos", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsADEManager.java#L1485-L1506
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.fromTransferObject
public GeometryCollection fromTransferObject(GeometryCollectionTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); Geometry[] geoms = new Geometry[input.getGeometries().length]; for (int i = 0; i < geoms.length; i++) { geoms[i] = fromTransferObject(input.getGeometries()[i], crsId); } return new GeometryCollection(geoms); }
java
public GeometryCollection fromTransferObject(GeometryCollectionTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); Geometry[] geoms = new Geometry[input.getGeometries().length]; for (int i = 0; i < geoms.length; i++) { geoms[i] = fromTransferObject(input.getGeometries()[i], crsId); } return new GeometryCollection(geoms); }
[ "public", "GeometryCollection", "fromTransferObject", "(", "GeometryCollectionTo", "input", ",", "CrsId", "crsId", ")", "{", "if", "(", "input", "==", "null", ")", "{", "return", "null", ";", "}", "crsId", "=", "getCrsId", "(", "input", ",", "crsId", ")", ...
Creates a geometrycollection object starting from a transfer object. @param input the geometry collection transfer object @param crsId the crs id to use (ignores the crs of the input). If null, uses the crs of the input. @return the corresponding geometry @throws IllegalArgumentException If the geometry could not be constructed due to an invalid transfer object
[ "Creates", "a", "geometrycollection", "object", "starting", "from", "a", "transfer", "object", "." ]
train
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L271-L282
Erudika/para
para-core/src/main/java/com/erudika/para/core/App.java
App.permissionsContainOwnKeyword
public boolean permissionsContainOwnKeyword(User user, ParaObject object) { if (user == null || object == null) { return false; } String resourcePath1 = object.getType(); String resourcePath2 = object.getObjectURI().substring(1); // remove first '/' String resourcePath3 = object.getPlural(); return hasOwnKeyword(App.ALLOW_ALL, resourcePath1) || hasOwnKeyword(App.ALLOW_ALL, resourcePath2) || hasOwnKeyword(App.ALLOW_ALL, resourcePath3) || hasOwnKeyword(user.getId(), resourcePath1) || hasOwnKeyword(user.getId(), resourcePath2) || hasOwnKeyword(user.getId(), resourcePath3); }
java
public boolean permissionsContainOwnKeyword(User user, ParaObject object) { if (user == null || object == null) { return false; } String resourcePath1 = object.getType(); String resourcePath2 = object.getObjectURI().substring(1); // remove first '/' String resourcePath3 = object.getPlural(); return hasOwnKeyword(App.ALLOW_ALL, resourcePath1) || hasOwnKeyword(App.ALLOW_ALL, resourcePath2) || hasOwnKeyword(App.ALLOW_ALL, resourcePath3) || hasOwnKeyword(user.getId(), resourcePath1) || hasOwnKeyword(user.getId(), resourcePath2) || hasOwnKeyword(user.getId(), resourcePath3); }
[ "public", "boolean", "permissionsContainOwnKeyword", "(", "User", "user", ",", "ParaObject", "object", ")", "{", "if", "(", "user", "==", "null", "||", "object", "==", "null", ")", "{", "return", "false", ";", "}", "String", "resourcePath1", "=", "object", ...
Check if the permissions map contains "OWN" keyword, which restricts access to objects to their creators. @param user user in context @param object some object @return true if app contains permission for this resource and it is marked with "OWN"
[ "Check", "if", "the", "permissions", "map", "contains", "OWN", "keyword", "which", "restricts", "access", "to", "objects", "to", "their", "creators", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-core/src/main/java/com/erudika/para/core/App.java#L841-L854
GoogleCloudPlatform/bigdata-interop
gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageReadChannel.java
GoogleCloudStorageReadChannel.handleExecuteMediaException
private HttpResponse handleExecuteMediaException( IOException e, Get getObject, boolean retryWithLiveVersion) throws IOException { if (errorExtractor.itemNotFound(e)) { if (retryWithLiveVersion) { generation = null; footerContent = null; getObject.setGeneration(null); try { return getObject.executeMedia(); } catch (IOException e1) { return handleExecuteMediaException(e1, getObject, /* retryWithLiveVersion= */ false); } } throw GoogleCloudStorageExceptions.getFileNotFoundException(bucketName, objectName); } String msg = String.format("Error reading '%s' at position %d", resourceIdString, currentPosition); if (errorExtractor.rangeNotSatisfiable(e)) { throw (EOFException) new EOFException(msg).initCause(e); } throw new IOException(msg, e); }
java
private HttpResponse handleExecuteMediaException( IOException e, Get getObject, boolean retryWithLiveVersion) throws IOException { if (errorExtractor.itemNotFound(e)) { if (retryWithLiveVersion) { generation = null; footerContent = null; getObject.setGeneration(null); try { return getObject.executeMedia(); } catch (IOException e1) { return handleExecuteMediaException(e1, getObject, /* retryWithLiveVersion= */ false); } } throw GoogleCloudStorageExceptions.getFileNotFoundException(bucketName, objectName); } String msg = String.format("Error reading '%s' at position %d", resourceIdString, currentPosition); if (errorExtractor.rangeNotSatisfiable(e)) { throw (EOFException) new EOFException(msg).initCause(e); } throw new IOException(msg, e); }
[ "private", "HttpResponse", "handleExecuteMediaException", "(", "IOException", "e", ",", "Get", "getObject", ",", "boolean", "retryWithLiveVersion", ")", "throws", "IOException", "{", "if", "(", "errorExtractor", ".", "itemNotFound", "(", "e", ")", ")", "{", "if", ...
When an IOException is thrown, depending on if the exception is caused by non-existent object generation, and depending on the generation read consistency setting, either retry the read (of the latest generation), or handle the exception directly. @param e IOException thrown while reading from GCS. @param getObject the Get request to GCS. @param retryWithLiveVersion flag indicating whether we should strip the generation (thus read from the latest generation) and retry. @return the HttpResponse of reading from GCS from possible retry. @throws IOException either error on retry, or thrown because the original read encounters error.
[ "When", "an", "IOException", "is", "thrown", "depending", "on", "if", "the", "exception", "is", "caused", "by", "non", "-", "existent", "object", "generation", "and", "depending", "on", "the", "generation", "read", "consistency", "setting", "either", "retry", ...
train
https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageReadChannel.java#L1131-L1152
gallandarakhneorg/afc
core/maths/mathgraph/src/main/java/org/arakhne/afc/math/graph/GraphIterationElementComparator.java
GraphIterationElementComparator.compareSegments
@Pure protected int compareSegments(ST s1, ST s2) { assert s1 != null && s2 != null; return s1.hashCode() - s2.hashCode(); }
java
@Pure protected int compareSegments(ST s1, ST s2) { assert s1 != null && s2 != null; return s1.hashCode() - s2.hashCode(); }
[ "@", "Pure", "protected", "int", "compareSegments", "(", "ST", "s1", ",", "ST", "s2", ")", "{", "assert", "s1", "!=", "null", "&&", "s2", "!=", "null", ";", "return", "s1", ".", "hashCode", "(", ")", "-", "s2", ".", "hashCode", "(", ")", ";", "}"...
Compare the two given segments. @param s1 the first segment. @param s2 the second segment. @return <code>-1</code> if {@code s1} is lower than {@code s2}, <code>1</code> if {@code s1} is greater than {@code s2}, otherwise <code>0</code>.
[ "Compare", "the", "two", "given", "segments", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgraph/src/main/java/org/arakhne/afc/math/graph/GraphIterationElementComparator.java#L76-L80