repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
201
func_name
stringlengths
4
126
whole_func_string
stringlengths
75
3.57k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.57k
func_code_tokens
listlengths
21
599
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
upwork/java-upwork
src/com/Upwork/api/OAuthClient.java
OAuthClient.sendGetRequest
private JSONObject sendGetRequest(String url, Integer type, HashMap<String, String> params) throws JSONException { String fullUrl = getFullUrl(url); HttpGet request = new HttpGet(fullUrl); if (params != null) { URI uri; String query = ""; try { URIBuilder uriBuilder = new URIBuilder(request.getURI()); // encode values and add them to the request for (Map.Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); // to prevent double encoding, we need to create query string ourself // uriBuilder.addParameter(key, URLEncoder.encode(value).replace("%3B", ";")); query = query + key + "=" + value.replace("&", "&amp;") + "&"; // what the hell is going on in java - no adequate way to encode query string // lets temporary replace "&" in the value, to encode it manually later } // this routine will encode query string uriBuilder.setCustomQuery(query); uri = uriBuilder.build(); // re-create request to have validly encoded ampersand request = new HttpGet(fullUrl + "?" + uri.getRawQuery().replace("&amp;", "%26")); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { mOAuthConsumer.sign(request); } catch (OAuthException e) { e.printStackTrace(); } return UpworkRestClient.getJSONObject(request, type); }
java
private JSONObject sendGetRequest(String url, Integer type, HashMap<String, String> params) throws JSONException { String fullUrl = getFullUrl(url); HttpGet request = new HttpGet(fullUrl); if (params != null) { URI uri; String query = ""; try { URIBuilder uriBuilder = new URIBuilder(request.getURI()); // encode values and add them to the request for (Map.Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); // to prevent double encoding, we need to create query string ourself // uriBuilder.addParameter(key, URLEncoder.encode(value).replace("%3B", ";")); query = query + key + "=" + value.replace("&", "&amp;") + "&"; // what the hell is going on in java - no adequate way to encode query string // lets temporary replace "&" in the value, to encode it manually later } // this routine will encode query string uriBuilder.setCustomQuery(query); uri = uriBuilder.build(); // re-create request to have validly encoded ampersand request = new HttpGet(fullUrl + "?" + uri.getRawQuery().replace("&amp;", "%26")); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { mOAuthConsumer.sign(request); } catch (OAuthException e) { e.printStackTrace(); } return UpworkRestClient.getJSONObject(request, type); }
[ "private", "JSONObject", "sendGetRequest", "(", "String", "url", ",", "Integer", "type", ",", "HashMap", "<", "String", ",", "String", ">", "params", ")", "throws", "JSONException", "{", "String", "fullUrl", "=", "getFullUrl", "(", "url", ")", ";", "HttpGet"...
Send signed GET OAuth request @param url Relative URL @param type Type of HTTP request (HTTP method) @param params Hash of parameters @throws JSONException If JSON object is invalid or request was abnormal @return {@link JSONObject} JSON Object that contains data from response
[ "Send", "signed", "GET", "OAuth", "request" ]
train
https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/OAuthClient.java#L272-L312
liferay/com-liferay-commerce
commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceEntryPersistenceImpl.java
CommercePriceEntryPersistenceImpl.findAll
@Override public List<CommercePriceEntry> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
@Override public List<CommercePriceEntry> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
[ "@", "Override", "public", "List", "<", "CommercePriceEntry", ">", "findAll", "(", ")", "{", "return", "findAll", "(", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ";", "}" ]
Returns all the commerce price entries. @return the commerce price entries
[ "Returns", "all", "the", "commerce", "price", "entries", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceEntryPersistenceImpl.java#L4899-L4902
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.overTheBox_serviceName_migrate_GET
public OvhOrder overTheBox_serviceName_migrate_GET(String serviceName, Boolean hardware, String offer, String shippingContactID, OvhShippingMethodEnum shippingMethod, Long shippingRelayID) throws IOException { String qPath = "/order/overTheBox/{serviceName}/migrate"; StringBuilder sb = path(qPath, serviceName); query(sb, "hardware", hardware); query(sb, "offer", offer); query(sb, "shippingContactID", shippingContactID); query(sb, "shippingMethod", shippingMethod); query(sb, "shippingRelayID", shippingRelayID); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder overTheBox_serviceName_migrate_GET(String serviceName, Boolean hardware, String offer, String shippingContactID, OvhShippingMethodEnum shippingMethod, Long shippingRelayID) throws IOException { String qPath = "/order/overTheBox/{serviceName}/migrate"; StringBuilder sb = path(qPath, serviceName); query(sb, "hardware", hardware); query(sb, "offer", offer); query(sb, "shippingContactID", shippingContactID); query(sb, "shippingMethod", shippingMethod); query(sb, "shippingRelayID", shippingRelayID); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "overTheBox_serviceName_migrate_GET", "(", "String", "serviceName", ",", "Boolean", "hardware", ",", "String", "offer", ",", "String", "shippingContactID", ",", "OvhShippingMethodEnum", "shippingMethod", ",", "Long", "shippingRelayID", ")", "throws",...
Get prices and contracts information REST: GET /order/overTheBox/{serviceName}/migrate @param offer [required] Offer name to migrate to @param shippingContactID [required] Contact ID to deliver to @param shippingRelayID [required] Relay ID to deliver to. Needed if shipping is mondialRelay @param shippingMethod [required] How do you want your shipment shipped @param hardware [required] If you want to migrate with a new hardware @param serviceName [required] The internal name of your overTheBox offer API beta
[ "Get", "prices", "and", "contracts", "information" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L3152-L3162
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/resource/i18n/MessageBuilder.java
MessageBuilder.define
public void define(final MessageItem key, final MessageResource forcedValue) { this.overriddenMessageMap.put(key, forcedValue); set(getParamKey(key), forcedValue); }
java
public void define(final MessageItem key, final MessageResource forcedValue) { this.overriddenMessageMap.put(key, forcedValue); set(getParamKey(key), forcedValue); }
[ "public", "void", "define", "(", "final", "MessageItem", "key", ",", "final", "MessageResource", "forcedValue", ")", "{", "this", ".", "overriddenMessageMap", ".", "put", "(", "key", ",", "forcedValue", ")", ";", "set", "(", "getParamKey", "(", "key", ")", ...
Override a parameter value. @param key the parameter item key @param forcedValue the overridden value
[ "Override", "a", "parameter", "value", "." ]
train
https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/resource/i18n/MessageBuilder.java#L218-L221
morfologik/morfologik-stemming
morfologik-fsa/src/main/java/morfologik/fsa/FSA5.java
FSA5.getRightLanguageCount
@Override public int getRightLanguageCount(int node) { assert getFlags().contains(FSAFlags.NUMBERS) : "This FSA was not compiled with NUMBERS."; return decodeFromBytes(arcs, node, nodeDataLength); }
java
@Override public int getRightLanguageCount(int node) { assert getFlags().contains(FSAFlags.NUMBERS) : "This FSA was not compiled with NUMBERS."; return decodeFromBytes(arcs, node, nodeDataLength); }
[ "@", "Override", "public", "int", "getRightLanguageCount", "(", "int", "node", ")", "{", "assert", "getFlags", "(", ")", ".", "contains", "(", "FSAFlags", ".", "NUMBERS", ")", ":", "\"This FSA was not compiled with NUMBERS.\"", ";", "return", "decodeFromBytes", "(...
Returns the number encoded at the given node. The number equals the count of the set of suffixes reachable from <code>node</code> (called its right language).
[ "Returns", "the", "number", "encoded", "at", "the", "given", "node", ".", "The", "number", "equals", "the", "count", "of", "the", "set", "of", "suffixes", "reachable", "from", "<code", ">", "node<", "/", "code", ">", "(", "called", "its", "right", "langu...
train
https://github.com/morfologik/morfologik-stemming/blob/9d9099cc5ec4155a0eb8dfecdc23d01cbd734f6e/morfologik-fsa/src/main/java/morfologik/fsa/FSA5.java#L247-L251
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SpringUtils.java
SpringUtils.getBean
public static <T> T getBean(ApplicationContext appContext, String id, Class<T> clazz) { try { return appContext.getBean(id, clazz); } catch (BeansException e) { return null; } }
java
public static <T> T getBean(ApplicationContext appContext, String id, Class<T> clazz) { try { return appContext.getBean(id, clazz); } catch (BeansException e) { return null; } }
[ "public", "static", "<", "T", ">", "T", "getBean", "(", "ApplicationContext", "appContext", ",", "String", "id", ",", "Class", "<", "T", ">", "clazz", ")", "{", "try", "{", "return", "appContext", ".", "getBean", "(", "id", ",", "clazz", ")", ";", "}...
Gets a bean by its id and class. @param appContext @param id @param clazz @return
[ "Gets", "a", "bean", "by", "its", "id", "and", "class", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SpringUtils.java#L58-L64
JodaOrg/joda-time
src/main/java/org/joda/time/chrono/GJChronology.java
GJChronology.withZone
public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone, iCutoverInstant, getMinimumDaysInFirstWeek()); }
java
public Chronology withZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone, iCutoverInstant, getMinimumDaysInFirstWeek()); }
[ "public", "Chronology", "withZone", "(", "DateTimeZone", "zone", ")", "{", "if", "(", "zone", "==", "null", ")", "{", "zone", "=", "DateTimeZone", ".", "getDefault", "(", ")", ";", "}", "if", "(", "zone", "==", "getZone", "(", ")", ")", "{", "return"...
Gets the Chronology in a specific time zone. @param zone the zone to get the chronology in, null is default @return the chronology
[ "Gets", "the", "Chronology", "in", "a", "specific", "time", "zone", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/chrono/GJChronology.java#L307-L315
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/context/VmlGraphicsContext.java
VmlGraphicsContext.drawPolygon
public void drawPolygon(Object parent, String name, Polygon polygon, ShapeStyle style) { if (isAttached()) { Element element = helper.createOrUpdateElement(parent, name, "shape", style); if (polygon != null) { Dom.setStyleAttribute(element, "position", "absolute"); Dom.setElementAttribute(element, "fill-rule", "evenodd"); Dom.setElementAttribute(element, "path", VmlPathDecoder.decode(polygon)); applyElementSize(element, getWidth(), getHeight(), false); } } }
java
public void drawPolygon(Object parent, String name, Polygon polygon, ShapeStyle style) { if (isAttached()) { Element element = helper.createOrUpdateElement(parent, name, "shape", style); if (polygon != null) { Dom.setStyleAttribute(element, "position", "absolute"); Dom.setElementAttribute(element, "fill-rule", "evenodd"); Dom.setElementAttribute(element, "path", VmlPathDecoder.decode(polygon)); applyElementSize(element, getWidth(), getHeight(), false); } } }
[ "public", "void", "drawPolygon", "(", "Object", "parent", ",", "String", "name", ",", "Polygon", "polygon", ",", "ShapeStyle", "style", ")", "{", "if", "(", "isAttached", "(", ")", ")", "{", "Element", "element", "=", "helper", ".", "createOrUpdateElement", ...
Draw a {@link Polygon} geometry onto the <code>GraphicsContext</code>. @param parent parent group object @param name The Polygon's name. @param polygon The Polygon to be drawn. @param style The styling object for the Polygon.
[ "Draw", "a", "{", "@link", "Polygon", "}", "geometry", "onto", "the", "<code", ">", "GraphicsContext<", "/", "code", ">", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/VmlGraphicsContext.java#L311-L321
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/sjavac/Main.java
Main.findNumberOption
public static int findNumberOption(String[] args, String option) { int rc = 0; for (int i = 0; i<args.length; ++i) { if (args[i].equals(option)) { if (args.length > i+1) { rc = Integer.parseInt(args[i+1]); } } } return rc; }
java
public static int findNumberOption(String[] args, String option) { int rc = 0; for (int i = 0; i<args.length; ++i) { if (args[i].equals(option)) { if (args.length > i+1) { rc = Integer.parseInt(args[i+1]); } } } return rc; }
[ "public", "static", "int", "findNumberOption", "(", "String", "[", "]", "args", ",", "String", "option", ")", "{", "int", "rc", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "++", "i", ")", "{", "if...
Scan the arguments to find an option that specifies a number.
[ "Scan", "the", "arguments", "to", "find", "an", "option", "that", "specifies", "a", "number", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/sjavac/Main.java#L761-L771
OpenLiberty/open-liberty
dev/com.ibm.ws.security.audit.file/src/com/ibm/ws/security/audit/logutils/FileLogUtils.java
FileLogUtils.compileLogFileRegex
static Pattern compileLogFileRegex(String baseName, String extension) { StringBuilder builder = new StringBuilder(); // filename (dots escaped) builder.append(Pattern.quote(baseName)); // _yy.MM.dd_HH.mm.ss builder.append("(_\\d\\d\\.\\d\\d\\.\\d\\d_\\d\\d\\.\\d\\d\\.\\d\\d)"); // numeric identifier builder.append("(?:\\.(\\d+))"); // extension (dots escaped) builder.append(Pattern.quote(extension)); return Pattern.compile(builder.toString()); }
java
static Pattern compileLogFileRegex(String baseName, String extension) { StringBuilder builder = new StringBuilder(); // filename (dots escaped) builder.append(Pattern.quote(baseName)); // _yy.MM.dd_HH.mm.ss builder.append("(_\\d\\d\\.\\d\\d\\.\\d\\d_\\d\\d\\.\\d\\d\\.\\d\\d)"); // numeric identifier builder.append("(?:\\.(\\d+))"); // extension (dots escaped) builder.append(Pattern.quote(extension)); return Pattern.compile(builder.toString()); }
[ "static", "Pattern", "compileLogFileRegex", "(", "String", "baseName", ",", "String", "extension", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "// filename (dots escaped)", "builder", ".", "append", "(", "Pattern", ".", "quote...
Compiles a pattern that can be used to match rolled over log file names. The first capturing group is the date/time string, and the second capturing group is the ID. @param baseName the log file basename (e.g., "messages") @param extension the log file extension (e.g., ".log") @param idOptional true if the rollover ID is optional @return
[ "Compiles", "a", "pattern", "that", "can", "be", "used", "to", "match", "rolled", "over", "log", "file", "names", ".", "The", "first", "capturing", "group", "is", "the", "date", "/", "time", "string", "and", "the", "second", "capturing", "group", "is", "...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.audit.file/src/com/ibm/ws/security/audit/logutils/FileLogUtils.java#L153-L169
undertow-io/undertow
core/src/main/java/io/undertow/client/http/HttpResponseParser.java
HttpResponseParser.handleReasonPhrase
@SuppressWarnings("unused") final void handleReasonPhrase(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) { StringBuilder stringBuilder = state.stringBuilder; while (buffer.hasRemaining()) { final char next = (char) buffer.get(); if (next == '\n' || next == '\r') { builder.setReasonPhrase(stringBuilder.toString()); state.state = ResponseParseState.AFTER_REASON_PHRASE; state.stringBuilder.setLength(0); state.parseState = 0; state.leftOver = (byte) next; state.pos = 0; state.nextHeader = null; return; } else { stringBuilder.append(next); } } }
java
@SuppressWarnings("unused") final void handleReasonPhrase(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) { StringBuilder stringBuilder = state.stringBuilder; while (buffer.hasRemaining()) { final char next = (char) buffer.get(); if (next == '\n' || next == '\r') { builder.setReasonPhrase(stringBuilder.toString()); state.state = ResponseParseState.AFTER_REASON_PHRASE; state.stringBuilder.setLength(0); state.parseState = 0; state.leftOver = (byte) next; state.pos = 0; state.nextHeader = null; return; } else { stringBuilder.append(next); } } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "final", "void", "handleReasonPhrase", "(", "ByteBuffer", "buffer", ",", "ResponseParseState", "state", ",", "HttpResponseBuilder", "builder", ")", "{", "StringBuilder", "stringBuilder", "=", "state", ".", "stringBuilde...
Parses the reason phrase. This is called from the generated bytecode. @param buffer The buffer @param state The current state @param builder The exchange builder @return The number of bytes remaining
[ "Parses", "the", "reason", "phrase", ".", "This", "is", "called", "from", "the", "generated", "bytecode", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/client/http/HttpResponseParser.java#L202-L220
docusign/docusign-java-client
src/main/java/com/docusign/esign/api/AccountsApi.java
AccountsApi.listSharedAccess
public AccountSharedAccess listSharedAccess(String accountId, AccountsApi.ListSharedAccessOptions options) throws ApiException { Object localVarPostBody = "{}"; // verify the required parameter 'accountId' is set if (accountId == null) { throw new ApiException(400, "Missing the required parameter 'accountId' when calling listSharedAccess"); } // create path and map variables String localVarPath = "/v2/accounts/{accountId}/shared_access".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString())); // query params java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>(); java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>(); java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>(); if (options != null) { localVarQueryParams.addAll(apiClient.parameterToPairs("", "count", options.count)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "envelopes_not_shared_user_status", options.envelopesNotSharedUserStatus)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "folder_ids", options.folderIds)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "item_type", options.itemType)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "search_text", options.searchText)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "shared", options.shared)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "start_position", options.startPosition)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "user_ids", options.userIds)); } final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "docusignAccessCode" }; //{ }; GenericType<AccountSharedAccess> localVarReturnType = new GenericType<AccountSharedAccess>() {}; return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); }
java
public AccountSharedAccess listSharedAccess(String accountId, AccountsApi.ListSharedAccessOptions options) throws ApiException { Object localVarPostBody = "{}"; // verify the required parameter 'accountId' is set if (accountId == null) { throw new ApiException(400, "Missing the required parameter 'accountId' when calling listSharedAccess"); } // create path and map variables String localVarPath = "/v2/accounts/{accountId}/shared_access".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString())); // query params java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>(); java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>(); java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>(); if (options != null) { localVarQueryParams.addAll(apiClient.parameterToPairs("", "count", options.count)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "envelopes_not_shared_user_status", options.envelopesNotSharedUserStatus)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "folder_ids", options.folderIds)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "item_type", options.itemType)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "search_text", options.searchText)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "shared", options.shared)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "start_position", options.startPosition)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "user_ids", options.userIds)); } final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "docusignAccessCode" }; //{ }; GenericType<AccountSharedAccess> localVarReturnType = new GenericType<AccountSharedAccess>() {}; return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); }
[ "public", "AccountSharedAccess", "listSharedAccess", "(", "String", "accountId", ",", "AccountsApi", ".", "ListSharedAccessOptions", "options", ")", "throws", "ApiException", "{", "Object", "localVarPostBody", "=", "\"{}\"", ";", "// verify the required parameter 'accountId' ...
Reserved: Gets the shared item status for one or more users. Reserved: Retrieves shared item status for one or more users and types of items. Users with account administration privileges can retrieve shared access information for all account users. Users without account administrator privileges can only retrieve shared access information for themselves and the returned information is limited to the retrieving the status of all members of the account that are sharing their folders to the user. This is equivalent to setting the shared&#x3D;shared_from. @param accountId The external account number (int) or account ID Guid. (required) @param options for modifying the method behavior. @return AccountSharedAccess @throws ApiException if fails to make API call
[ "Reserved", ":", "Gets", "the", "shared", "item", "status", "for", "one", "or", "more", "users", ".", "Reserved", ":", "Retrieves", "shared", "item", "status", "for", "one", "or", "more", "users", "and", "types", "of", "items", ".", "Users", "with", "acc...
train
https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/AccountsApi.java#L2283-L2326
padrig64/ValidationFramework
validationframework-swing/src/main/java/com/google/code/validationframework/swing/property/JTableRolloverCellProperty.java
JTableRolloverCellProperty.updateValue
private void updateValue(Point location) { CellPosition oldValue = value; if (location == null) { value = null; } else { int row = table.rowAtPoint(location); int column = table.columnAtPoint(location); value = new CellPosition(row, column); } maybeNotifyListeners(oldValue, value); }
java
private void updateValue(Point location) { CellPosition oldValue = value; if (location == null) { value = null; } else { int row = table.rowAtPoint(location); int column = table.columnAtPoint(location); value = new CellPosition(row, column); } maybeNotifyListeners(oldValue, value); }
[ "private", "void", "updateValue", "(", "Point", "location", ")", "{", "CellPosition", "oldValue", "=", "value", ";", "if", "(", "location", "==", "null", ")", "{", "value", "=", "null", ";", "}", "else", "{", "int", "row", "=", "table", ".", "rowAtPoin...
Updates the value of this property based on the location of the mouse pointer. @param location Location of the mouse in the relatively to the table.
[ "Updates", "the", "value", "of", "this", "property", "based", "on", "the", "location", "of", "the", "mouse", "pointer", "." ]
train
https://github.com/padrig64/ValidationFramework/blob/2dd3c7b3403993db366d24a927645f467ccd1dda/validationframework-swing/src/main/java/com/google/code/validationframework/swing/property/JTableRolloverCellProperty.java#L104-L114
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/InternalListenerIntrospector.java
InternalListenerIntrospector.validateMethod
private void validateMethod(Method method, CallbackType callbackType) { int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { String message = String.format("Method %s in class %s must be public", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } if (Modifier.isStatic(modifiers)) { String message = String.format("Method %s in class %s must not be static", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } if (Modifier.isAbstract(modifiers)) { String message = String.format("Method %s in class %s must not be abstract", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } Class<?>[] parameters = method.getParameterTypes(); if (parameters.length != 0) { String pattern = "Method %s in class %s is not a valid %s callback method. Method must not " + "have any parameters. "; String message = String.format(pattern, method.getName(), method.getDeclaringClass().getName(), callbackType); throw new EntityManagerException(message); } if (method.getReturnType() != void.class) { String message = String.format("Method %s in class %s must have a return type of %s", method.getName(), method.getDeclaringClass().getName(), void.class.getName()); throw new EntityManagerException(message); } }
java
private void validateMethod(Method method, CallbackType callbackType) { int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { String message = String.format("Method %s in class %s must be public", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } if (Modifier.isStatic(modifiers)) { String message = String.format("Method %s in class %s must not be static", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } if (Modifier.isAbstract(modifiers)) { String message = String.format("Method %s in class %s must not be abstract", method.getName(), method.getDeclaringClass().getName()); throw new EntityManagerException(message); } Class<?>[] parameters = method.getParameterTypes(); if (parameters.length != 0) { String pattern = "Method %s in class %s is not a valid %s callback method. Method must not " + "have any parameters. "; String message = String.format(pattern, method.getName(), method.getDeclaringClass().getName(), callbackType); throw new EntityManagerException(message); } if (method.getReturnType() != void.class) { String message = String.format("Method %s in class %s must have a return type of %s", method.getName(), method.getDeclaringClass().getName(), void.class.getName()); throw new EntityManagerException(message); } }
[ "private", "void", "validateMethod", "(", "Method", "method", ",", "CallbackType", "callbackType", ")", "{", "int", "modifiers", "=", "method", ".", "getModifiers", "(", ")", ";", "if", "(", "!", "Modifier", ".", "isPublic", "(", "modifiers", ")", ")", "{"...
Validates the given method to ensure if it is a valid callback method for the given event type. @param method the method to validate @param callbackType the callback type
[ "Validates", "the", "given", "method", "to", "ensure", "if", "it", "is", "a", "valid", "callback", "method", "for", "the", "given", "event", "type", "." ]
train
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/InternalListenerIntrospector.java#L113-L143
alkacon/opencms-core
src/org/opencms/xml/content/CmsXmlContent.java
CmsXmlContent.copyLocale
public void copyLocale(Locale source, Locale destination, Set<String> elements) throws CmsXmlException { if (!hasLocale(source)) { throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_NOT_AVAILABLE_1, source)); } if (hasLocale(destination)) { throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_ALREADY_EXISTS_1, destination)); } Element sourceElement = null; Element rootNode = m_document.getRootElement(); Iterator<Element> i = CmsXmlGenericWrapper.elementIterator(rootNode); String localeStr = source.toString(); while (i.hasNext()) { Element element = i.next(); String language = element.attributeValue(CmsXmlContentDefinition.XSD_ATTRIBUTE_VALUE_LANGUAGE, null); if ((language != null) && (localeStr.equals(language))) { // detach node with the locale sourceElement = createDeepElementCopy(element, elements); // there can be only one node for the locale break; } } if (sourceElement == null) { // should not happen since this was checked already, just to make sure... throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_NOT_AVAILABLE_1, source)); } // switch locale value in attribute of copied node sourceElement.addAttribute(CmsXmlContentDefinition.XSD_ATTRIBUTE_VALUE_LANGUAGE, destination.toString()); // attach the copied node to the root node rootNode.add(sourceElement); // re-initialize the document bookmarks initDocument(m_document, m_encoding, getContentDefinition()); }
java
public void copyLocale(Locale source, Locale destination, Set<String> elements) throws CmsXmlException { if (!hasLocale(source)) { throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_NOT_AVAILABLE_1, source)); } if (hasLocale(destination)) { throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_ALREADY_EXISTS_1, destination)); } Element sourceElement = null; Element rootNode = m_document.getRootElement(); Iterator<Element> i = CmsXmlGenericWrapper.elementIterator(rootNode); String localeStr = source.toString(); while (i.hasNext()) { Element element = i.next(); String language = element.attributeValue(CmsXmlContentDefinition.XSD_ATTRIBUTE_VALUE_LANGUAGE, null); if ((language != null) && (localeStr.equals(language))) { // detach node with the locale sourceElement = createDeepElementCopy(element, elements); // there can be only one node for the locale break; } } if (sourceElement == null) { // should not happen since this was checked already, just to make sure... throw new CmsXmlException( Messages.get().container(org.opencms.xml.Messages.ERR_LOCALE_NOT_AVAILABLE_1, source)); } // switch locale value in attribute of copied node sourceElement.addAttribute(CmsXmlContentDefinition.XSD_ATTRIBUTE_VALUE_LANGUAGE, destination.toString()); // attach the copied node to the root node rootNode.add(sourceElement); // re-initialize the document bookmarks initDocument(m_document, m_encoding, getContentDefinition()); }
[ "public", "void", "copyLocale", "(", "Locale", "source", ",", "Locale", "destination", ",", "Set", "<", "String", ">", "elements", ")", "throws", "CmsXmlException", "{", "if", "(", "!", "hasLocale", "(", "source", ")", ")", "{", "throw", "new", "CmsXmlExce...
Copies the content of the given source locale to the given destination locale in this XML document.<p> @param source the source locale @param destination the destination loacle @param elements the set of elements to copy @throws CmsXmlException if something goes wrong
[ "Copies", "the", "content", "of", "the", "given", "source", "locale", "to", "the", "given", "destination", "locale", "in", "this", "XML", "document", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsXmlContent.java#L400-L439
likethecolor/Alchemy-API
src/main/java/com/likethecolor/alchemy/api/parser/json/AbstractParser.java
AbstractParser.getDouble
protected Double getDouble(final String key, final JSONObject jsonObject) { Double value = null; if(hasKey(key, jsonObject)) { try { value = jsonObject.getDouble(key); } catch(JSONException e) { LOGGER.error("Could not get Double from JSONObject for key: " + key, e); } } return value; }
java
protected Double getDouble(final String key, final JSONObject jsonObject) { Double value = null; if(hasKey(key, jsonObject)) { try { value = jsonObject.getDouble(key); } catch(JSONException e) { LOGGER.error("Could not get Double from JSONObject for key: " + key, e); } } return value; }
[ "protected", "Double", "getDouble", "(", "final", "String", "key", ",", "final", "JSONObject", "jsonObject", ")", "{", "Double", "value", "=", "null", ";", "if", "(", "hasKey", "(", "key", ",", "jsonObject", ")", ")", "{", "try", "{", "value", "=", "js...
Check to make sure the JSONObject has the specified key and if so return the value as a double. If no key is found null is returned. @param key name of the field to fetch from the json object @param jsonObject object from which to fetch the value @return double value corresponding to the key or null if key not found
[ "Check", "to", "make", "sure", "the", "JSONObject", "has", "the", "specified", "key", "and", "if", "so", "return", "the", "value", "as", "a", "double", ".", "If", "no", "key", "is", "found", "null", "is", "returned", "." ]
train
https://github.com/likethecolor/Alchemy-API/blob/5208cfc92a878ceeaff052787af29da92d98db7e/src/main/java/com/likethecolor/alchemy/api/parser/json/AbstractParser.java#L142-L153
GCRC/nunaliit
nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java
JdbcUtils.extractIntResult
static public int extractIntResult(ResultSet rs, ResultSetMetaData rsmd, int index) throws Exception { int count = rsmd.getColumnCount(); if( index > count || index < 1 ) { throw new Exception("Invalid index"); } int type = rsmd.getColumnType(index); switch (type) { case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: return rs.getInt(index); } throw new Exception("Column type ("+type+") invalid for a string at index: "+index); }
java
static public int extractIntResult(ResultSet rs, ResultSetMetaData rsmd, int index) throws Exception { int count = rsmd.getColumnCount(); if( index > count || index < 1 ) { throw new Exception("Invalid index"); } int type = rsmd.getColumnType(index); switch (type) { case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: return rs.getInt(index); } throw new Exception("Column type ("+type+") invalid for a string at index: "+index); }
[ "static", "public", "int", "extractIntResult", "(", "ResultSet", "rs", ",", "ResultSetMetaData", "rsmd", ",", "int", "index", ")", "throws", "Exception", "{", "int", "count", "=", "rsmd", ".", "getColumnCount", "(", ")", ";", "if", "(", "index", ">", "coun...
This method returns an int result at a given index. @param stmt Statement that has been successfully executed @param index Index of expected column @return A value returned at the specified index @throws Exception If there is no column at index
[ "This", "method", "returns", "an", "int", "result", "at", "a", "given", "index", "." ]
train
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java#L131-L146
OpenTSDB/opentsdb
src/tools/UidManager.java
UidManager.metaPurge
private static int metaPurge(final TSDB tsdb) throws Exception { final long start_time = System.currentTimeMillis() / 1000; final long max_id = CliUtils.getMaxMetricID(tsdb); // now figure out how many IDs to divy up between the workers final int workers = Runtime.getRuntime().availableProcessors() * 2; final double quotient = (double)max_id / (double)workers; long index = 1; LOG.info("Max metric ID is [" + max_id + "]"); LOG.info("Spooling up [" + workers + "] worker threads"); final Thread[] threads = new Thread[workers]; for (int i = 0; i < workers; i++) { threads[i] = new MetaPurge(tsdb, index, quotient, i); threads[i].setName("MetaSync # " + i); threads[i].start(); index += quotient; if (index < max_id) { index++; } } // wait till we're all done for (int i = 0; i < workers; i++) { threads[i].join(); LOG.info("[" + i + "] Finished"); } // make sure buffered data is flushed to storage before exiting tsdb.flush().joinUninterruptibly(); final long duration = (System.currentTimeMillis() / 1000) - start_time; LOG.info("Completed meta data synchronization in [" + duration + "] seconds"); return 0; }
java
private static int metaPurge(final TSDB tsdb) throws Exception { final long start_time = System.currentTimeMillis() / 1000; final long max_id = CliUtils.getMaxMetricID(tsdb); // now figure out how many IDs to divy up between the workers final int workers = Runtime.getRuntime().availableProcessors() * 2; final double quotient = (double)max_id / (double)workers; long index = 1; LOG.info("Max metric ID is [" + max_id + "]"); LOG.info("Spooling up [" + workers + "] worker threads"); final Thread[] threads = new Thread[workers]; for (int i = 0; i < workers; i++) { threads[i] = new MetaPurge(tsdb, index, quotient, i); threads[i].setName("MetaSync # " + i); threads[i].start(); index += quotient; if (index < max_id) { index++; } } // wait till we're all done for (int i = 0; i < workers; i++) { threads[i].join(); LOG.info("[" + i + "] Finished"); } // make sure buffered data is flushed to storage before exiting tsdb.flush().joinUninterruptibly(); final long duration = (System.currentTimeMillis() / 1000) - start_time; LOG.info("Completed meta data synchronization in [" + duration + "] seconds"); return 0; }
[ "private", "static", "int", "metaPurge", "(", "final", "TSDB", "tsdb", ")", "throws", "Exception", "{", "final", "long", "start_time", "=", "System", ".", "currentTimeMillis", "(", ")", "/", "1000", ";", "final", "long", "max_id", "=", "CliUtils", ".", "ge...
Runs through the tsdb-uid table and removes TSMeta, UIDMeta and TSUID counter entries from the table The process is as follows: <ul><li>Fetch the max number of Metric UIDs</li> <li>Split the # of UIDs amongst worker threads</li> <li>Create a delete request with the qualifiers of any matching meta data columns</li></ul> <li>Continue on to the next unprocessed timeseries data row</li></ul> @param tsdb The tsdb to use for processing, including a search plugin @return 0 if completed successfully, something else if it dies
[ "Runs", "through", "the", "tsdb", "-", "uid", "table", "and", "removes", "TSMeta", "UIDMeta", "and", "TSUID", "counter", "entries", "from", "the", "table", "The", "process", "is", "as", "follows", ":", "<ul", ">", "<li", ">", "Fetch", "the", "max", "numb...
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tools/UidManager.java#L1055-L1091
facebook/fresco
drawee/src/main/java/com/facebook/drawee/generic/WrappingUtils.java
WrappingUtils.maybeWrapWithMatrix
@Nullable static Drawable maybeWrapWithMatrix( @Nullable Drawable drawable, @Nullable Matrix matrix) { if (drawable == null || matrix == null) { return drawable; } return new MatrixDrawable(drawable, matrix); }
java
@Nullable static Drawable maybeWrapWithMatrix( @Nullable Drawable drawable, @Nullable Matrix matrix) { if (drawable == null || matrix == null) { return drawable; } return new MatrixDrawable(drawable, matrix); }
[ "@", "Nullable", "static", "Drawable", "maybeWrapWithMatrix", "(", "@", "Nullable", "Drawable", "drawable", ",", "@", "Nullable", "Matrix", "matrix", ")", "{", "if", "(", "drawable", "==", "null", "||", "matrix", "==", "null", ")", "{", "return", "drawable",...
Wraps the given drawable with a new {@link MatrixDrawable}. <p> If the provided drawable or matrix is null, the given drawable is returned without being wrapped. @return the wrapping matrix drawable, or the original drawable if the wrapping didn't take place
[ "Wraps", "the", "given", "drawable", "with", "a", "new", "{", "@link", "MatrixDrawable", "}", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/WrappingUtils.java#L113-L121
looly/hutool
hutool-core/src/main/java/cn/hutool/core/codec/Base64Decoder.java
Base64Decoder.getNextValidDecodeByte
private static byte getNextValidDecodeByte(byte[] in, IntWrapper pos, int maxPos) { byte base64Byte; byte decodeByte; while (pos.value <= maxPos) { base64Byte = in[pos.value++]; if (base64Byte > -1) { decodeByte = DECODE_TABLE[base64Byte]; if (decodeByte > -1) { return decodeByte; } } } // padding if reached max position return PADDING; }
java
private static byte getNextValidDecodeByte(byte[] in, IntWrapper pos, int maxPos) { byte base64Byte; byte decodeByte; while (pos.value <= maxPos) { base64Byte = in[pos.value++]; if (base64Byte > -1) { decodeByte = DECODE_TABLE[base64Byte]; if (decodeByte > -1) { return decodeByte; } } } // padding if reached max position return PADDING; }
[ "private", "static", "byte", "getNextValidDecodeByte", "(", "byte", "[", "]", "in", ",", "IntWrapper", "pos", ",", "int", "maxPos", ")", "{", "byte", "base64Byte", ";", "byte", "decodeByte", ";", "while", "(", "pos", ".", "value", "<=", "maxPos", ")", "{...
获取下一个有效的byte字符 @param in 输入 @param pos 当前位置,调用此方法后此位置保持在有效字符的下一个位置 @param maxPos 最大位置 @return 有效字符,如果达到末尾返回
[ "获取下一个有效的byte字符" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/codec/Base64Decoder.java#L174-L188
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/provisioning/ContentBasedLocalBundleRepository.java
ContentBasedLocalBundleRepository.selectBaseBundle
public File selectBaseBundle(String baseLocation, final String symbolicName, final VersionRange versionRange) { readCache(); return selectResource(baseLocation, symbolicName, versionRange, true, //performURICheck=true true //selectBaseBundle=true ); }
java
public File selectBaseBundle(String baseLocation, final String symbolicName, final VersionRange versionRange) { readCache(); return selectResource(baseLocation, symbolicName, versionRange, true, //performURICheck=true true //selectBaseBundle=true ); }
[ "public", "File", "selectBaseBundle", "(", "String", "baseLocation", ",", "final", "String", "symbolicName", ",", "final", "VersionRange", "versionRange", ")", "{", "readCache", "(", ")", ";", "return", "selectResource", "(", "baseLocation", ",", "symbolicName", "...
This method can be used to obtain the 'base' bundle for a given 'selected' bundle. The {@link ContentBasedLocalBundleRepository#selectBundle} Will select a Bundle, which may or may not be an ifix. When the selectedBundle is an ifix, this method will return the corresponding bundle that has been 'ifixed'. If the selectedBundle is not an ifix, this method will return the selected bundle. @param baseLocation The base location. @param symbolicName The desired symbolic name. @param versionRange The range of versions that can be selected. @return The file representing the chosen bundle.
[ "This", "method", "can", "be", "used", "to", "obtain", "the", "base", "bundle", "for", "a", "given", "selected", "bundle", ".", "The", "{", "@link", "ContentBasedLocalBundleRepository#selectBundle", "}", "Will", "select", "a", "Bundle", "which", "may", "or", "...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/provisioning/ContentBasedLocalBundleRepository.java#L343-L349
samskivert/samskivert
src/main/java/com/samskivert/servlet/util/CookieUtil.java
CookieUtil.getCookieValue
public static String getCookieValue (HttpServletRequest req, String name) { Cookie c = getCookie(req, name); return (c == null) ? null : c.getValue(); }
java
public static String getCookieValue (HttpServletRequest req, String name) { Cookie c = getCookie(req, name); return (c == null) ? null : c.getValue(); }
[ "public", "static", "String", "getCookieValue", "(", "HttpServletRequest", "req", ",", "String", "name", ")", "{", "Cookie", "c", "=", "getCookie", "(", "req", ",", "name", ")", ";", "return", "(", "c", "==", "null", ")", "?", "null", ":", "c", ".", ...
Get the value of the cookie for the cookie of the specified name, or null if not found.
[ "Get", "the", "value", "of", "the", "cookie", "for", "the", "cookie", "of", "the", "specified", "name", "or", "null", "if", "not", "found", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/servlet/util/CookieUtil.java#L37-L41
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseSparseNDArrayCOO.java
BaseSparseNDArrayCOO.indexesBinarySearch
public int indexesBinarySearch(int lowerBound, int upperBound, int[] idx) { int min = lowerBound; int max = upperBound; int mid = (max + min) / 2; int[] midIdx = getUnderlyingIndicesOf(mid).asInt(); if (Arrays.equals(idx, midIdx)) { return mid; } if (ArrayUtil.lessThan(idx, midIdx)) { max = mid; } if (ArrayUtil.greaterThan(idx, midIdx)) { min = mid; } if (min == max) { return -1; } return indexesBinarySearch(min, max, idx); }
java
public int indexesBinarySearch(int lowerBound, int upperBound, int[] idx) { int min = lowerBound; int max = upperBound; int mid = (max + min) / 2; int[] midIdx = getUnderlyingIndicesOf(mid).asInt(); if (Arrays.equals(idx, midIdx)) { return mid; } if (ArrayUtil.lessThan(idx, midIdx)) { max = mid; } if (ArrayUtil.greaterThan(idx, midIdx)) { min = mid; } if (min == max) { return -1; } return indexesBinarySearch(min, max, idx); }
[ "public", "int", "indexesBinarySearch", "(", "int", "lowerBound", ",", "int", "upperBound", ",", "int", "[", "]", "idx", ")", "{", "int", "min", "=", "lowerBound", ";", "int", "max", "=", "upperBound", ";", "int", "mid", "=", "(", "max", "+", "min", ...
Return the position of the idx array into the indexes buffer between the lower and upper bound. @param idx a set of coordinates @param lowerBound the lower bound of the position @param upperBound the upper bound of the position @return the position of the idx array into the indexes buffers, which corresponds to the position of the corresponding value in the values data.
[ "Return", "the", "position", "of", "the", "idx", "array", "into", "the", "indexes", "buffer", "between", "the", "lower", "and", "upper", "bound", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseSparseNDArrayCOO.java#L631-L650
lkwg82/enforcer-rules
src/main/java/org/apache/maven/plugins/enforcer/RequireActiveProfile.java
RequireActiveProfile.isProfileActive
protected boolean isProfileActive( MavenProject project, String profileName ) { @SuppressWarnings( "unchecked" ) List<Profile> activeProfiles = project.getActiveProfiles(); if ( activeProfiles != null && !activeProfiles.isEmpty() ) { for ( Profile profile : activeProfiles ) { if ( profile.getId().equals( profileName ) ) { return true; } } } return false; }
java
protected boolean isProfileActive( MavenProject project, String profileName ) { @SuppressWarnings( "unchecked" ) List<Profile> activeProfiles = project.getActiveProfiles(); if ( activeProfiles != null && !activeProfiles.isEmpty() ) { for ( Profile profile : activeProfiles ) { if ( profile.getId().equals( profileName ) ) { return true; } } } return false; }
[ "protected", "boolean", "isProfileActive", "(", "MavenProject", "project", ",", "String", "profileName", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "List", "<", "Profile", ">", "activeProfiles", "=", "project", ".", "getActiveProfiles", "(", ")"...
Checks if profile is active. @param project the project @param profileName the profile name @return <code>true</code> if profile is active, otherwise <code>false</code>
[ "Checks", "if", "profile", "is", "active", "." ]
train
https://github.com/lkwg82/enforcer-rules/blob/fa2d309af7907b17fc8eaf386f8056d77b654749/src/main/java/org/apache/maven/plugins/enforcer/RequireActiveProfile.java#L151-L167
linkedin/linkedin-zookeeper
org.linkedin.zookeeper-impl/src/main/java/org/linkedin/zookeeper/client/AbstractZKClient.java
AbstractZKClient.createOrSetWithParents
@Override public Stat createOrSetWithParents(String path, String data, List<ACL> acl, CreateMode createMode) throws InterruptedException, KeeperException { if(exists(path) != null) return setData(path, data); try { createWithParents(path, data, acl, createMode); return null; } catch(KeeperException.NodeExistsException e) { // this should not happen very often (race condition) return setData(path, data); } }
java
@Override public Stat createOrSetWithParents(String path, String data, List<ACL> acl, CreateMode createMode) throws InterruptedException, KeeperException { if(exists(path) != null) return setData(path, data); try { createWithParents(path, data, acl, createMode); return null; } catch(KeeperException.NodeExistsException e) { // this should not happen very often (race condition) return setData(path, data); } }
[ "@", "Override", "public", "Stat", "createOrSetWithParents", "(", "String", "path", ",", "String", "data", ",", "List", "<", "ACL", ">", "acl", ",", "CreateMode", "createMode", ")", "throws", "InterruptedException", ",", "KeeperException", "{", "if", "(", "exi...
Tries to create first and if the node exists, then does a setData. @return <code>null</code> if create worked, otherwise the result of setData
[ "Tries", "to", "create", "first", "and", "if", "the", "node", "exists", "then", "does", "a", "setData", "." ]
train
https://github.com/linkedin/linkedin-zookeeper/blob/600b1d01318594ed425ede566bbbdc94b026a53e/org.linkedin.zookeeper-impl/src/main/java/org/linkedin/zookeeper/client/AbstractZKClient.java#L233-L251
openengsb/openengsb
api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java
TransformationDescription.concatField
public void concatField(String targetField, String concatString, String... sourceFields) { TransformationStep step = new TransformationStep(); step.setTargetField(targetField); step.setSourceFields(sourceFields); step.setOperationParameter(TransformationConstants.CONCAT_PARAM, concatString); step.setOperationName("concat"); steps.add(step); }
java
public void concatField(String targetField, String concatString, String... sourceFields) { TransformationStep step = new TransformationStep(); step.setTargetField(targetField); step.setSourceFields(sourceFields); step.setOperationParameter(TransformationConstants.CONCAT_PARAM, concatString); step.setOperationName("concat"); steps.add(step); }
[ "public", "void", "concatField", "(", "String", "targetField", ",", "String", "concatString", ",", "String", "...", "sourceFields", ")", "{", "TransformationStep", "step", "=", "new", "TransformationStep", "(", ")", ";", "step", ".", "setTargetField", "(", "targ...
Adds a concat transformation step to the transformation description. The values of the source fields are concatenated to the target field with the concat string between the source fields values. All fields need to be of the type String.
[ "Adds", "a", "concat", "transformation", "step", "to", "the", "transformation", "description", ".", "The", "values", "of", "the", "source", "fields", "are", "concatenated", "to", "the", "target", "field", "with", "the", "concat", "string", "between", "the", "s...
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java#L81-L88
libgdx/gdx-ai
gdx-ai/src/com/badlogic/gdx/ai/msg/MessageDispatcher.java
MessageDispatcher.addListener
public void addListener (Telegraph listener, int msg) { Array<Telegraph> listeners = msgListeners.get(msg); if (listeners == null) { // Associate an empty unordered array with the message code listeners = new Array<Telegraph>(false, 16); msgListeners.put(msg, listeners); } listeners.add(listener); // Dispatch messages from registered providers Array<TelegramProvider> providers = msgProviders.get(msg); if (providers != null) { for (int i = 0, n = providers.size; i < n; i++) { TelegramProvider provider = providers.get(i); Object info = provider.provideMessageInfo(msg, listener); if (info != null) { Telegraph sender = ClassReflection.isInstance(Telegraph.class, provider) ? (Telegraph)provider : null; dispatchMessage(0, sender, listener, msg, info, false); } } } }
java
public void addListener (Telegraph listener, int msg) { Array<Telegraph> listeners = msgListeners.get(msg); if (listeners == null) { // Associate an empty unordered array with the message code listeners = new Array<Telegraph>(false, 16); msgListeners.put(msg, listeners); } listeners.add(listener); // Dispatch messages from registered providers Array<TelegramProvider> providers = msgProviders.get(msg); if (providers != null) { for (int i = 0, n = providers.size; i < n; i++) { TelegramProvider provider = providers.get(i); Object info = provider.provideMessageInfo(msg, listener); if (info != null) { Telegraph sender = ClassReflection.isInstance(Telegraph.class, provider) ? (Telegraph)provider : null; dispatchMessage(0, sender, listener, msg, info, false); } } } }
[ "public", "void", "addListener", "(", "Telegraph", "listener", ",", "int", "msg", ")", "{", "Array", "<", "Telegraph", ">", "listeners", "=", "msgListeners", ".", "get", "(", "msg", ")", ";", "if", "(", "listeners", "==", "null", ")", "{", "// Associate ...
Registers a listener for the specified message code. Messages without an explicit receiver are broadcasted to all its registered listeners. @param listener the listener to add @param msg the message code
[ "Registers", "a", "listener", "for", "the", "specified", "message", "code", ".", "Messages", "without", "an", "explicit", "receiver", "are", "broadcasted", "to", "all", "its", "registered", "listeners", "." ]
train
https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/msg/MessageDispatcher.java#L69-L90
sagiegurari/fax4j
src/main/java/org/fax4j/util/AbstractProcessExecutor.java
AbstractProcessExecutor.executeProcess
public ProcessOutput executeProcess(ConfigurationHolder configurationHolder,String command) throws IOException,InterruptedException { //validate command provided if((command==null)||(command.length()==0)) { throw new FaxException("Command not provided."); } //trim command and validate String updatedCommand=command.trim(); if(updatedCommand.length()==0) { throw new FaxException("Command not provided."); } //validate configuration holder provided if(configurationHolder==null) { throw new FaxException("Configuration holder not provided."); } this.LOGGER.logDebug(new Object[]{"Invoking command: ",updatedCommand},null); //execute process ProcessOutput processOutput=this.executeProcessImpl(configurationHolder,updatedCommand); int exitCode=processOutput.getExitCode(); String outputText=processOutput.getOutputText(); String errorText=processOutput.getErrorText(); this.LOGGER.logDebug(new Object[]{"Invoked command: ",updatedCommand," Exit Code: ",String.valueOf(exitCode),Logger.SYSTEM_EOL,"Output Text:",Logger.SYSTEM_EOL,outputText,Logger.SYSTEM_EOL,"Error Text:",Logger.SYSTEM_EOL,errorText},null); return processOutput; }
java
public ProcessOutput executeProcess(ConfigurationHolder configurationHolder,String command) throws IOException,InterruptedException { //validate command provided if((command==null)||(command.length()==0)) { throw new FaxException("Command not provided."); } //trim command and validate String updatedCommand=command.trim(); if(updatedCommand.length()==0) { throw new FaxException("Command not provided."); } //validate configuration holder provided if(configurationHolder==null) { throw new FaxException("Configuration holder not provided."); } this.LOGGER.logDebug(new Object[]{"Invoking command: ",updatedCommand},null); //execute process ProcessOutput processOutput=this.executeProcessImpl(configurationHolder,updatedCommand); int exitCode=processOutput.getExitCode(); String outputText=processOutput.getOutputText(); String errorText=processOutput.getErrorText(); this.LOGGER.logDebug(new Object[]{"Invoked command: ",updatedCommand," Exit Code: ",String.valueOf(exitCode),Logger.SYSTEM_EOL,"Output Text:",Logger.SYSTEM_EOL,outputText,Logger.SYSTEM_EOL,"Error Text:",Logger.SYSTEM_EOL,errorText},null); return processOutput; }
[ "public", "ProcessOutput", "executeProcess", "(", "ConfigurationHolder", "configurationHolder", ",", "String", "command", ")", "throws", "IOException", ",", "InterruptedException", "{", "//validate command provided", "if", "(", "(", "command", "==", "null", ")", "||", ...
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/AbstractProcessExecutor.java#L49-L82
netplex/json-smart-v2
json-smart/src/main/java/net/minidev/json/parser/JSONParser.java
JSONParser.parse
public <T> T parse(byte[] in, JsonReaderI<T> mapper) throws ParseException { return getPBytes().parse(in, mapper); }
java
public <T> T parse(byte[] in, JsonReaderI<T> mapper) throws ParseException { return getPBytes().parse(in, mapper); }
[ "public", "<", "T", ">", "T", "parse", "(", "byte", "[", "]", "in", ",", "JsonReaderI", "<", "T", ">", "mapper", ")", "throws", "ParseException", "{", "return", "getPBytes", "(", ")", ".", "parse", "(", "in", ",", "mapper", ")", ";", "}" ]
use to return Primitive Type, or String, Or JsonObject or JsonArray generated by a ContainerFactory
[ "use", "to", "return", "Primitive", "Type", "or", "String", "Or", "JsonObject", "or", "JsonArray", "generated", "by", "a", "ContainerFactory" ]
train
https://github.com/netplex/json-smart-v2/blob/bfb3daef039e22a7bbff5f76bf14ea23330cd70e/json-smart/src/main/java/net/minidev/json/parser/JSONParser.java#L197-L199
msgpack/msgpack-java
msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java
MessageUnpacker.unpackBoolean
public boolean unpackBoolean() throws IOException { byte b = readByte(); if (b == Code.FALSE) { return false; } else if (b == Code.TRUE) { return true; } throw unexpected("boolean", b); }
java
public boolean unpackBoolean() throws IOException { byte b = readByte(); if (b == Code.FALSE) { return false; } else if (b == Code.TRUE) { return true; } throw unexpected("boolean", b); }
[ "public", "boolean", "unpackBoolean", "(", ")", "throws", "IOException", "{", "byte", "b", "=", "readByte", "(", ")", ";", "if", "(", "b", "==", "Code", ".", "FALSE", ")", "{", "return", "false", ";", "}", "else", "if", "(", "b", "==", "Code", ".",...
Reads true or false. @return the read value @throws MessageTypeException when value is not MessagePack Boolean type @throws IOException when underlying input throws IOException
[ "Reads", "true", "or", "false", "." ]
train
https://github.com/msgpack/msgpack-java/blob/16e370e348215a72a14c210b42d448d513aee015/msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java#L766-L777
Azure/azure-sdk-for-java
mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/AssetFiltersInner.java
AssetFiltersInner.createOrUpdate
public AssetFilterInner createOrUpdate(String resourceGroupName, String accountName, String assetName, String filterName, AssetFilterInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, assetName, filterName, parameters).toBlocking().single().body(); }
java
public AssetFilterInner createOrUpdate(String resourceGroupName, String accountName, String assetName, String filterName, AssetFilterInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, assetName, filterName, parameters).toBlocking().single().body(); }
[ "public", "AssetFilterInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "assetName", ",", "String", "filterName", ",", "AssetFilterInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", ...
Create or update an Asset Filter. Creates or updates an Asset Filter associated with the specified Asset. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @param assetName The Asset name. @param filterName The Asset Filter name @param parameters The request parameters @throws IllegalArgumentException thrown if parameters fail the validation @throws ApiErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the AssetFilterInner object if successful.
[ "Create", "or", "update", "an", "Asset", "Filter", ".", "Creates", "or", "updates", "an", "Asset", "Filter", "associated", "with", "the", "specified", "Asset", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/AssetFiltersInner.java#L346-L348
Azure/azure-sdk-for-java
postgresql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/postgresql/v2017_12_01/implementation/FirewallRulesInner.java
FirewallRulesInner.beginCreateOrUpdate
public FirewallRuleInner beginCreateOrUpdate(String resourceGroupName, String serverName, String firewallRuleName, FirewallRuleInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, firewallRuleName, parameters).toBlocking().single().body(); }
java
public FirewallRuleInner beginCreateOrUpdate(String resourceGroupName, String serverName, String firewallRuleName, FirewallRuleInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, firewallRuleName, parameters).toBlocking().single().body(); }
[ "public", "FirewallRuleInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "firewallRuleName", ",", "FirewallRuleInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceG...
Creates a new firewall rule or updates an existing firewall rule. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param firewallRuleName The name of the server firewall rule. @param parameters The required parameters for creating or updating a firewall rule. @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 FirewallRuleInner object if successful.
[ "Creates", "a", "new", "firewall", "rule", "or", "updates", "an", "existing", "firewall", "rule", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/postgresql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/postgresql/v2017_12_01/implementation/FirewallRulesInner.java#L181-L183
nmorel/gwt-jackson
gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/ser/bean/BeanPropertySerializer.java
BeanPropertySerializer.serializePropertyName
public void serializePropertyName( JsonWriter writer, T bean, JsonSerializationContext ctx ) { writer.unescapeName( propertyName ); }
java
public void serializePropertyName( JsonWriter writer, T bean, JsonSerializationContext ctx ) { writer.unescapeName( propertyName ); }
[ "public", "void", "serializePropertyName", "(", "JsonWriter", "writer", ",", "T", "bean", ",", "JsonSerializationContext", "ctx", ")", "{", "writer", ".", "unescapeName", "(", "propertyName", ")", ";", "}" ]
Serializes the property name @param writer writer @param bean bean containing the property to serialize @param ctx context of the serialization process
[ "Serializes", "the", "property", "name" ]
train
https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/ser/bean/BeanPropertySerializer.java#L82-L84
elki-project/elki
elki-timeseries/src/main/java/de/lmu/ifi/dbs/elki/algorithm/timeseries/OfflineChangePointDetectionAlgorithm.java
OfflineChangePointDetectionAlgorithm.bestChangeInMean
public static DoubleIntPair bestChangeInMean(double[] sums, int begin, int end) { final int len = end - begin, last = end - 1; final double suml = begin > 0 ? sums[begin - 1] : 0.; final double sumr = sums[last]; int bestpos = begin; double bestscore = Double.NEGATIVE_INFINITY; // Iterate elements k=2..n-1 in math notation_ for(int j = begin, km1 = 1; j < last; j++, km1++) { assert (km1 < len); // FIXME: remove eventually final double sumj = sums[j]; // Sum _inclusive_ j'th element. // Derive the left mean and right mean from the precomputed aggregates: final double lmean = (sumj - suml) / km1; final double rmean = (sumr - sumj) / (len - km1); // Equation 2.6.17 from the Basseville book final double dm = lmean - rmean; final double score = km1 * (double) (len - km1) * dm * dm; if(score > bestscore) { bestpos = j + 1; bestscore = score; } } return new DoubleIntPair(bestscore, bestpos); }
java
public static DoubleIntPair bestChangeInMean(double[] sums, int begin, int end) { final int len = end - begin, last = end - 1; final double suml = begin > 0 ? sums[begin - 1] : 0.; final double sumr = sums[last]; int bestpos = begin; double bestscore = Double.NEGATIVE_INFINITY; // Iterate elements k=2..n-1 in math notation_ for(int j = begin, km1 = 1; j < last; j++, km1++) { assert (km1 < len); // FIXME: remove eventually final double sumj = sums[j]; // Sum _inclusive_ j'th element. // Derive the left mean and right mean from the precomputed aggregates: final double lmean = (sumj - suml) / km1; final double rmean = (sumr - sumj) / (len - km1); // Equation 2.6.17 from the Basseville book final double dm = lmean - rmean; final double score = km1 * (double) (len - km1) * dm * dm; if(score > bestscore) { bestpos = j + 1; bestscore = score; } } return new DoubleIntPair(bestscore, bestpos); }
[ "public", "static", "DoubleIntPair", "bestChangeInMean", "(", "double", "[", "]", "sums", ",", "int", "begin", ",", "int", "end", ")", "{", "final", "int", "len", "=", "end", "-", "begin", ",", "last", "=", "end", "-", "1", ";", "final", "double", "s...
Find the best position to assume a change in mean. @param sums Cumulative sums @param begin Interval begin @param end Interval end @return Best change position
[ "Find", "the", "best", "position", "to", "assume", "a", "change", "in", "mean", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-timeseries/src/main/java/de/lmu/ifi/dbs/elki/algorithm/timeseries/OfflineChangePointDetectionAlgorithm.java#L295-L318
SonarSource/sonarqube
sonar-core/src/main/java/org/sonar/core/i18n/DefaultI18n.java
DefaultI18n.messageFromFile
String messageFromFile(Locale locale, String filename, String relatedProperty) { String result = null; String bundleBase = propertyToBundles.get(relatedProperty); if (bundleBase == null) { // this property has no translation return null; } String filePath = bundleBase.replace('.', '/'); if (!"en".equals(locale.getLanguage())) { filePath += "_" + locale.getLanguage(); } filePath += "/" + filename; InputStream input = classloader.getResourceAsStream(filePath); if (input != null) { result = readInputStream(filePath, input); } return result; }
java
String messageFromFile(Locale locale, String filename, String relatedProperty) { String result = null; String bundleBase = propertyToBundles.get(relatedProperty); if (bundleBase == null) { // this property has no translation return null; } String filePath = bundleBase.replace('.', '/'); if (!"en".equals(locale.getLanguage())) { filePath += "_" + locale.getLanguage(); } filePath += "/" + filename; InputStream input = classloader.getResourceAsStream(filePath); if (input != null) { result = readInputStream(filePath, input); } return result; }
[ "String", "messageFromFile", "(", "Locale", "locale", ",", "String", "filename", ",", "String", "relatedProperty", ")", "{", "String", "result", "=", "null", ";", "String", "bundleBase", "=", "propertyToBundles", ".", "get", "(", "relatedProperty", ")", ";", "...
Only the given locale is searched. Contrary to java.util.ResourceBundle, no strategy for locating the bundle is implemented in this method.
[ "Only", "the", "given", "locale", "is", "searched", ".", "Contrary", "to", "java", ".", "util", ".", "ResourceBundle", "no", "strategy", "for", "locating", "the", "bundle", "is", "implemented", "in", "this", "method", "." ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-core/src/main/java/org/sonar/core/i18n/DefaultI18n.java#L193-L211
liferay/com-liferay-commerce
commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountPersistenceImpl.java
CommerceDiscountPersistenceImpl.findByG_C
@Override public List<CommerceDiscount> findByG_C(long groupId, String couponCode, int start, int end) { return findByG_C(groupId, couponCode, start, end, null); }
java
@Override public List<CommerceDiscount> findByG_C(long groupId, String couponCode, int start, int end) { return findByG_C(groupId, couponCode, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceDiscount", ">", "findByG_C", "(", "long", "groupId", ",", "String", "couponCode", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByG_C", "(", "groupId", ",", "couponCode", ",", "start", ","...
Returns a range of all the commerce discounts where groupId = &#63; and couponCode = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceDiscountModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param groupId the group ID @param couponCode the coupon code @param start the lower bound of the range of commerce discounts @param end the upper bound of the range of commerce discounts (not inclusive) @return the range of matching commerce discounts
[ "Returns", "a", "range", "of", "all", "the", "commerce", "discounts", "where", "groupId", "=", "&#63", ";", "and", "couponCode", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountPersistenceImpl.java#L2405-L2409
lessthanoptimal/ejml
main/ejml-simple/src/org/ejml/simple/SimpleBase.java
SimpleBase.extractMatrix
public T extractMatrix(int y0 , int y1, int x0 , int x1 ) { if( y0 == SimpleMatrix.END ) y0 = mat.getNumRows(); if( y1 == SimpleMatrix.END ) y1 = mat.getNumRows(); if( x0 == SimpleMatrix.END ) x0 = mat.getNumCols(); if( x1 == SimpleMatrix.END ) x1 = mat.getNumCols(); T ret = createMatrix(y1-y0,x1-x0, mat.getType()); ops.extract(mat, y0, y1, x0, x1, ret.mat, 0, 0); return ret; }
java
public T extractMatrix(int y0 , int y1, int x0 , int x1 ) { if( y0 == SimpleMatrix.END ) y0 = mat.getNumRows(); if( y1 == SimpleMatrix.END ) y1 = mat.getNumRows(); if( x0 == SimpleMatrix.END ) x0 = mat.getNumCols(); if( x1 == SimpleMatrix.END ) x1 = mat.getNumCols(); T ret = createMatrix(y1-y0,x1-x0, mat.getType()); ops.extract(mat, y0, y1, x0, x1, ret.mat, 0, 0); return ret; }
[ "public", "T", "extractMatrix", "(", "int", "y0", ",", "int", "y1", ",", "int", "x0", ",", "int", "x1", ")", "{", "if", "(", "y0", "==", "SimpleMatrix", ".", "END", ")", "y0", "=", "mat", ".", "getNumRows", "(", ")", ";", "if", "(", "y1", "==",...
<p> Creates a new SimpleMatrix which is a submatrix of this matrix. </p> <p> s<sub>i-y0 , j-x0</sub> = o<sub>ij</sub> for all y0 &le; i &lt; y1 and x0 &le; j &lt; x1<br> <br> where 's<sub>ij</sub>' is an element in the submatrix and 'o<sub>ij</sub>' is an element in the original matrix. </p> <p> If any of the inputs are set to SimpleMatrix.END then it will be set to the last row or column in the matrix. </p> @param y0 Start row. @param y1 Stop row + 1. @param x0 Start column. @param x1 Stop column + 1. @return The submatrix.
[ "<p", ">", "Creates", "a", "new", "SimpleMatrix", "which", "is", "a", "submatrix", "of", "this", "matrix", ".", "<", "/", "p", ">", "<p", ">", "s<sub", ">", "i", "-", "y0", "j", "-", "x0<", "/", "sub", ">", "=", "o<sub", ">", "ij<", "/", "sub",...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-simple/src/org/ejml/simple/SimpleBase.java#L851-L862
aspectran/aspectran
shell/src/main/java/com/aspectran/shell/command/option/DefaultOptionParser.java
DefaultOptionParser.handleUnknownToken
private void handleUnknownToken(String token) throws OptionParserException { if (token.startsWith("-") && token.length() > 1 && !skipParsingAtNonOption) { throw new UnrecognizedOptionException("Unrecognized option: " + token, token); } parsedOptions.addArg(token); }
java
private void handleUnknownToken(String token) throws OptionParserException { if (token.startsWith("-") && token.length() > 1 && !skipParsingAtNonOption) { throw new UnrecognizedOptionException("Unrecognized option: " + token, token); } parsedOptions.addArg(token); }
[ "private", "void", "handleUnknownToken", "(", "String", "token", ")", "throws", "OptionParserException", "{", "if", "(", "token", ".", "startsWith", "(", "\"-\"", ")", "&&", "token", ".", "length", "(", ")", ">", "1", "&&", "!", "skipParsingAtNonOption", ")"...
Handles an unknown token. If the token starts with a dash an UnrecognizedOptionException is thrown. Otherwise the token is added to the arguments of the command line. If the skipParsingAtNonOption flag is set, this stops the parsing and the remaining tokens are added as-is in the arguments of the command line. @param token the command line token to handle @throws OptionParserException if option parsing fails
[ "Handles", "an", "unknown", "token", ".", "If", "the", "token", "starts", "with", "a", "dash", "an", "UnrecognizedOptionException", "is", "thrown", ".", "Otherwise", "the", "token", "is", "added", "to", "the", "arguments", "of", "the", "command", "line", "."...
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/shell/src/main/java/com/aspectran/shell/command/option/DefaultOptionParser.java#L392-L397
alkacon/opencms-core
src/org/opencms/search/documents/CmsDocumentDependency.java
CmsDocumentDependency.toJSON
public JSONObject toJSON(CmsObject cms, boolean includeLang) { try { CmsObject clone = OpenCms.initCmsObject(cms); clone.getRequestContext().setSiteRoot(""); JSONObject jsonAttachment = new JSONObject(); CmsResource res = clone.readResource(m_rootPath, CmsResourceFilter.IGNORE_EXPIRATION); Map<String, String> props = CmsProperty.toMap(clone.readPropertyObjects(res, false)); // id and path jsonAttachment.put(JSON_UUID, res.getStructureId()); jsonAttachment.put(JSON_PATH, res.getRootPath()); // title jsonAttachment.put(JSON_TITLE, props.get(CmsPropertyDefinition.PROPERTY_TITLE)); // date created jsonAttachment.put(JSON_DATE_CREATED, res.getDateCreated()); // date created jsonAttachment.put(JSON_LOCALE, m_locale); // date modified jsonAttachment.put(JSON_DATE_MODIFIED, res.getDateLastModified()); if (includeLang) { // get all language versions of the document List<CmsDocumentDependency> langs = getVariants(); if (langs != null) { JSONArray jsonLanguages = new JSONArray(); for (CmsDocumentDependency lang : langs) { JSONObject jsonLanguage = lang.toJSON(cms, false); jsonLanguages.put(jsonLanguage); } jsonAttachment.put(JSON_LANGUAGES, jsonLanguages); } } return jsonAttachment; } catch (Exception ex) { LOG.error(ex.getLocalizedMessage(), ex); } return null; }
java
public JSONObject toJSON(CmsObject cms, boolean includeLang) { try { CmsObject clone = OpenCms.initCmsObject(cms); clone.getRequestContext().setSiteRoot(""); JSONObject jsonAttachment = new JSONObject(); CmsResource res = clone.readResource(m_rootPath, CmsResourceFilter.IGNORE_EXPIRATION); Map<String, String> props = CmsProperty.toMap(clone.readPropertyObjects(res, false)); // id and path jsonAttachment.put(JSON_UUID, res.getStructureId()); jsonAttachment.put(JSON_PATH, res.getRootPath()); // title jsonAttachment.put(JSON_TITLE, props.get(CmsPropertyDefinition.PROPERTY_TITLE)); // date created jsonAttachment.put(JSON_DATE_CREATED, res.getDateCreated()); // date created jsonAttachment.put(JSON_LOCALE, m_locale); // date modified jsonAttachment.put(JSON_DATE_MODIFIED, res.getDateLastModified()); if (includeLang) { // get all language versions of the document List<CmsDocumentDependency> langs = getVariants(); if (langs != null) { JSONArray jsonLanguages = new JSONArray(); for (CmsDocumentDependency lang : langs) { JSONObject jsonLanguage = lang.toJSON(cms, false); jsonLanguages.put(jsonLanguage); } jsonAttachment.put(JSON_LANGUAGES, jsonLanguages); } } return jsonAttachment; } catch (Exception ex) { LOG.error(ex.getLocalizedMessage(), ex); } return null; }
[ "public", "JSONObject", "toJSON", "(", "CmsObject", "cms", ",", "boolean", "includeLang", ")", "{", "try", "{", "CmsObject", "clone", "=", "OpenCms", ".", "initCmsObject", "(", "cms", ")", ";", "clone", ".", "getRequestContext", "(", ")", ".", "setSiteRoot",...
Returns a JSON object describing this dependency document.<p> @param cms the current cms object @param includeLang flag if language versions should be included @return a JSON object describing this dependency document
[ "Returns", "a", "JSON", "object", "describing", "this", "dependency", "document", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/documents/CmsDocumentDependency.java#L957-L995
Azure/azure-sdk-for-java
kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java
DatabasesInner.beginUpdateAsync
public Observable<DatabaseInner> beginUpdateAsync(String resourceGroupName, String clusterName, String databaseName, DatabaseUpdate parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, clusterName, databaseName, parameters).map(new Func1<ServiceResponse<DatabaseInner>, DatabaseInner>() { @Override public DatabaseInner call(ServiceResponse<DatabaseInner> response) { return response.body(); } }); }
java
public Observable<DatabaseInner> beginUpdateAsync(String resourceGroupName, String clusterName, String databaseName, DatabaseUpdate parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, clusterName, databaseName, parameters).map(new Func1<ServiceResponse<DatabaseInner>, DatabaseInner>() { @Override public DatabaseInner call(ServiceResponse<DatabaseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DatabaseInner", ">", "beginUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "clusterName", ",", "String", "databaseName", ",", "DatabaseUpdate", "parameters", ")", "{", "return", "beginUpdateWithServiceResponseAsync", "(", "...
Updates a database. @param resourceGroupName The name of the resource group containing the Kusto cluster. @param clusterName The name of the Kusto cluster. @param databaseName The name of the database in the Kusto cluster. @param parameters The database parameters supplied to the Update operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DatabaseInner object
[ "Updates", "a", "database", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java#L705-L712
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalBigDecimal
public BigDecimal getInternalBigDecimal(ColumnInformation columnInfo) { if (lastValueWasNull()) { return null; } if (columnInfo.getColumnType() == ColumnType.BIT) { return BigDecimal.valueOf(parseBit()); } return new BigDecimal(new String(buf, pos, length, StandardCharsets.UTF_8)); }
java
public BigDecimal getInternalBigDecimal(ColumnInformation columnInfo) { if (lastValueWasNull()) { return null; } if (columnInfo.getColumnType() == ColumnType.BIT) { return BigDecimal.valueOf(parseBit()); } return new BigDecimal(new String(buf, pos, length, StandardCharsets.UTF_8)); }
[ "public", "BigDecimal", "getInternalBigDecimal", "(", "ColumnInformation", "columnInfo", ")", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "columnInfo", ".", "getColumnType", "(", ")", "==", "ColumnType", ".", ...
Get BigDecimal from raw text format. @param columnInfo column information @return BigDecimal value
[ "Get", "BigDecimal", "from", "raw", "text", "format", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L442-L451
jamesagnew/hapi-fhir
hapi-fhir-utilities/src/main/java/org/hl7/fhir/utilities/IniFile.java
IniFile.utilDateToStr
private String utilDateToStr(Date pdt, String pstrFmt) { String strRet = null; SimpleDateFormat dtFmt = null; try { dtFmt = new SimpleDateFormat(pstrFmt); strRet = dtFmt.format(pdt); } catch (Exception e) { strRet = null; } finally { if (dtFmt != null) dtFmt = null; } return strRet; }
java
private String utilDateToStr(Date pdt, String pstrFmt) { String strRet = null; SimpleDateFormat dtFmt = null; try { dtFmt = new SimpleDateFormat(pstrFmt); strRet = dtFmt.format(pdt); } catch (Exception e) { strRet = null; } finally { if (dtFmt != null) dtFmt = null; } return strRet; }
[ "private", "String", "utilDateToStr", "(", "Date", "pdt", ",", "String", "pstrFmt", ")", "{", "String", "strRet", "=", "null", ";", "SimpleDateFormat", "dtFmt", "=", "null", ";", "try", "{", "dtFmt", "=", "new", "SimpleDateFormat", "(", "pstrFmt", ")", ";"...
Converts a java.util.date into String @param pd Date that need to be converted to String @param pstrFmt The date format pattern. @return String
[ "Converts", "a", "java", ".", "util", ".", "date", "into", "String" ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-utilities/src/main/java/org/hl7/fhir/utilities/IniFile.java#L1099-L1118
xwiki/xwiki-rendering
xwiki-rendering-transformations/xwiki-rendering-transformation-icon/src/main/java/org/xwiki/rendering/internal/transformation/icon/IconTransformation.java
IconTransformation.indexOf
private int indexOf(List<Block> targetBlocks, Block block) { int pos = 0; for (Block targetBlock : targetBlocks) { // Test a non deep equality if (blockEquals(targetBlock, block)) { return pos; } pos++; } return -1; }
java
private int indexOf(List<Block> targetBlocks, Block block) { int pos = 0; for (Block targetBlock : targetBlocks) { // Test a non deep equality if (blockEquals(targetBlock, block)) { return pos; } pos++; } return -1; }
[ "private", "int", "indexOf", "(", "List", "<", "Block", ">", "targetBlocks", ",", "Block", "block", ")", "{", "int", "pos", "=", "0", ";", "for", "(", "Block", "targetBlock", ":", "targetBlocks", ")", "{", "// Test a non deep equality", "if", "(", "blockEq...
Shallow indexOf implementation that only compares nodes based on their data and not their children data. @param targetBlocks the list of blocks to look into @param block the block to look for in the list of passed blocks @return the position of the block in the list of target blocks and -1 if not found
[ "Shallow", "indexOf", "implementation", "that", "only", "compares", "nodes", "based", "on", "their", "data", "and", "not", "their", "children", "data", "." ]
train
https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-transformations/xwiki-rendering-transformation-icon/src/main/java/org/xwiki/rendering/internal/transformation/icon/IconTransformation.java#L176-L187
onepf/OpenIAB
library/src/main/java/org/onepf/oms/SkuManager.java
SkuManager.mapSku
@NotNull public SkuManager mapSku(String sku, String storeName, @NotNull String storeSku) { checkSkuMappingParams(sku, storeName, storeSku); Map<String, String> skuMap = sku2storeSkuMappings.get(storeName); if (skuMap == null) { skuMap = new HashMap<String, String>(); sku2storeSkuMappings.put(storeName, skuMap); } else if (skuMap.containsKey(sku)) { throw new SkuMappingException("Already specified SKU. sku: " + sku + " -> storeSku: " + skuMap.get(sku)); } Map<String, String> storeSkuMap = storeSku2skuMappings.get(storeName); if (storeSkuMap == null) { storeSkuMap = new HashMap<String, String>(); storeSku2skuMappings.put(storeName, storeSkuMap); } else if (storeSkuMap.get(storeSku) != null) { throw new SkuMappingException("Ambiguous SKU mapping. You try to map sku: " + sku + " -> storeSku: " + storeSku + ", that is already mapped to sku: " + storeSkuMap.get(storeSku)); } skuMap.put(sku, storeSku); storeSkuMap.put(storeSku, sku); return this; }
java
@NotNull public SkuManager mapSku(String sku, String storeName, @NotNull String storeSku) { checkSkuMappingParams(sku, storeName, storeSku); Map<String, String> skuMap = sku2storeSkuMappings.get(storeName); if (skuMap == null) { skuMap = new HashMap<String, String>(); sku2storeSkuMappings.put(storeName, skuMap); } else if (skuMap.containsKey(sku)) { throw new SkuMappingException("Already specified SKU. sku: " + sku + " -> storeSku: " + skuMap.get(sku)); } Map<String, String> storeSkuMap = storeSku2skuMappings.get(storeName); if (storeSkuMap == null) { storeSkuMap = new HashMap<String, String>(); storeSku2skuMappings.put(storeName, storeSkuMap); } else if (storeSkuMap.get(storeSku) != null) { throw new SkuMappingException("Ambiguous SKU mapping. You try to map sku: " + sku + " -> storeSku: " + storeSku + ", that is already mapped to sku: " + storeSkuMap.get(storeSku)); } skuMap.put(sku, storeSku); storeSkuMap.put(storeSku, sku); return this; }
[ "@", "NotNull", "public", "SkuManager", "mapSku", "(", "String", "sku", ",", "String", "storeName", ",", "@", "NotNull", "String", "storeSku", ")", "{", "checkSkuMappingParams", "(", "sku", ",", "storeName", ",", "storeSku", ")", ";", "Map", "<", "String", ...
Maps a store-specific SKU to an internal base SKU. The best approach is to use SKU like <code>com.companyname.application.item</code>. Such SKU fits most of stores, so it doesn't need to be mapped. If this approach is not applicable, use an internal application SKU in the code (usually it is a SKU for Google Play) and map SKU from other stores using this method. OpenIAB will map SKU in both directions, so you can use only your internal SKU @param sku - The internal SKU @param storeSku - The store-specific SKU. Shouldn't duplicate already mapped values @param storeName - @see {@link IOpenAppstore#getAppstoreName()} or {@link org.onepf.oms.OpenIabHelper#NAME_AMAZON} {@link org.onepf.oms.OpenIabHelper#NAME_GOOGLE} @return Instance of {@link org.onepf.oms.SkuManager}. @throws org.onepf.oms.SkuMappingException If mapping can't be done. @see #mapSku(String, java.util.Map)
[ "Maps", "a", "store", "-", "specific", "SKU", "to", "an", "internal", "base", "SKU", ".", "The", "best", "approach", "is", "to", "use", "SKU", "like", "<code", ">", "com", ".", "companyname", ".", "application", ".", "item<", "/", "code", ">", ".", "...
train
https://github.com/onepf/OpenIAB/blob/90552d53c5303b322940d96a0c4b7cb797d78760/library/src/main/java/org/onepf/oms/SkuManager.java#L72-L98
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/StringUtils.java
StringUtils.propFileToProperties
public static Properties propFileToProperties(String filename) { Properties result = new Properties(); try { InputStream is = new BufferedInputStream(new FileInputStream(filename)); result.load(is); // trim all values for (Object propKey : result.keySet()){ String newVal = result.getProperty((String)propKey); result.setProperty((String)propKey,newVal.trim()); } is.close(); return result; } catch (IOException e) { throw new RuntimeIOException("propFileToProperties could not read properties file: " + filename, e); } }
java
public static Properties propFileToProperties(String filename) { Properties result = new Properties(); try { InputStream is = new BufferedInputStream(new FileInputStream(filename)); result.load(is); // trim all values for (Object propKey : result.keySet()){ String newVal = result.getProperty((String)propKey); result.setProperty((String)propKey,newVal.trim()); } is.close(); return result; } catch (IOException e) { throw new RuntimeIOException("propFileToProperties could not read properties file: " + filename, e); } }
[ "public", "static", "Properties", "propFileToProperties", "(", "String", "filename", ")", "{", "Properties", "result", "=", "new", "Properties", "(", ")", ";", "try", "{", "InputStream", "is", "=", "new", "BufferedInputStream", "(", "new", "FileInputStream", "("...
This method reads in properties listed in a file in the format prop=value, one property per line. Although <code>Properties.load(InputStream)</code> exists, I implemented this method to trim the lines, something not implemented in the <code>load()</code> method. @param filename A properties file to read @return The corresponding Properties object
[ "This", "method", "reads", "in", "properties", "listed", "in", "a", "file", "in", "the", "format", "prop", "=", "value", "one", "property", "per", "line", ".", "Although", "<code", ">", "Properties", ".", "load", "(", "InputStream", ")", "<", "/", "code"...
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/StringUtils.java#L803-L818
pippo-java/pippo
pippo-core/src/main/java/ro/pippo/core/PippoSettings.java
PippoSettings.overrideSetting
public void overrideSetting(String name, long value) { overrides.put(name, Long.toString(value)); }
java
public void overrideSetting(String name, long value) { overrides.put(name, Long.toString(value)); }
[ "public", "void", "overrideSetting", "(", "String", "name", ",", "long", "value", ")", "{", "overrides", ".", "put", "(", "name", ",", "Long", ".", "toString", "(", "value", ")", ")", ";", "}" ]
Override the setting at runtime with the specified value. This change does not persist. @param name @param value
[ "Override", "the", "setting", "at", "runtime", "with", "the", "specified", "value", ".", "This", "change", "does", "not", "persist", "." ]
train
https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/PippoSettings.java#L1056-L1058
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/common/utils/NetUtils.java
NetUtils.connectToString
public static String connectToString(InetSocketAddress local, InetSocketAddress remote) { return toAddressString(local) + " <-> " + toAddressString(remote); }
java
public static String connectToString(InetSocketAddress local, InetSocketAddress remote) { return toAddressString(local) + " <-> " + toAddressString(remote); }
[ "public", "static", "String", "connectToString", "(", "InetSocketAddress", "local", ",", "InetSocketAddress", "remote", ")", "{", "return", "toAddressString", "(", "local", ")", "+", "\" <-> \"", "+", "toAddressString", "(", "remote", ")", ";", "}" ]
连接转字符串 @param local 本地地址 @param remote 远程地址 @return 地址信息字符串
[ "连接转字符串" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/common/utils/NetUtils.java#L457-L459
Harium/keel
src/main/java/com/harium/keel/catalano/core/IntPoint.java
IntPoint.Divide
public static IntPoint Divide(IntPoint point1, IntPoint point2) { IntPoint result = new IntPoint(point1); result.Divide(point2); return result; }
java
public static IntPoint Divide(IntPoint point1, IntPoint point2) { IntPoint result = new IntPoint(point1); result.Divide(point2); return result; }
[ "public", "static", "IntPoint", "Divide", "(", "IntPoint", "point1", ",", "IntPoint", "point2", ")", "{", "IntPoint", "result", "=", "new", "IntPoint", "(", "point1", ")", ";", "result", ".", "Divide", "(", "point2", ")", ";", "return", "result", ";", "}...
Divides values of two points. @param point1 IntPoint. @param point2 IntPoint. @return IntPoint that contains X and Y axis coordinate.
[ "Divides", "values", "of", "two", "points", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/core/IntPoint.java#L238-L242
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/XDMAuditor.java
XDMAuditor.auditPortableMediaCreate
public void auditPortableMediaCreate( RFC3881EventOutcomeCodes eventOutcome, String submissionSetUniqueId, String patientId, List<CodedValueType> purposesOfUse) { if (!isAuditorEnabled()) { return; } ExportEvent exportEvent = new ExportEvent(true, eventOutcome, new IHETransactionEventTypeCodes.DistributeDocumentSetOnMedia(), purposesOfUse); exportEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId()); exportEvent.addSourceActiveParticipant(getSystemUserId(), getSystemAltUserId(), getSystemUserName(), getSystemNetworkId(), true); if (!EventUtils.isEmptyOrNull(patientId)) { exportEvent.addPatientParticipantObject(patientId); } exportEvent.addSubmissionSetParticipantObject(submissionSetUniqueId); audit(exportEvent); }
java
public void auditPortableMediaCreate( RFC3881EventOutcomeCodes eventOutcome, String submissionSetUniqueId, String patientId, List<CodedValueType> purposesOfUse) { if (!isAuditorEnabled()) { return; } ExportEvent exportEvent = new ExportEvent(true, eventOutcome, new IHETransactionEventTypeCodes.DistributeDocumentSetOnMedia(), purposesOfUse); exportEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId()); exportEvent.addSourceActiveParticipant(getSystemUserId(), getSystemAltUserId(), getSystemUserName(), getSystemNetworkId(), true); if (!EventUtils.isEmptyOrNull(patientId)) { exportEvent.addPatientParticipantObject(patientId); } exportEvent.addSubmissionSetParticipantObject(submissionSetUniqueId); audit(exportEvent); }
[ "public", "void", "auditPortableMediaCreate", "(", "RFC3881EventOutcomeCodes", "eventOutcome", ",", "String", "submissionSetUniqueId", ",", "String", "patientId", ",", "List", "<", "CodedValueType", ">", "purposesOfUse", ")", "{", "if", "(", "!", "isAuditorEnabled", "...
Audits a PHI Export event for the IHE XDM Portable Media Creator actor, ITI-32 Distribute Document Set on Media transaction. @param eventOutcome The event outcome indicator @param submissionSetUniqueId The Unique ID of the Submission Set exported @param patientId The ID of the Patient to which the Submission Set pertains
[ "Audits", "a", "PHI", "Export", "event", "for", "the", "IHE", "XDM", "Portable", "Media", "Creator", "actor", "ITI", "-", "32", "Distribute", "Document", "Set", "on", "Media", "transaction", "." ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/XDMAuditor.java#L81-L98
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/corona/Session.java
Session.incrementRequestCount
protected void incrementRequestCount(ResourceType type, int delta) { Context c = getContext(type); int newRequestCount = c.requestCount + delta; c.requestCount = newRequestCount; if (newRequestCount > c.maxConcurrentRequestCount) { c.maxConcurrentRequestCount = newRequestCount; } }
java
protected void incrementRequestCount(ResourceType type, int delta) { Context c = getContext(type); int newRequestCount = c.requestCount + delta; c.requestCount = newRequestCount; if (newRequestCount > c.maxConcurrentRequestCount) { c.maxConcurrentRequestCount = newRequestCount; } }
[ "protected", "void", "incrementRequestCount", "(", "ResourceType", "type", ",", "int", "delta", ")", "{", "Context", "c", "=", "getContext", "(", "type", ")", ";", "int", "newRequestCount", "=", "c", ".", "requestCount", "+", "delta", ";", "c", ".", "reque...
Increase a request count for a resource for this session. It cannot exceed the max concurrent request count. @param type Resource type @param delta incremental request count
[ "Increase", "a", "request", "count", "for", "a", "resource", "for", "this", "session", ".", "It", "cannot", "exceed", "the", "max", "concurrent", "request", "count", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/Session.java#L620-L627
lucee/Lucee
core/src/main/java/lucee/runtime/reflection/Reflector.java
Reflector.setPropertyEL
public static void setPropertyEL(Object obj, String prop, Object value) { // first check for field Field[] fields = getFieldsIgnoreCase(obj.getClass(), prop, null); if (!ArrayUtil.isEmpty(fields)) { try { fields[0].set(obj, value); return; } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } } // then check for setter try { getSetter(obj, prop, value).invoke(obj); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } }
java
public static void setPropertyEL(Object obj, String prop, Object value) { // first check for field Field[] fields = getFieldsIgnoreCase(obj.getClass(), prop, null); if (!ArrayUtil.isEmpty(fields)) { try { fields[0].set(obj, value); return; } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } } // then check for setter try { getSetter(obj, prop, value).invoke(obj); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } }
[ "public", "static", "void", "setPropertyEL", "(", "Object", "obj", ",", "String", "prop", ",", "Object", "value", ")", "{", "// first check for field", "Field", "[", "]", "fields", "=", "getFieldsIgnoreCase", "(", "obj", ".", "getClass", "(", ")", ",", "prop...
assign a value to a visible Property (Field or Setter) of a object @param obj Object to assign value to his property @param prop name of property @param value Value to assign
[ "assign", "a", "value", "to", "a", "visible", "Property", "(", "Field", "or", "Setter", ")", "of", "a", "object" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/reflection/Reflector.java#L1265-L1287
josueeduardo/snappy
plugin-parent/snappy-maven-plugin/src/main/java/io/joshworks/snappy/maven/tools/MainClassFinder.java
MainClassFinder.findMainClass
public static String findMainClass(File rootFolder) throws IOException { return doWithMainClasses(rootFolder, new ClassNameCallback<String>() { @Override public String doWith(String className) { return className; } }); }
java
public static String findMainClass(File rootFolder) throws IOException { return doWithMainClasses(rootFolder, new ClassNameCallback<String>() { @Override public String doWith(String className) { return className; } }); }
[ "public", "static", "String", "findMainClass", "(", "File", "rootFolder", ")", "throws", "IOException", "{", "return", "doWithMainClasses", "(", "rootFolder", ",", "new", "ClassNameCallback", "<", "String", ">", "(", ")", "{", "@", "Override", "public", "String"...
Find the main class from a given folder. @param rootFolder the root folder to search @return the main class or {@code null} @throws IOException if the folder cannot be read
[ "Find", "the", "main", "class", "from", "a", "given", "folder", "." ]
train
https://github.com/josueeduardo/snappy/blob/d95a9e811eda3c24a5e53086369208819884fa49/plugin-parent/snappy-maven-plugin/src/main/java/io/joshworks/snappy/maven/tools/MainClassFinder.java#L82-L89
cogroo/cogroo4
cogroo-nlp/src/main/java/org/cogroo/tools/featurizer/FeaturizerCrossValidator.java
FeaturizerCrossValidator.evaluate
public void evaluate(ObjectStream<FeatureSample> samples, int nFolds) throws IOException, InvalidFormatException, IOException { CrossValidationPartitioner<FeatureSample> partitioner = new CrossValidationPartitioner<FeatureSample>( samples, nFolds); while (partitioner.hasNext()) { CrossValidationPartitioner.TrainingSampleStream<FeatureSample> trainingSampleStream = partitioner .next(); if (this.factory == null) { this.factory = FeaturizerFactory.create(this.factoryClassName, posDict, cgFlags); } FeaturizerModel model = FeaturizerME.train(languageCode, trainingSampleStream, this.params, factory); // do testing FeaturizerEvaluator evaluator = new FeaturizerEvaluator(new FeaturizerME( model), listeners); evaluator.evaluate(trainingSampleStream.getTestSampleStream()); wordAccuracy.add(evaluator.getWordAccuracy(), evaluator.getWordCount()); } }
java
public void evaluate(ObjectStream<FeatureSample> samples, int nFolds) throws IOException, InvalidFormatException, IOException { CrossValidationPartitioner<FeatureSample> partitioner = new CrossValidationPartitioner<FeatureSample>( samples, nFolds); while (partitioner.hasNext()) { CrossValidationPartitioner.TrainingSampleStream<FeatureSample> trainingSampleStream = partitioner .next(); if (this.factory == null) { this.factory = FeaturizerFactory.create(this.factoryClassName, posDict, cgFlags); } FeaturizerModel model = FeaturizerME.train(languageCode, trainingSampleStream, this.params, factory); // do testing FeaturizerEvaluator evaluator = new FeaturizerEvaluator(new FeaturizerME( model), listeners); evaluator.evaluate(trainingSampleStream.getTestSampleStream()); wordAccuracy.add(evaluator.getWordAccuracy(), evaluator.getWordCount()); } }
[ "public", "void", "evaluate", "(", "ObjectStream", "<", "FeatureSample", ">", "samples", ",", "int", "nFolds", ")", "throws", "IOException", ",", "InvalidFormatException", ",", "IOException", "{", "CrossValidationPartitioner", "<", "FeatureSample", ">", "partitioner",...
Starts the evaluation. @param samples the data to train and test @param nFolds number of folds @throws IOException
[ "Starts", "the", "evaluation", "." ]
train
https://github.com/cogroo/cogroo4/blob/b6228900c20c6b37eac10a03708a9669dd562f52/cogroo-nlp/src/main/java/org/cogroo/tools/featurizer/FeaturizerCrossValidator.java#L62-L87
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/INodeDirectory.java
INodeDirectory.addNode
<T extends INode> T addNode(String path, T newNode) throws FileNotFoundException { return addNode(path, newNode, false); }
java
<T extends INode> T addNode(String path, T newNode) throws FileNotFoundException { return addNode(path, newNode, false); }
[ "<", "T", "extends", "INode", ">", "T", "addNode", "(", "String", "path", ",", "T", "newNode", ")", "throws", "FileNotFoundException", "{", "return", "addNode", "(", "path", ",", "newNode", ",", "false", ")", ";", "}" ]
Equivalent to addNode(path, newNode, false). @see #addNode(String, INode, boolean)
[ "Equivalent", "to", "addNode", "(", "path", "newNode", "false", ")", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/INodeDirectory.java#L328-L330
Impetus/Kundera
src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/index/LuceneIndexer.java
LuceneIndexer.indexDocument
public void indexDocument(EntityMetadata metadata, Document document) { if (log.isDebugEnabled()) { log.debug("Indexing document: {} for in file system using Lucene", document); } IndexWriter w = getIndexWriter(); try { w.addDocument(document); } catch (Exception e) { log.error("Error while indexing document {} into Lucene, Caused by:{} ", document, e); throw new LuceneIndexingException("Error while indexing document " + document + " into Lucene.", e); } }
java
public void indexDocument(EntityMetadata metadata, Document document) { if (log.isDebugEnabled()) { log.debug("Indexing document: {} for in file system using Lucene", document); } IndexWriter w = getIndexWriter(); try { w.addDocument(document); } catch (Exception e) { log.error("Error while indexing document {} into Lucene, Caused by:{} ", document, e); throw new LuceneIndexingException("Error while indexing document " + document + " into Lucene.", e); } }
[ "public", "void", "indexDocument", "(", "EntityMetadata", "metadata", ",", "Document", "document", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Indexing document: {} for in file system using Lucene\"", ",", "d...
Indexes document in file system using lucene. @param metadata the metadata @param document the document
[ "Indexes", "document", "in", "file", "system", "using", "lucene", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/index/LuceneIndexer.java#L471-L488
Azure/azure-sdk-for-java
servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java
ClientFactory.createMessageReceiverFromEntityPathAsync
public static CompletableFuture<IMessageReceiver> createMessageReceiverFromEntityPathAsync(URI namespaceEndpointURI, String entityPath, ClientSettings clientSettings, ReceiveMode receiveMode) { Utils.assertNonNull("namespaceEndpointURI", namespaceEndpointURI); Utils.assertNonNull("entityPath", entityPath); MessageReceiver receiver = new MessageReceiver(namespaceEndpointURI, entityPath, null, clientSettings, receiveMode); return receiver.initializeAsync().thenApply((v) -> receiver); }
java
public static CompletableFuture<IMessageReceiver> createMessageReceiverFromEntityPathAsync(URI namespaceEndpointURI, String entityPath, ClientSettings clientSettings, ReceiveMode receiveMode) { Utils.assertNonNull("namespaceEndpointURI", namespaceEndpointURI); Utils.assertNonNull("entityPath", entityPath); MessageReceiver receiver = new MessageReceiver(namespaceEndpointURI, entityPath, null, clientSettings, receiveMode); return receiver.initializeAsync().thenApply((v) -> receiver); }
[ "public", "static", "CompletableFuture", "<", "IMessageReceiver", ">", "createMessageReceiverFromEntityPathAsync", "(", "URI", "namespaceEndpointURI", ",", "String", "entityPath", ",", "ClientSettings", "clientSettings", ",", "ReceiveMode", "receiveMode", ")", "{", "Utils",...
Asynchronously creates a message receiver to the entity using the client settings @param namespaceEndpointURI endpoint uri of entity namespace @param entityPath path of entity @param clientSettings client settings @param receiveMode PeekLock or ReceiveAndDelete @return a CompletableFuture representing the pending creation of message receiver
[ "Asynchronously", "creates", "a", "message", "receiver", "to", "the", "entity", "using", "the", "client", "settings" ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java#L442-L447
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/ie/AbstractSequenceClassifier.java
AbstractSequenceClassifier.loadClassifier
public void loadClassifier(String loadPath, Properties props) throws ClassCastException, IOException, ClassNotFoundException { InputStream is; // ms, 10-04-2010: check first is this path exists in our CLASSPATH. This // takes priority over the file system. if ((is = loadStreamFromClasspath(loadPath)) != null) { Timing.startDoing("Loading classifier from " + loadPath); loadClassifier(is); is.close(); Timing.endDoing(); } else { loadClassifier(new File(loadPath), props); } }
java
public void loadClassifier(String loadPath, Properties props) throws ClassCastException, IOException, ClassNotFoundException { InputStream is; // ms, 10-04-2010: check first is this path exists in our CLASSPATH. This // takes priority over the file system. if ((is = loadStreamFromClasspath(loadPath)) != null) { Timing.startDoing("Loading classifier from " + loadPath); loadClassifier(is); is.close(); Timing.endDoing(); } else { loadClassifier(new File(loadPath), props); } }
[ "public", "void", "loadClassifier", "(", "String", "loadPath", ",", "Properties", "props", ")", "throws", "ClassCastException", ",", "IOException", ",", "ClassNotFoundException", "{", "InputStream", "is", ";", "// ms, 10-04-2010: check first is this path exists in our CLASSPA...
Loads a classifier from the file specified by loadPath. If loadPath ends in .gz, uses a GZIPInputStream, else uses a regular FileInputStream.
[ "Loads", "a", "classifier", "from", "the", "file", "specified", "by", "loadPath", ".", "If", "loadPath", "ends", "in", ".", "gz", "uses", "a", "GZIPInputStream", "else", "uses", "a", "regular", "FileInputStream", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/ie/AbstractSequenceClassifier.java#L1591-L1603
rsocket/rsocket-java
rsocket-transport-netty/src/main/java/io/rsocket/transport/netty/UriUtils.java
UriUtils.getPort
public static int getPort(URI uri, int defaultPort) { Objects.requireNonNull(uri, "uri must not be null"); return uri.getPort() == -1 ? defaultPort : uri.getPort(); }
java
public static int getPort(URI uri, int defaultPort) { Objects.requireNonNull(uri, "uri must not be null"); return uri.getPort() == -1 ? defaultPort : uri.getPort(); }
[ "public", "static", "int", "getPort", "(", "URI", "uri", ",", "int", "defaultPort", ")", "{", "Objects", ".", "requireNonNull", "(", "uri", ",", "\"uri must not be null\"", ")", ";", "return", "uri", ".", "getPort", "(", ")", "==", "-", "1", "?", "defaul...
Returns the port of a URI. If the port is unset (i.e. {@code -1}) then returns the {@code defaultPort}. @param uri the URI to extract the port from @param defaultPort the default to use if the port is unset @return the port of a URI or {@code defaultPort} if unset @throws NullPointerException if {@code uri} is {@code null}
[ "Returns", "the", "port", "of", "a", "URI", ".", "If", "the", "port", "is", "unset", "(", "i", ".", "e", ".", "{", "@code", "-", "1", "}", ")", "then", "returns", "the", "{", "@code", "defaultPort", "}", "." ]
train
https://github.com/rsocket/rsocket-java/blob/5101748fbd224ec86570351cebd24d079b63fbfc/rsocket-transport-netty/src/main/java/io/rsocket/transport/netty/UriUtils.java#L36-L39
aws/aws-sdk-java
aws-java-sdk-workdocs/src/main/java/com/amazonaws/services/workdocs/model/GetDocumentResult.java
GetDocumentResult.withCustomMetadata
public GetDocumentResult withCustomMetadata(java.util.Map<String, String> customMetadata) { setCustomMetadata(customMetadata); return this; }
java
public GetDocumentResult withCustomMetadata(java.util.Map<String, String> customMetadata) { setCustomMetadata(customMetadata); return this; }
[ "public", "GetDocumentResult", "withCustomMetadata", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "customMetadata", ")", "{", "setCustomMetadata", "(", "customMetadata", ")", ";", "return", "this", ";", "}" ]
<p> The custom metadata on the document. </p> @param customMetadata The custom metadata on the document. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "custom", "metadata", "on", "the", "document", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-workdocs/src/main/java/com/amazonaws/services/workdocs/model/GetDocumentResult.java#L114-L117
lagom/lagom
service/javadsl/broker/src/main/java/com/lightbend/lagom/javadsl/broker/TopicProducer.java
TopicProducer.singleStreamWithOffset
public static <Message> Topic<Message> singleStreamWithOffset( Function<Offset, Source<Pair<Message, Offset>, ?>> eventStream) { return taggedStreamWithOffset(SINGLETON_TAG, (tag, offset) -> eventStream.apply(offset)); }
java
public static <Message> Topic<Message> singleStreamWithOffset( Function<Offset, Source<Pair<Message, Offset>, ?>> eventStream) { return taggedStreamWithOffset(SINGLETON_TAG, (tag, offset) -> eventStream.apply(offset)); }
[ "public", "static", "<", "Message", ">", "Topic", "<", "Message", ">", "singleStreamWithOffset", "(", "Function", "<", "Offset", ",", "Source", "<", "Pair", "<", "Message", ",", "Offset", ">", ",", "?", ">", ">", "eventStream", ")", "{", "return", "tagge...
Publish a single stream. This producer will ensure every element from the stream will be published at least once (usually only once), using the message offsets to track where in the stream the producer is up to publishing. @param eventStream A function to create the event stream given the last offset that was published. @return The topic producer.
[ "Publish", "a", "single", "stream", "." ]
train
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/broker/src/main/java/com/lightbend/lagom/javadsl/broker/TopicProducer.java#L38-L41
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/REST.java
REST.postMultiPart
@Override public com.flickr4java.flickr.Response postMultiPart(String path, UploadMetaData metaData, Payload payload, String apiKey, String sharedSecret) throws FlickrException { OAuthRequest request = new OAuthRequest(Verb.POST, buildUrl(path)); Map<String, String> uploadParameters = new HashMap<>(metaData.getUploadParameters()); buildMultipartRequest(uploadParameters, request); OAuth10aService service = createAndSignRequest(apiKey, sharedSecret, request); // Ensure all parameters (including oauth) are added to payload so signature matches uploadParameters.putAll(request.getOauthParameters()); request.addMultipartPayload(String.format("form-data; name=\"photo\"; filename=\"%s\"", metaData.getFilename()), metaData.getFilemimetype(), payload.getPayload()); uploadParameters.entrySet().forEach(e -> request.addMultipartPayload(String.format("form-data; name=\"%s\"", e.getKey()), null, e.getValue().getBytes())); try { return handleResponse(request, service); } catch (IllegalAccessException | InterruptedException | ExecutionException | InstantiationException | IOException | SAXException | ParserConfigurationException e) { throw new FlickrRuntimeException(e); } }
java
@Override public com.flickr4java.flickr.Response postMultiPart(String path, UploadMetaData metaData, Payload payload, String apiKey, String sharedSecret) throws FlickrException { OAuthRequest request = new OAuthRequest(Verb.POST, buildUrl(path)); Map<String, String> uploadParameters = new HashMap<>(metaData.getUploadParameters()); buildMultipartRequest(uploadParameters, request); OAuth10aService service = createAndSignRequest(apiKey, sharedSecret, request); // Ensure all parameters (including oauth) are added to payload so signature matches uploadParameters.putAll(request.getOauthParameters()); request.addMultipartPayload(String.format("form-data; name=\"photo\"; filename=\"%s\"", metaData.getFilename()), metaData.getFilemimetype(), payload.getPayload()); uploadParameters.entrySet().forEach(e -> request.addMultipartPayload(String.format("form-data; name=\"%s\"", e.getKey()), null, e.getValue().getBytes())); try { return handleResponse(request, service); } catch (IllegalAccessException | InterruptedException | ExecutionException | InstantiationException | IOException | SAXException | ParserConfigurationException e) { throw new FlickrRuntimeException(e); } }
[ "@", "Override", "public", "com", ".", "flickr4java", ".", "flickr", ".", "Response", "postMultiPart", "(", "String", "path", ",", "UploadMetaData", "metaData", ",", "Payload", "payload", ",", "String", "apiKey", ",", "String", "sharedSecret", ")", "throws", "...
Invoke an HTTP POST request on a remote host. @param path The request path @param metaData The parameters (collection of Parameter objects) @param payload @return The Response object
[ "Invoke", "an", "HTTP", "POST", "request", "on", "a", "remote", "host", "." ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/REST.java#L201-L223
querydsl/querydsl
querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java
Expressions.stringTemplate
public static StringTemplate stringTemplate(String template, Object... args) { return stringTemplate(createTemplate(template), ImmutableList.copyOf(args)); }
java
public static StringTemplate stringTemplate(String template, Object... args) { return stringTemplate(createTemplate(template), ImmutableList.copyOf(args)); }
[ "public", "static", "StringTemplate", "stringTemplate", "(", "String", "template", ",", "Object", "...", "args", ")", "{", "return", "stringTemplate", "(", "createTemplate", "(", "template", ")", ",", "ImmutableList", ".", "copyOf", "(", "args", ")", ")", ";",...
Create a new Template expression @param template template @param args template parameters @return template expression
[ "Create", "a", "new", "Template", "expression" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L888-L890
JavaMoney/jsr354-ri-bp
src/main/java/org/javamoney/moneta/spi/base/BaseMonetaryCurrenciesSingletonSpi.java
BaseMonetaryCurrenciesSingletonSpi.getCurrency
public CurrencyUnit getCurrency(CurrencyQuery query) { Set<CurrencyUnit> currencies = getCurrencies(query); if (currencies.isEmpty()) { return null; } if (currencies.size() == 1) { return currencies.iterator().next(); } throw new MonetaryException("Ambiguous request for CurrencyUnit: " + query + ", found: " + currencies); }
java
public CurrencyUnit getCurrency(CurrencyQuery query) { Set<CurrencyUnit> currencies = getCurrencies(query); if (currencies.isEmpty()) { return null; } if (currencies.size() == 1) { return currencies.iterator().next(); } throw new MonetaryException("Ambiguous request for CurrencyUnit: " + query + ", found: " + currencies); }
[ "public", "CurrencyUnit", "getCurrency", "(", "CurrencyQuery", "query", ")", "{", "Set", "<", "CurrencyUnit", ">", "currencies", "=", "getCurrencies", "(", "query", ")", ";", "if", "(", "currencies", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";...
Access a single currency by query. @param query The currency query, not null. @return the {@link javax.money.CurrencyUnit} found, never null. @throws javax.money.MonetaryException if multiple currencies match the query.
[ "Access", "a", "single", "currency", "by", "query", "." ]
train
https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/spi/base/BaseMonetaryCurrenciesSingletonSpi.java#L144-L153
Azure/azure-sdk-for-java
cognitiveservices/resource-manager/v2017_04_18/src/main/java/com/microsoft/azure/management/cognitiveservices/v2017_04_18/implementation/AccountsInner.java
AccountsInner.listSkusAsync
public Observable<CognitiveServicesAccountEnumerateSkusResultInner> listSkusAsync(String resourceGroupName, String accountName) { return listSkusWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<CognitiveServicesAccountEnumerateSkusResultInner>, CognitiveServicesAccountEnumerateSkusResultInner>() { @Override public CognitiveServicesAccountEnumerateSkusResultInner call(ServiceResponse<CognitiveServicesAccountEnumerateSkusResultInner> response) { return response.body(); } }); }
java
public Observable<CognitiveServicesAccountEnumerateSkusResultInner> listSkusAsync(String resourceGroupName, String accountName) { return listSkusWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<CognitiveServicesAccountEnumerateSkusResultInner>, CognitiveServicesAccountEnumerateSkusResultInner>() { @Override public CognitiveServicesAccountEnumerateSkusResultInner call(ServiceResponse<CognitiveServicesAccountEnumerateSkusResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "CognitiveServicesAccountEnumerateSkusResultInner", ">", "listSkusAsync", "(", "String", "resourceGroupName", ",", "String", "accountName", ")", "{", "return", "listSkusWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ")", ...
List available SKUs for the requested Cognitive Services account. @param resourceGroupName The name of the resource group within the user's subscription. @param accountName The name of Cognitive Services account. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the CognitiveServicesAccountEnumerateSkusResultInner object
[ "List", "available", "SKUs", "for", "the", "requested", "Cognitive", "Services", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/resource-manager/v2017_04_18/src/main/java/com/microsoft/azure/management/cognitiveservices/v2017_04_18/implementation/AccountsInner.java#L1013-L1020
Azure/azure-sdk-for-java
mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingLocatorsInner.java
StreamingLocatorsInner.listContentKeys
public ListContentKeysResponseInner listContentKeys(String resourceGroupName, String accountName, String streamingLocatorName) { return listContentKeysWithServiceResponseAsync(resourceGroupName, accountName, streamingLocatorName).toBlocking().single().body(); }
java
public ListContentKeysResponseInner listContentKeys(String resourceGroupName, String accountName, String streamingLocatorName) { return listContentKeysWithServiceResponseAsync(resourceGroupName, accountName, streamingLocatorName).toBlocking().single().body(); }
[ "public", "ListContentKeysResponseInner", "listContentKeys", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "streamingLocatorName", ")", "{", "return", "listContentKeysWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", "...
List Content Keys. List Content Keys used by this Streaming Locator. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @param streamingLocatorName The Streaming Locator name. @throws IllegalArgumentException thrown if parameters fail the validation @throws ApiErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ListContentKeysResponseInner object if successful.
[ "List", "Content", "Keys", ".", "List", "Content", "Keys", "used", "by", "this", "Streaming", "Locator", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingLocatorsInner.java#L674-L676
h2oai/h2o-3
h2o-core/src/main/java/water/parser/DecryptionTool.java
DecryptionTool.readSecretKey
static SecretKeySpec readSecretKey(DecryptionSetup ds) { Keyed<?> ksObject = DKV.getGet(ds._keystore_id); ByteVec ksVec = (ByteVec) (ksObject instanceof Frame ? ((Frame) ksObject).vec(0) : ksObject); InputStream ksStream = ksVec.openStream(null /*job key*/); try { KeyStore keystore = KeyStore.getInstance(ds._keystore_type); keystore.load(ksStream, ds._password); if (! keystore.containsAlias(ds._key_alias)) { throw new IllegalArgumentException("Alias for key not found"); } java.security.Key key = keystore.getKey(ds._key_alias, ds._password); return new SecretKeySpec(key.getEncoded(), key.getAlgorithm()); } catch (GeneralSecurityException e) { throw new RuntimeException("Unable to load key " + ds._key_alias + " from keystore " + ds._keystore_id, e); } catch (IOException e) { throw new RuntimeException("Failed to read keystore " + ds._keystore_id, e); } }
java
static SecretKeySpec readSecretKey(DecryptionSetup ds) { Keyed<?> ksObject = DKV.getGet(ds._keystore_id); ByteVec ksVec = (ByteVec) (ksObject instanceof Frame ? ((Frame) ksObject).vec(0) : ksObject); InputStream ksStream = ksVec.openStream(null /*job key*/); try { KeyStore keystore = KeyStore.getInstance(ds._keystore_type); keystore.load(ksStream, ds._password); if (! keystore.containsAlias(ds._key_alias)) { throw new IllegalArgumentException("Alias for key not found"); } java.security.Key key = keystore.getKey(ds._key_alias, ds._password); return new SecretKeySpec(key.getEncoded(), key.getAlgorithm()); } catch (GeneralSecurityException e) { throw new RuntimeException("Unable to load key " + ds._key_alias + " from keystore " + ds._keystore_id, e); } catch (IOException e) { throw new RuntimeException("Failed to read keystore " + ds._keystore_id, e); } }
[ "static", "SecretKeySpec", "readSecretKey", "(", "DecryptionSetup", "ds", ")", "{", "Keyed", "<", "?", ">", "ksObject", "=", "DKV", ".", "getGet", "(", "ds", ".", "_keystore_id", ")", ";", "ByteVec", "ksVec", "=", "(", "ByteVec", ")", "(", "ksObject", "i...
Retrieves a Secret Key using a given Decryption Setup. @param ds decryption setup @return SecretKey
[ "Retrieves", "a", "Secret", "Key", "using", "a", "given", "Decryption", "Setup", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/parser/DecryptionTool.java#L63-L82
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/exceptions/ExceptionMapper.java
ExceptionMapper.get
public static SQLException get(final String message, String sqlState, int errorCode, final Throwable exception, boolean timeout) { final SqlStates state = SqlStates.fromString(sqlState); switch (state) { case DATA_EXCEPTION: return new SQLDataException(message, sqlState, errorCode, exception); case FEATURE_NOT_SUPPORTED: return new SQLFeatureNotSupportedException(message, sqlState, errorCode, exception); case CONSTRAINT_VIOLATION: return new SQLIntegrityConstraintViolationException(message, sqlState, errorCode, exception); case INVALID_AUTHORIZATION: return new SQLInvalidAuthorizationSpecException(message, sqlState, errorCode, exception); case CONNECTION_EXCEPTION: return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception); case SYNTAX_ERROR_ACCESS_RULE: return new SQLSyntaxErrorException(message, sqlState, errorCode, exception); case TRANSACTION_ROLLBACK: return new SQLTransactionRollbackException(message, sqlState, errorCode, exception); case WARNING: return new SQLWarning(message, sqlState, errorCode, exception); case INTERRUPTED_EXCEPTION: if (timeout && "70100".equals(sqlState)) { return new SQLTimeoutException(message, sqlState, errorCode, exception); } if (exception instanceof SQLNonTransientConnectionException) { return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception); } return new SQLTransientException(message, sqlState, errorCode, exception); case TIMEOUT_EXCEPTION: return new SQLTimeoutException(message, sqlState, errorCode, exception); case UNDEFINED_SQLSTATE: if (exception instanceof SQLNonTransientConnectionException) { return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception); } return new SQLException(message, sqlState, errorCode, exception); default: // DISTRIBUTED_TRANSACTION_ERROR, return new SQLException(message, sqlState, errorCode, exception); } }
java
public static SQLException get(final String message, String sqlState, int errorCode, final Throwable exception, boolean timeout) { final SqlStates state = SqlStates.fromString(sqlState); switch (state) { case DATA_EXCEPTION: return new SQLDataException(message, sqlState, errorCode, exception); case FEATURE_NOT_SUPPORTED: return new SQLFeatureNotSupportedException(message, sqlState, errorCode, exception); case CONSTRAINT_VIOLATION: return new SQLIntegrityConstraintViolationException(message, sqlState, errorCode, exception); case INVALID_AUTHORIZATION: return new SQLInvalidAuthorizationSpecException(message, sqlState, errorCode, exception); case CONNECTION_EXCEPTION: return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception); case SYNTAX_ERROR_ACCESS_RULE: return new SQLSyntaxErrorException(message, sqlState, errorCode, exception); case TRANSACTION_ROLLBACK: return new SQLTransactionRollbackException(message, sqlState, errorCode, exception); case WARNING: return new SQLWarning(message, sqlState, errorCode, exception); case INTERRUPTED_EXCEPTION: if (timeout && "70100".equals(sqlState)) { return new SQLTimeoutException(message, sqlState, errorCode, exception); } if (exception instanceof SQLNonTransientConnectionException) { return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception); } return new SQLTransientException(message, sqlState, errorCode, exception); case TIMEOUT_EXCEPTION: return new SQLTimeoutException(message, sqlState, errorCode, exception); case UNDEFINED_SQLSTATE: if (exception instanceof SQLNonTransientConnectionException) { return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception); } return new SQLException(message, sqlState, errorCode, exception); default: // DISTRIBUTED_TRANSACTION_ERROR, return new SQLException(message, sqlState, errorCode, exception); } }
[ "public", "static", "SQLException", "get", "(", "final", "String", "message", ",", "String", "sqlState", ",", "int", "errorCode", ",", "final", "Throwable", "exception", ",", "boolean", "timeout", ")", "{", "final", "SqlStates", "state", "=", "SqlStates", ".",...
Helper to decorate exception with associate subclass of {@link SQLException} exception. @param message exception message @param sqlState sqlstate @param errorCode errorCode @param exception cause @param timeout was timeout on query @return SQLException exception
[ "Helper", "to", "decorate", "exception", "with", "associate", "subclass", "of", "{", "@link", "SQLException", "}", "exception", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/exceptions/ExceptionMapper.java#L226-L266
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Range.java
Range.intersectionWith
public Range<T> intersectionWith(final Range<T> other) { if (!this.isOverlappedBy(other)) { throw new IllegalArgumentException(StringUtils.simpleFormat( "Cannot calculate intersection with non-overlapping range %s", other)); } if (this.equals(other)) { return this; } final T min = getComparator().compare(minimum, other.minimum) < 0 ? other.minimum : minimum; final T max = getComparator().compare(maximum, other.maximum) < 0 ? maximum : other.maximum; return between(min, max, getComparator()); }
java
public Range<T> intersectionWith(final Range<T> other) { if (!this.isOverlappedBy(other)) { throw new IllegalArgumentException(StringUtils.simpleFormat( "Cannot calculate intersection with non-overlapping range %s", other)); } if (this.equals(other)) { return this; } final T min = getComparator().compare(minimum, other.minimum) < 0 ? other.minimum : minimum; final T max = getComparator().compare(maximum, other.maximum) < 0 ? maximum : other.maximum; return between(min, max, getComparator()); }
[ "public", "Range", "<", "T", ">", "intersectionWith", "(", "final", "Range", "<", "T", ">", "other", ")", "{", "if", "(", "!", "this", ".", "isOverlappedBy", "(", "other", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "StringUtils", "."...
Calculate the intersection of {@code this} and an overlapping Range. @param other overlapping Range @return range representing the intersection of {@code this} and {@code other} ({@code this} if equal) @throws IllegalArgumentException if {@code other} does not overlap {@code this} @since 3.0.1
[ "Calculate", "the", "intersection", "of", "{" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Range.java#L381-L392
phax/ph-web
ph-web/src/main/java/com/helger/web/fileupload/parse/FileItemHeaders.java
FileItemHeaders.addHeader
public void addHeader (@Nonnull final String sName, @Nullable final String sValue) { ValueEnforcer.notNull (sName, "HeaderName"); final String sNameLower = sName.toLowerCase (Locale.US); m_aRWLock.writeLocked ( () -> { ICommonsList <String> aHeaderValueList = m_aHeaderNameToValueListMap.get (sNameLower); if (aHeaderValueList == null) { aHeaderValueList = new CommonsArrayList <> (); m_aHeaderNameToValueListMap.put (sNameLower, aHeaderValueList); m_aHeaderNameList.add (sNameLower); } aHeaderValueList.add (sValue); }); }
java
public void addHeader (@Nonnull final String sName, @Nullable final String sValue) { ValueEnforcer.notNull (sName, "HeaderName"); final String sNameLower = sName.toLowerCase (Locale.US); m_aRWLock.writeLocked ( () -> { ICommonsList <String> aHeaderValueList = m_aHeaderNameToValueListMap.get (sNameLower); if (aHeaderValueList == null) { aHeaderValueList = new CommonsArrayList <> (); m_aHeaderNameToValueListMap.put (sNameLower, aHeaderValueList); m_aHeaderNameList.add (sNameLower); } aHeaderValueList.add (sValue); }); }
[ "public", "void", "addHeader", "(", "@", "Nonnull", "final", "String", "sName", ",", "@", "Nullable", "final", "String", "sValue", ")", "{", "ValueEnforcer", ".", "notNull", "(", "sName", ",", "\"HeaderName\"", ")", ";", "final", "String", "sNameLower", "=",...
Method to add header values to this instance. @param sName name of this header @param sValue value of this header
[ "Method", "to", "add", "header", "values", "to", "this", "instance", "." ]
train
https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-web/src/main/java/com/helger/web/fileupload/parse/FileItemHeaders.java#L123-L139
elki-project/elki
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/correlation/CASH.java
CASH.determineMinMaxDistance
private double[] determineMinMaxDistance(Relation<ParameterizationFunction> relation, int dimensionality) { double[] min = new double[dimensionality - 1]; double[] max = new double[dimensionality - 1]; Arrays.fill(max, Math.PI); HyperBoundingBox box = new HyperBoundingBox(min, max); double d_min = Double.POSITIVE_INFINITY, d_max = Double.NEGATIVE_INFINITY; for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { ParameterizationFunction f = relation.get(iditer); HyperBoundingBox minMax = f.determineAlphaMinMax(box); double f_min = f.function(SpatialUtil.getMin(minMax)); double f_max = f.function(SpatialUtil.getMax(minMax)); d_min = Math.min(d_min, f_min); d_max = Math.max(d_max, f_max); } return new double[] { d_min, d_max }; }
java
private double[] determineMinMaxDistance(Relation<ParameterizationFunction> relation, int dimensionality) { double[] min = new double[dimensionality - 1]; double[] max = new double[dimensionality - 1]; Arrays.fill(max, Math.PI); HyperBoundingBox box = new HyperBoundingBox(min, max); double d_min = Double.POSITIVE_INFINITY, d_max = Double.NEGATIVE_INFINITY; for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { ParameterizationFunction f = relation.get(iditer); HyperBoundingBox minMax = f.determineAlphaMinMax(box); double f_min = f.function(SpatialUtil.getMin(minMax)); double f_max = f.function(SpatialUtil.getMax(minMax)); d_min = Math.min(d_min, f_min); d_max = Math.max(d_max, f_max); } return new double[] { d_min, d_max }; }
[ "private", "double", "[", "]", "determineMinMaxDistance", "(", "Relation", "<", "ParameterizationFunction", ">", "relation", ",", "int", "dimensionality", ")", "{", "double", "[", "]", "min", "=", "new", "double", "[", "dimensionality", "-", "1", "]", ";", "...
Determines the minimum and maximum function value of all parameterization functions stored in the specified database. @param relation the database containing the parameterization functions. @param dimensionality the dimensionality of the database @return an array containing the minimum and maximum function value of all parameterization functions stored in the specified database
[ "Determines", "the", "minimum", "and", "maximum", "function", "value", "of", "all", "parameterization", "functions", "stored", "in", "the", "specified", "database", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/correlation/CASH.java#L595-L612
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/workunit/packer/KafkaWorkUnitPacker.java
KafkaWorkUnitPacker.populateMultiPartitionWorkUnit
private static void populateMultiPartitionWorkUnit(List<KafkaPartition> partitions, WorkUnit workUnit) { Preconditions.checkArgument(!partitions.isEmpty(), "There should be at least one partition"); GobblinMetrics.addCustomTagToState(workUnit, new Tag<>("kafkaTopic", partitions.get(0).getTopicName())); for (int i = 0; i < partitions.size(); i++) { workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.PARTITION_ID, i), partitions.get(i).getId()); workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.LEADER_ID, i), partitions.get(i).getLeader().getId()); workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.LEADER_HOSTANDPORT, i), partitions.get(i).getLeader().getHostAndPort()); } }
java
private static void populateMultiPartitionWorkUnit(List<KafkaPartition> partitions, WorkUnit workUnit) { Preconditions.checkArgument(!partitions.isEmpty(), "There should be at least one partition"); GobblinMetrics.addCustomTagToState(workUnit, new Tag<>("kafkaTopic", partitions.get(0).getTopicName())); for (int i = 0; i < partitions.size(); i++) { workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.PARTITION_ID, i), partitions.get(i).getId()); workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.LEADER_ID, i), partitions.get(i).getLeader().getId()); workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.LEADER_HOSTANDPORT, i), partitions.get(i).getLeader().getHostAndPort()); } }
[ "private", "static", "void", "populateMultiPartitionWorkUnit", "(", "List", "<", "KafkaPartition", ">", "partitions", ",", "WorkUnit", "workUnit", ")", "{", "Preconditions", ".", "checkArgument", "(", "!", "partitions", ".", "isEmpty", "(", ")", ",", "\"There shou...
Add a list of partitions of the same topic to a {@link WorkUnit}.
[ "Add", "a", "list", "of", "partitions", "of", "the", "same", "topic", "to", "a", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/workunit/packer/KafkaWorkUnitPacker.java#L256-L266
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalCreator.java
JournalCreator.setDatastreamState
public Date setDatastreamState(Context context, String pid, String dsID, String dsState, String logMessage) throws ServerException { try { CreatorJournalEntry cje = new CreatorJournalEntry(METHOD_SET_DATASTREAM_STATE, context); cje.addArgument(ARGUMENT_NAME_PID, pid); cje.addArgument(ARGUMENT_NAME_DS_ID, dsID); cje.addArgument(ARGUMENT_NAME_DS_STATE, dsState); cje.addArgument(ARGUMENT_NAME_LOG_MESSAGE, logMessage); return (Date) cje.invokeAndClose(delegate, writer); } catch (JournalException e) { throw new GeneralException("Problem creating the Journal", e); } }
java
public Date setDatastreamState(Context context, String pid, String dsID, String dsState, String logMessage) throws ServerException { try { CreatorJournalEntry cje = new CreatorJournalEntry(METHOD_SET_DATASTREAM_STATE, context); cje.addArgument(ARGUMENT_NAME_PID, pid); cje.addArgument(ARGUMENT_NAME_DS_ID, dsID); cje.addArgument(ARGUMENT_NAME_DS_STATE, dsState); cje.addArgument(ARGUMENT_NAME_LOG_MESSAGE, logMessage); return (Date) cje.invokeAndClose(delegate, writer); } catch (JournalException e) { throw new GeneralException("Problem creating the Journal", e); } }
[ "public", "Date", "setDatastreamState", "(", "Context", "context", ",", "String", "pid", ",", "String", "dsID", ",", "String", "dsState", ",", "String", "logMessage", ")", "throws", "ServerException", "{", "try", "{", "CreatorJournalEntry", "cje", "=", "new", ...
Create a journal entry, add the arguments, and invoke the method.
[ "Create", "a", "journal", "entry", "add", "the", "arguments", "and", "invoke", "the", "method", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalCreator.java#L277-L294
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java
ApiOvhHostingweb.serviceName_statistics_GET
public ArrayList<OvhChartSerie<OvhChartTimestampValue>> serviceName_statistics_GET(String serviceName, OvhStatisticsPeriodEnum period, OvhStatisticsTypeEnum type) throws IOException { String qPath = "/hosting/web/{serviceName}/statistics"; StringBuilder sb = path(qPath, serviceName); query(sb, "period", period); query(sb, "type", type); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t6); }
java
public ArrayList<OvhChartSerie<OvhChartTimestampValue>> serviceName_statistics_GET(String serviceName, OvhStatisticsPeriodEnum period, OvhStatisticsTypeEnum type) throws IOException { String qPath = "/hosting/web/{serviceName}/statistics"; StringBuilder sb = path(qPath, serviceName); query(sb, "period", period); query(sb, "type", type); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t6); }
[ "public", "ArrayList", "<", "OvhChartSerie", "<", "OvhChartTimestampValue", ">", ">", "serviceName_statistics_GET", "(", "String", "serviceName", ",", "OvhStatisticsPeriodEnum", "period", ",", "OvhStatisticsTypeEnum", "type", ")", "throws", "IOException", "{", "String", ...
Get statistics about this web hosting REST: GET /hosting/web/{serviceName}/statistics @param period [required] @param type [required] @param serviceName [required] The internal name of your hosting
[ "Get", "statistics", "about", "this", "web", "hosting" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java#L531-L538
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/lss/LssClient.java
LssClient.getPreset
public GetPresetResponse getPreset(GetPresetRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getName(), "The parameter name should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_PRESET, request.getName()); return invokeHttpClient(internalRequest, GetPresetResponse.class); }
java
public GetPresetResponse getPreset(GetPresetRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getName(), "The parameter name should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_PRESET, request.getName()); return invokeHttpClient(internalRequest, GetPresetResponse.class); }
[ "public", "GetPresetResponse", "getPreset", "(", "GetPresetRequest", "request", ")", "{", "checkNotNull", "(", "request", ",", "\"The parameter request should NOT be null.\"", ")", ";", "checkStringNotEmpty", "(", "request", ".", "getName", "(", ")", ",", "\"The paramet...
Get your live preset by live preset name. @param request The request object containing all parameters for getting live preset. @return Your live preset
[ "Get", "your", "live", "preset", "by", "live", "preset", "name", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssClient.java#L417-L423
Omertron/api-thetvdb
src/main/java/com/omertron/thetvdbapi/tools/TvdbParser.java
TvdbParser.getUpdates
public static TVDBUpdates getUpdates(String urlString, int seriesId) throws TvDbException { TVDBUpdates updates = new TVDBUpdates(); Document doc = DOMHelper.getEventDocFromUrl(urlString); if (doc != null) { Node root = doc.getChildNodes().item(0); List<SeriesUpdate> seriesUpdates = new ArrayList<>(); List<EpisodeUpdate> episodeUpdates = new ArrayList<>(); List<BannerUpdate> bannerUpdates = new ArrayList<>(); NodeList updateNodes = root.getChildNodes(); Node updateNode; for (int i = 0; i < updateNodes.getLength(); i++) { updateNode = updateNodes.item(i); switch (updateNode.getNodeName()) { case SERIES: SeriesUpdate su = parseNextSeriesUpdate((Element) updateNode); if (isValidUpdate(seriesId, su)) { seriesUpdates.add(su); } break; case EPISODE: EpisodeUpdate eu = parseNextEpisodeUpdate((Element) updateNode); if (isValidUpdate(seriesId, eu)) { episodeUpdates.add(eu); } break; case BANNER: BannerUpdate bu = parseNextBannerUpdate((Element) updateNode); if (isValidUpdate(seriesId, bu)) { bannerUpdates.add(bu); } break; default: LOG.warn("Unknown update type '{}'", updateNode.getNodeName()); } } updates.setTime(DOMHelper.getValueFromElement((Element) root, TIME)); updates.setSeriesUpdates(seriesUpdates); updates.setEpisodeUpdates(episodeUpdates); updates.setBannerUpdates(bannerUpdates); } return updates; }
java
public static TVDBUpdates getUpdates(String urlString, int seriesId) throws TvDbException { TVDBUpdates updates = new TVDBUpdates(); Document doc = DOMHelper.getEventDocFromUrl(urlString); if (doc != null) { Node root = doc.getChildNodes().item(0); List<SeriesUpdate> seriesUpdates = new ArrayList<>(); List<EpisodeUpdate> episodeUpdates = new ArrayList<>(); List<BannerUpdate> bannerUpdates = new ArrayList<>(); NodeList updateNodes = root.getChildNodes(); Node updateNode; for (int i = 0; i < updateNodes.getLength(); i++) { updateNode = updateNodes.item(i); switch (updateNode.getNodeName()) { case SERIES: SeriesUpdate su = parseNextSeriesUpdate((Element) updateNode); if (isValidUpdate(seriesId, su)) { seriesUpdates.add(su); } break; case EPISODE: EpisodeUpdate eu = parseNextEpisodeUpdate((Element) updateNode); if (isValidUpdate(seriesId, eu)) { episodeUpdates.add(eu); } break; case BANNER: BannerUpdate bu = parseNextBannerUpdate((Element) updateNode); if (isValidUpdate(seriesId, bu)) { bannerUpdates.add(bu); } break; default: LOG.warn("Unknown update type '{}'", updateNode.getNodeName()); } } updates.setTime(DOMHelper.getValueFromElement((Element) root, TIME)); updates.setSeriesUpdates(seriesUpdates); updates.setEpisodeUpdates(episodeUpdates); updates.setBannerUpdates(bannerUpdates); } return updates; }
[ "public", "static", "TVDBUpdates", "getUpdates", "(", "String", "urlString", ",", "int", "seriesId", ")", "throws", "TvDbException", "{", "TVDBUpdates", "updates", "=", "new", "TVDBUpdates", "(", ")", ";", "Document", "doc", "=", "DOMHelper", ".", "getEventDocFr...
Get a list of updates from the URL @param urlString @param seriesId @return @throws com.omertron.thetvdbapi.TvDbException
[ "Get", "a", "list", "of", "updates", "from", "the", "URL" ]
train
https://github.com/Omertron/api-thetvdb/blob/2ff9f9580e76043f19d2fc3234d87e16a95fa485/src/main/java/com/omertron/thetvdbapi/tools/TvdbParser.java#L284-L330
fabric8io/fabric8-forge
fabric8-forge-rest-client/src/main/java/io/fabric8/forge/rest/client/TailResults.java
TailResults.isNewLine
public boolean isNewLine(String line, int index) { return index > lastIndex || (index == lastIndex && !Objects.equals(line, lastLine)); }
java
public boolean isNewLine(String line, int index) { return index > lastIndex || (index == lastIndex && !Objects.equals(line, lastLine)); }
[ "public", "boolean", "isNewLine", "(", "String", "line", ",", "int", "index", ")", "{", "return", "index", ">", "lastIndex", "||", "(", "index", "==", "lastIndex", "&&", "!", "Objects", ".", "equals", "(", "line", ",", "lastLine", ")", ")", ";", "}" ]
Returns true if this line index is newer than the last results or the last line has changed (e.g. if output was appended to the last line)
[ "Returns", "true", "if", "this", "line", "index", "is", "newer", "than", "the", "last", "results", "or", "the", "last", "line", "has", "changed", "(", "e", ".", "g", ".", "if", "output", "was", "appended", "to", "the", "last", "line", ")" ]
train
https://github.com/fabric8io/fabric8-forge/blob/a59871bae4d5c5d3ece10f1e8758e73663087f19/fabric8-forge-rest-client/src/main/java/io/fabric8/forge/rest/client/TailResults.java#L54-L56
b3log/latke
latke-core/src/main/java/org/json/JSONArray.java
JSONArray.optBigDecimal
public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { Object val = this.opt(index); return JSONObject.objectToBigDecimal(val, defaultValue); }
java
public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { Object val = this.opt(index); return JSONObject.objectToBigDecimal(val, defaultValue); }
[ "public", "BigDecimal", "optBigDecimal", "(", "int", "index", ",", "BigDecimal", "defaultValue", ")", "{", "Object", "val", "=", "this", ".", "opt", "(", "index", ")", ";", "return", "JSONObject", ".", "objectToBigDecimal", "(", "val", ",", "defaultValue", "...
Get the optional BigDecimal value associated with an index. The defaultValue is returned if there is no value for the index, or if the value is not a number and cannot be converted to a number. If the value is float or double, the the {@link BigDecimal#BigDecimal(double)} constructor will be used. See notes on the constructor for conversion issues that may arise. @param index The index must be between 0 and length() - 1. @param defaultValue The default value. @return The value.
[ "Get", "the", "optional", "BigDecimal", "value", "associated", "with", "an", "index", ".", "The", "defaultValue", "is", "returned", "if", "there", "is", "no", "value", "for", "the", "index", "or", "if", "the", "value", "is", "not", "a", "number", "and", ...
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L728-L731
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/FreesoundClient.java
FreesoundClient.executeQuery
@SuppressWarnings("unchecked") public <S extends Object, R extends Object> Response<R> executeQuery(final Query<S, R> query) throws FreesoundClientException { final HttpRequest request = buildHTTPRequest(query); final String credential = buildAuthorisationCredential(query); if (credential != null) { request.header("Authorization", credential); } try { if (query instanceof JSONResponseQuery) { final HttpResponse<JsonNode> httpResponse = request.asJson(); final S responseBody = (S) httpResponse.getBody().getObject(); return query.processResponse(httpResponse.getStatus(), httpResponse.getStatusText(), responseBody); } else if (query instanceof BinaryResponseQuery) { final HttpResponse<InputStream> httpResponse = request.asBinary(); final S responseBody = (S) httpResponse.getBody(); return query.processResponse(httpResponse.getStatus(), httpResponse.getStatusText(), responseBody); } else { throw new FreesoundClientException(String.format("Unknown request type: %s", query.getClass())); } } catch (final ClassCastException | UnirestException e) { throw new FreesoundClientException("Error when attempting to make API call", e); } }
java
@SuppressWarnings("unchecked") public <S extends Object, R extends Object> Response<R> executeQuery(final Query<S, R> query) throws FreesoundClientException { final HttpRequest request = buildHTTPRequest(query); final String credential = buildAuthorisationCredential(query); if (credential != null) { request.header("Authorization", credential); } try { if (query instanceof JSONResponseQuery) { final HttpResponse<JsonNode> httpResponse = request.asJson(); final S responseBody = (S) httpResponse.getBody().getObject(); return query.processResponse(httpResponse.getStatus(), httpResponse.getStatusText(), responseBody); } else if (query instanceof BinaryResponseQuery) { final HttpResponse<InputStream> httpResponse = request.asBinary(); final S responseBody = (S) httpResponse.getBody(); return query.processResponse(httpResponse.getStatus(), httpResponse.getStatusText(), responseBody); } else { throw new FreesoundClientException(String.format("Unknown request type: %s", query.getClass())); } } catch (final ClassCastException | UnirestException e) { throw new FreesoundClientException("Error when attempting to make API call", e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "S", "extends", "Object", ",", "R", "extends", "Object", ">", "Response", "<", "R", ">", "executeQuery", "(", "final", "Query", "<", "S", ",", "R", ">", "query", ")", "throws", "Freesound...
Execute a given query (synchronously) against the freesound API. @param <S> The expected response type from the query @param <R> The response type to return @param query The query to execute @return The result of the query @throws FreesoundClientException Any errors encountered when performing API call
[ "Execute", "a", "given", "query", "(", "synchronously", ")", "against", "the", "freesound", "API", "." ]
train
https://github.com/Sonoport/freesound-java/blob/ab029e25de068c6f8cc028bc7f916938fd97c036/src/main/java/com/sonoport/freesound/FreesoundClient.java#L107-L134
cdk/cdk
base/standard/src/main/java/org/openscience/cdk/tools/manipulator/AtomContainerManipulator.java
AtomContainerManipulator.extractSubstructure
public static IAtomContainer extractSubstructure(IAtomContainer atomContainer, int... atomIndices) throws CloneNotSupportedException { IAtomContainer substructure = (IAtomContainer) atomContainer.clone(); int numberOfAtoms = substructure.getAtomCount(); IAtom[] atoms = new IAtom[numberOfAtoms]; for (int atomIndex = 0; atomIndex < numberOfAtoms; atomIndex++) { atoms[atomIndex] = substructure.getAtom(atomIndex); } Arrays.sort(atomIndices); for (int index = 0; index < numberOfAtoms; index++) { if (Arrays.binarySearch(atomIndices, index) < 0) { IAtom atom = atoms[index]; substructure.removeAtom(atom); } } return substructure; }
java
public static IAtomContainer extractSubstructure(IAtomContainer atomContainer, int... atomIndices) throws CloneNotSupportedException { IAtomContainer substructure = (IAtomContainer) atomContainer.clone(); int numberOfAtoms = substructure.getAtomCount(); IAtom[] atoms = new IAtom[numberOfAtoms]; for (int atomIndex = 0; atomIndex < numberOfAtoms; atomIndex++) { atoms[atomIndex] = substructure.getAtom(atomIndex); } Arrays.sort(atomIndices); for (int index = 0; index < numberOfAtoms; index++) { if (Arrays.binarySearch(atomIndices, index) < 0) { IAtom atom = atoms[index]; substructure.removeAtom(atom); } } return substructure; }
[ "public", "static", "IAtomContainer", "extractSubstructure", "(", "IAtomContainer", "atomContainer", ",", "int", "...", "atomIndices", ")", "throws", "CloneNotSupportedException", "{", "IAtomContainer", "substructure", "=", "(", "IAtomContainer", ")", "atomContainer", "."...
Extract a substructure from an atom container, in the form of a new cloned atom container with only the atoms with indices in atomIndices and bonds that connect these atoms. Note that this may result in a disconnected atom container. @param atomContainer the source container to extract from @param atomIndices the indices of the substructure @return a cloned atom container with a substructure of the source @throws CloneNotSupportedException if the source container cannot be cloned
[ "Extract", "a", "substructure", "from", "an", "atom", "container", "in", "the", "form", "of", "a", "new", "cloned", "atom", "container", "with", "only", "the", "atoms", "with", "indices", "in", "atomIndices", "and", "bonds", "that", "connect", "these", "atom...
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/tools/manipulator/AtomContainerManipulator.java#L138-L156
haraldk/TwelveMonkeys
imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java
PICTUtil.readColorTable
public static IndexColorModel readColorTable(final DataInput pStream, final int pPixelSize) throws IOException { // TODO: Do we need to support these? /*int seed = */pStream.readInt(); /*int flags = */pStream.readUnsignedShort(); int size = pStream.readUnsignedShort() + 1; // data is size - 1 int[] colors = new int[size]; for (int i = 0; i < size; i++) { // Read ColorSpec records /*int index = */pStream.readUnsignedShort(); Color color = readRGBColor(pStream); colors[i] = color.getRGB(); } return new IndexColorModel(pPixelSize, size, colors, 0, false, -1, DataBuffer.TYPE_BYTE); }
java
public static IndexColorModel readColorTable(final DataInput pStream, final int pPixelSize) throws IOException { // TODO: Do we need to support these? /*int seed = */pStream.readInt(); /*int flags = */pStream.readUnsignedShort(); int size = pStream.readUnsignedShort() + 1; // data is size - 1 int[] colors = new int[size]; for (int i = 0; i < size; i++) { // Read ColorSpec records /*int index = */pStream.readUnsignedShort(); Color color = readRGBColor(pStream); colors[i] = color.getRGB(); } return new IndexColorModel(pPixelSize, size, colors, 0, false, -1, DataBuffer.TYPE_BYTE); }
[ "public", "static", "IndexColorModel", "readColorTable", "(", "final", "DataInput", "pStream", ",", "final", "int", "pPixelSize", ")", "throws", "IOException", "{", "// TODO: Do we need to support these?", "/*int seed = */", "pStream", ".", "readInt", "(", ")", ";", "...
/* http://developer.apple.com/DOCUMENTATION/mac/QuickDraw/QuickDraw-269.html#HEADING269-11 ColorSpec = RECORD value: Integer; {index or other value} rgb: RGBColor; {true color} END; ColorTable = RECORD ctSeed: LongInt; {unique identifier from table} ctFlags: Integer; {contains flags describing the ctTable field; } { clear for a PixMap record} ctSize: Integer; {number of entries in the next field minus 1} ctTable: cSpecArray; {an array of ColorSpec records} END;
[ "/", "*", "http", ":", "//", "developer", ".", "apple", ".", "com", "/", "DOCUMENTATION", "/", "mac", "/", "QuickDraw", "/", "QuickDraw", "-", "269", ".", "html#HEADING269", "-", "11", "ColorSpec", "=", "RECORD", "value", ":", "Integer", ";", "{", "ind...
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java#L257-L273
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/FuncExtFunction.java
FuncExtFunction.setArg
public void setArg(Expression arg, int argNum) throws WrongNumberArgsException { m_argVec.addElement(arg); arg.exprSetParent(this); }
java
public void setArg(Expression arg, int argNum) throws WrongNumberArgsException { m_argVec.addElement(arg); arg.exprSetParent(this); }
[ "public", "void", "setArg", "(", "Expression", "arg", ",", "int", "argNum", ")", "throws", "WrongNumberArgsException", "{", "m_argVec", ".", "addElement", "(", "arg", ")", ";", "arg", ".", "exprSetParent", "(", "this", ")", ";", "}" ]
Set an argument expression for a function. This method is called by the XPath compiler. @param arg non-null expression that represents the argument. @param argNum The argument number index. @throws WrongNumberArgsException If the argNum parameter is beyond what is specified for this function.
[ "Set", "an", "argument", "expression", "for", "a", "function", ".", "This", "method", "is", "called", "by", "the", "XPath", "compiler", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/FuncExtFunction.java#L232-L237
knowm/XChange
xchange-wex/src/main/java/org/knowm/xchange/wex/v3/WexAdapters.java
WexAdapters.adaptTrade
public static Trade adaptTrade(WexTrade bTCETrade, CurrencyPair currencyPair) { OrderType orderType = bTCETrade.getTradeType().equalsIgnoreCase("bid") ? OrderType.BID : OrderType.ASK; BigDecimal amount = bTCETrade.getAmount(); BigDecimal price = bTCETrade.getPrice(); Date date = DateUtils.fromMillisUtc(bTCETrade.getDate() * 1000L); final String tradeId = String.valueOf(bTCETrade.getTid()); return new Trade(orderType, amount, currencyPair, price, date, tradeId); }
java
public static Trade adaptTrade(WexTrade bTCETrade, CurrencyPair currencyPair) { OrderType orderType = bTCETrade.getTradeType().equalsIgnoreCase("bid") ? OrderType.BID : OrderType.ASK; BigDecimal amount = bTCETrade.getAmount(); BigDecimal price = bTCETrade.getPrice(); Date date = DateUtils.fromMillisUtc(bTCETrade.getDate() * 1000L); final String tradeId = String.valueOf(bTCETrade.getTid()); return new Trade(orderType, amount, currencyPair, price, date, tradeId); }
[ "public", "static", "Trade", "adaptTrade", "(", "WexTrade", "bTCETrade", ",", "CurrencyPair", "currencyPair", ")", "{", "OrderType", "orderType", "=", "bTCETrade", ".", "getTradeType", "(", ")", ".", "equalsIgnoreCase", "(", "\"bid\"", ")", "?", "OrderType", "."...
Adapts a BTCETradeV3 to a Trade Object @param bTCETrade Wex trade object v.3 @param currencyPair the currency pair @return The XChange Trade
[ "Adapts", "a", "BTCETradeV3", "to", "a", "Trade", "Object" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-wex/src/main/java/org/knowm/xchange/wex/v3/WexAdapters.java#L103-L113
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalCreator.java
JournalCreator.addDatastream
public String addDatastream(Context context, String pid, String dsID, String[] altIDs, String dsLabel, boolean versionable, String MIMEType, String formatURI, String location, String controlGroup, String dsState, String checksumType, String checksum, String logMessage) throws ServerException { try { CreatorJournalEntry cje = new CreatorJournalEntry(METHOD_ADD_DATASTREAM, context); cje.addArgument(ARGUMENT_NAME_PID, pid); cje.addArgument(ARGUMENT_NAME_DS_ID, dsID); cje.addArgument(ARGUMENT_NAME_ALT_IDS, altIDs); cje.addArgument(ARGUMENT_NAME_DS_LABEL, dsLabel); cje.addArgument(ARGUMENT_NAME_VERSIONABLE, versionable); cje.addArgument(ARGUMENT_NAME_MIME_TYPE, MIMEType); cje.addArgument(ARGUMENT_NAME_FORMAT_URI, formatURI); cje.addArgument(ARGUMENT_NAME_LOCATION, location); cje.addArgument(ARGUMENT_NAME_CONTROL_GROUP, controlGroup); cje.addArgument(ARGUMENT_NAME_DS_STATE, dsState); cje.addArgument(ARGUMENT_NAME_CHECKSUM_TYPE, checksumType); cje.addArgument(ARGUMENT_NAME_CHECKSUM, checksum); cje.addArgument(ARGUMENT_NAME_LOG_MESSAGE, logMessage); return (String) cje.invokeAndClose(delegate, writer); } catch (JournalException e) { throw new GeneralException("Problem creating the Journal", e); } }
java
public String addDatastream(Context context, String pid, String dsID, String[] altIDs, String dsLabel, boolean versionable, String MIMEType, String formatURI, String location, String controlGroup, String dsState, String checksumType, String checksum, String logMessage) throws ServerException { try { CreatorJournalEntry cje = new CreatorJournalEntry(METHOD_ADD_DATASTREAM, context); cje.addArgument(ARGUMENT_NAME_PID, pid); cje.addArgument(ARGUMENT_NAME_DS_ID, dsID); cje.addArgument(ARGUMENT_NAME_ALT_IDS, altIDs); cje.addArgument(ARGUMENT_NAME_DS_LABEL, dsLabel); cje.addArgument(ARGUMENT_NAME_VERSIONABLE, versionable); cje.addArgument(ARGUMENT_NAME_MIME_TYPE, MIMEType); cje.addArgument(ARGUMENT_NAME_FORMAT_URI, formatURI); cje.addArgument(ARGUMENT_NAME_LOCATION, location); cje.addArgument(ARGUMENT_NAME_CONTROL_GROUP, controlGroup); cje.addArgument(ARGUMENT_NAME_DS_STATE, dsState); cje.addArgument(ARGUMENT_NAME_CHECKSUM_TYPE, checksumType); cje.addArgument(ARGUMENT_NAME_CHECKSUM, checksum); cje.addArgument(ARGUMENT_NAME_LOG_MESSAGE, logMessage); return (String) cje.invokeAndClose(delegate, writer); } catch (JournalException e) { throw new GeneralException("Problem creating the Journal", e); } }
[ "public", "String", "addDatastream", "(", "Context", "context", ",", "String", "pid", ",", "String", "dsID", ",", "String", "[", "]", "altIDs", ",", "String", "dsLabel", ",", "boolean", "versionable", ",", "String", "MIMEType", ",", "String", "formatURI", ",...
Create a journal entry, add the arguments, and invoke the method.
[ "Create", "a", "journal", "entry", "add", "the", "arguments", "and", "invoke", "the", "method", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalCreator.java#L165-L199
alkacon/opencms-core
src/org/opencms/acacia/shared/CmsEntityAttribute.java
CmsEntityAttribute.createSimpleAttribute
public static CmsEntityAttribute createSimpleAttribute(String name, List<String> values) { CmsEntityAttribute result = new CmsEntityAttribute(); result.m_name = name; result.m_simpleValues = Collections.unmodifiableList(values); return result; }
java
public static CmsEntityAttribute createSimpleAttribute(String name, List<String> values) { CmsEntityAttribute result = new CmsEntityAttribute(); result.m_name = name; result.m_simpleValues = Collections.unmodifiableList(values); return result; }
[ "public", "static", "CmsEntityAttribute", "createSimpleAttribute", "(", "String", "name", ",", "List", "<", "String", ">", "values", ")", "{", "CmsEntityAttribute", "result", "=", "new", "CmsEntityAttribute", "(", ")", ";", "result", ".", "m_name", "=", "name", ...
Creates a simple type attribute.<p> @param name the attribute name @param values the attribute values @return the newly created attribute
[ "Creates", "a", "simple", "type", "attribute", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/acacia/shared/CmsEntityAttribute.java#L83-L89
zaproxy/zaproxy
src/org/zaproxy/zap/view/DynamicFieldsPanel.java
DynamicFieldsPanel.getFieldValues
public Map<String, String> getFieldValues() { Map<String, String> values = new HashMap<>(requiredFields.length + optionalFields.length); for (Entry<String, ZapTextField> f : textFields.entrySet()) values.put(f.getKey(), f.getValue().getText()); return values; } /** * Bind a mapping of field names/values to the fields in this panel. All the fields whose names * have a value provided in the map get set to that value, the others get cleared. * * @param fieldValues the field values */ public void bindFieldValues(Map<String, String> fieldValues) { for (Entry<String, ZapTextField> f : textFields.entrySet()) { ZapTextField field = f.getValue(); field.setText(fieldValues.get(f.getKey())); field.discardAllEdits(); } }
java
public Map<String, String> getFieldValues() { Map<String, String> values = new HashMap<>(requiredFields.length + optionalFields.length); for (Entry<String, ZapTextField> f : textFields.entrySet()) values.put(f.getKey(), f.getValue().getText()); return values; } /** * Bind a mapping of field names/values to the fields in this panel. All the fields whose names * have a value provided in the map get set to that value, the others get cleared. * * @param fieldValues the field values */ public void bindFieldValues(Map<String, String> fieldValues) { for (Entry<String, ZapTextField> f : textFields.entrySet()) { ZapTextField field = f.getValue(); field.setText(fieldValues.get(f.getKey())); field.discardAllEdits(); } }
[ "public", "Map", "<", "String", ",", "String", ">", "getFieldValues", "(", ")", "{", "Map", "<", "String", ",", "String", ">", "values", "=", "new", "HashMap", "<>", "(", "requiredFields", ".", "length", "+", "optionalFields", ".", "length", ")", ";", ...
Gets a mapping of the field names to the configured field values. @return the field values
[ "Gets", "a", "mapping", "of", "the", "field", "names", "to", "the", "configured", "field", "values", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/view/DynamicFieldsPanel.java#L146-L165
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/ValueDataUtil.java
ValueDataUtil.readValueData
public static ValueDataWrapper readValueData(int type, int orderNumber, File file, SpoolConfig spoolConfig) throws IOException { ValueDataWrapper vdDataWrapper = new ValueDataWrapper(); long fileSize = file.length(); vdDataWrapper.size = fileSize; if (fileSize > spoolConfig.maxBufferSize) { vdDataWrapper.value = new FilePersistedValueData(orderNumber, file, spoolConfig); } else { // JCR-2463 In case the file was renamed to be removed/changed, // but the transaction wasn't rollbacked cleanly file = fixFileName(file); FileInputStream is = new FileInputStream(file); try { byte[] data = new byte[(int)fileSize]; byte[] buff = new byte[ValueFileIOHelper.IOBUFFER_SIZE > fileSize ? ValueFileIOHelper.IOBUFFER_SIZE : (int)fileSize]; int rpos = 0; int read; while ((read = is.read(buff)) >= 0) { System.arraycopy(buff, 0, data, rpos, read); rpos += read; } vdDataWrapper.value = createValueData(type, orderNumber, data); } finally { is.close(); } } return vdDataWrapper; }
java
public static ValueDataWrapper readValueData(int type, int orderNumber, File file, SpoolConfig spoolConfig) throws IOException { ValueDataWrapper vdDataWrapper = new ValueDataWrapper(); long fileSize = file.length(); vdDataWrapper.size = fileSize; if (fileSize > spoolConfig.maxBufferSize) { vdDataWrapper.value = new FilePersistedValueData(orderNumber, file, spoolConfig); } else { // JCR-2463 In case the file was renamed to be removed/changed, // but the transaction wasn't rollbacked cleanly file = fixFileName(file); FileInputStream is = new FileInputStream(file); try { byte[] data = new byte[(int)fileSize]; byte[] buff = new byte[ValueFileIOHelper.IOBUFFER_SIZE > fileSize ? ValueFileIOHelper.IOBUFFER_SIZE : (int)fileSize]; int rpos = 0; int read; while ((read = is.read(buff)) >= 0) { System.arraycopy(buff, 0, data, rpos, read); rpos += read; } vdDataWrapper.value = createValueData(type, orderNumber, data); } finally { is.close(); } } return vdDataWrapper; }
[ "public", "static", "ValueDataWrapper", "readValueData", "(", "int", "type", ",", "int", "orderNumber", ",", "File", "file", ",", "SpoolConfig", "spoolConfig", ")", "throws", "IOException", "{", "ValueDataWrapper", "vdDataWrapper", "=", "new", "ValueDataWrapper", "(...
Read value data from file. @param type property type, {@link PropertyType} @param file File @param orderNumber value data order number @param spoolConfig contains threshold for spooling @return PersistedValueData @throws IOException if any error is occurred
[ "Read", "value", "data", "from", "file", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/ValueDataUtil.java#L174-L216
menacher/java-game-server
jetserver/src/main/java/org/menacheri/jetserver/util/NettyUtils.java
NettyUtils.readString
public static String readString(ChannelBuffer buffer, int length) { return readString(buffer, length, CharsetUtil.UTF_8); // char[] chars = new char[length]; // for (int i = 0; i < length; i++) // { // chars[i] = buffer.readChar(); // } // return new String(chars); }
java
public static String readString(ChannelBuffer buffer, int length) { return readString(buffer, length, CharsetUtil.UTF_8); // char[] chars = new char[length]; // for (int i = 0; i < length; i++) // { // chars[i] = buffer.readChar(); // } // return new String(chars); }
[ "public", "static", "String", "readString", "(", "ChannelBuffer", "buffer", ",", "int", "length", ")", "{", "return", "readString", "(", "buffer", ",", "length", ",", "CharsetUtil", ".", "UTF_8", ")", ";", "//\t\tchar[] chars = new char[length];", "//\t\tfor (int i ...
Read a string from a channel buffer with the specified length. It resets the reader index of the buffer to the end of the string. @param buffer The Netty buffer containing the String. @param length The number of bytes in the String. @return Returns the read string.
[ "Read", "a", "string", "from", "a", "channel", "buffer", "with", "the", "specified", "length", ".", "It", "resets", "the", "reader", "index", "of", "the", "buffer", "to", "the", "end", "of", "the", "string", "." ]
train
https://github.com/menacher/java-game-server/blob/668ca49e8bd1dac43add62378cf6c22a93125d48/jetserver/src/main/java/org/menacheri/jetserver/util/NettyUtils.java#L183-L193
apache/spark
common/network-common/src/main/java/org/apache/spark/network/client/TransportClient.java
TransportClient.fetchChunk
public void fetchChunk( long streamId, int chunkIndex, ChunkReceivedCallback callback) { if (logger.isDebugEnabled()) { logger.debug("Sending fetch chunk request {} to {}", chunkIndex, getRemoteAddress(channel)); } StreamChunkId streamChunkId = new StreamChunkId(streamId, chunkIndex); StdChannelListener listener = new StdChannelListener(streamChunkId) { @Override void handleFailure(String errorMsg, Throwable cause) { handler.removeFetchRequest(streamChunkId); callback.onFailure(chunkIndex, new IOException(errorMsg, cause)); } }; handler.addFetchRequest(streamChunkId, callback); channel.writeAndFlush(new ChunkFetchRequest(streamChunkId)).addListener(listener); }
java
public void fetchChunk( long streamId, int chunkIndex, ChunkReceivedCallback callback) { if (logger.isDebugEnabled()) { logger.debug("Sending fetch chunk request {} to {}", chunkIndex, getRemoteAddress(channel)); } StreamChunkId streamChunkId = new StreamChunkId(streamId, chunkIndex); StdChannelListener listener = new StdChannelListener(streamChunkId) { @Override void handleFailure(String errorMsg, Throwable cause) { handler.removeFetchRequest(streamChunkId); callback.onFailure(chunkIndex, new IOException(errorMsg, cause)); } }; handler.addFetchRequest(streamChunkId, callback); channel.writeAndFlush(new ChunkFetchRequest(streamChunkId)).addListener(listener); }
[ "public", "void", "fetchChunk", "(", "long", "streamId", ",", "int", "chunkIndex", ",", "ChunkReceivedCallback", "callback", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Sending fetch chunk request {} ...
Requests a single chunk from the remote side, from the pre-negotiated streamId. Chunk indices go from 0 onwards. It is valid to request the same chunk multiple times, though some streams may not support this. Multiple fetchChunk requests may be outstanding simultaneously, and the chunks are guaranteed to be returned in the same order that they were requested, assuming only a single TransportClient is used to fetch the chunks. @param streamId Identifier that refers to a stream in the remote StreamManager. This should be agreed upon by client and server beforehand. @param chunkIndex 0-based index of the chunk to fetch @param callback Callback invoked upon successful receipt of chunk, or upon any failure.
[ "Requests", "a", "single", "chunk", "from", "the", "remote", "side", "from", "the", "pre", "-", "negotiated", "streamId", "." ]
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-common/src/main/java/org/apache/spark/network/client/TransportClient.java#L132-L151
netty/netty
codec/src/main/java/io/netty/handler/codec/compression/Snappy.java
Snappy.validateOffset
private static void validateOffset(int offset, int chunkSizeSoFar) { if (offset == 0) { throw new DecompressionException("Offset is less than minimum permissible value"); } if (offset < 0) { // Due to arithmetic overflow throw new DecompressionException("Offset is greater than maximum value supported by this implementation"); } if (offset > chunkSizeSoFar) { throw new DecompressionException("Offset exceeds size of chunk"); } }
java
private static void validateOffset(int offset, int chunkSizeSoFar) { if (offset == 0) { throw new DecompressionException("Offset is less than minimum permissible value"); } if (offset < 0) { // Due to arithmetic overflow throw new DecompressionException("Offset is greater than maximum value supported by this implementation"); } if (offset > chunkSizeSoFar) { throw new DecompressionException("Offset exceeds size of chunk"); } }
[ "private", "static", "void", "validateOffset", "(", "int", "offset", ",", "int", "chunkSizeSoFar", ")", "{", "if", "(", "offset", "==", "0", ")", "{", "throw", "new", "DecompressionException", "(", "\"Offset is less than minimum permissible value\"", ")", ";", "}"...
Validates that the offset extracted from a compressed reference is within the permissible bounds of an offset (0 < offset < Integer.MAX_VALUE), and does not exceed the length of the chunk currently read so far. @param offset The offset extracted from the compressed reference @param chunkSizeSoFar The number of bytes read so far from this chunk @throws DecompressionException if the offset is invalid
[ "Validates", "that", "the", "offset", "extracted", "from", "a", "compressed", "reference", "is", "within", "the", "permissible", "bounds", "of", "an", "offset", "(", "0", "<", "offset", "<", "Integer", ".", "MAX_VALUE", ")", "and", "does", "not", "exceed", ...
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec/src/main/java/io/netty/handler/codec/compression/Snappy.java#L575-L588
fernandospr/javapns-jdk16
src/main/java/javapns/notification/PushNotificationPayload.java
PushNotificationPayload.getCompatibleProperty
private <T> T getCompatibleProperty(String propertyName, Class<T> expectedClass, String exceptionMessage) throws JSONException { return getCompatibleProperty(propertyName, expectedClass, exceptionMessage, this.apsDictionary); }
java
private <T> T getCompatibleProperty(String propertyName, Class<T> expectedClass, String exceptionMessage) throws JSONException { return getCompatibleProperty(propertyName, expectedClass, exceptionMessage, this.apsDictionary); }
[ "private", "<", "T", ">", "T", "getCompatibleProperty", "(", "String", "propertyName", ",", "Class", "<", "T", ">", "expectedClass", ",", "String", "exceptionMessage", ")", "throws", "JSONException", "{", "return", "getCompatibleProperty", "(", "propertyName", ","...
Get the value of a given property, but only if it is of the expected class. If the value exists but is of a different class than expected, an exception is thrown. This method simply invokes the other getCompatibleProperty method with the root aps dictionary. @param <T> the property value's class @param propertyName the name of the property to get @param expectedClass the property value's expected (required) class @param exceptionMessage the exception message to throw if the value is not of the expected class @return the property's value @throws JSONException
[ "Get", "the", "value", "of", "a", "given", "property", "but", "only", "if", "it", "is", "of", "the", "expected", "class", ".", "If", "the", "value", "exists", "but", "is", "of", "a", "different", "class", "than", "expected", "an", "exception", "is", "t...
train
https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/notification/PushNotificationPayload.java#L256-L258
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/util/ParsedScheduleExpression.java
ParsedScheduleExpression.getNextLastDayOfMonth
private int getNextLastDayOfMonth(int day, int lastDay) { // lastDaysOfMonth = 0b1000 0011 (LSB) = Last, -6, -7 // Shift left so that "Last" aligns with the last day of the month. // For example, for Jan, we want the Last bit in position 31, so we // shift 30-7=23 (note: 0-based last day for Jan is 30) resulting in: // bits = 0b0100 0001 1000 0000 0000 0000 0000 0000 (LSB) int offset = lastDay - 7; long bits = lastDaysOfMonth << offset; if (!contains(bits, day)) { long higher = higher(bits, day); if (higher != 0) { return first(higher); } return ADVANCE_TO_NEXT_MONTH; } return day; }
java
private int getNextLastDayOfMonth(int day, int lastDay) { // lastDaysOfMonth = 0b1000 0011 (LSB) = Last, -6, -7 // Shift left so that "Last" aligns with the last day of the month. // For example, for Jan, we want the Last bit in position 31, so we // shift 30-7=23 (note: 0-based last day for Jan is 30) resulting in: // bits = 0b0100 0001 1000 0000 0000 0000 0000 0000 (LSB) int offset = lastDay - 7; long bits = lastDaysOfMonth << offset; if (!contains(bits, day)) { long higher = higher(bits, day); if (higher != 0) { return first(higher); } return ADVANCE_TO_NEXT_MONTH; } return day; }
[ "private", "int", "getNextLastDayOfMonth", "(", "int", "day", ",", "int", "lastDay", ")", "{", "// lastDaysOfMonth = 0b1000 0011 (LSB) = Last, -6, -7", "// Shift left so that \"Last\" aligns with the last day of the month.", "// For example, for Jan, we want the Last bit in position 31, s...
Returns the next day of the month after <tt>day</tt> that satisfies the lastDayOfMonth constraint. @param day the current 0-based day of the month @param lastDay the current 0-based last day of the month @return a value greater than or equal to <tt>day</tt>
[ "Returns", "the", "next", "day", "of", "the", "month", "after", "<tt", ">", "day<", "/", "tt", ">", "that", "satisfies", "the", "lastDayOfMonth", "constraint", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/util/ParsedScheduleExpression.java#L937-L959
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/geopaparazzi/geopap4/DaoGpsLog.java
DaoGpsLog.getEnvelope
public static ReferencedEnvelope getEnvelope( IHMConnection connection ) throws Exception { String query = "SELECT min(" + // GpsLogsDataTableFields.COLUMN_DATA_LON.getFieldName() + "), max(" + // GpsLogsDataTableFields.COLUMN_DATA_LON.getFieldName() + "), min(" + // GpsLogsDataTableFields.COLUMN_DATA_LAT.getFieldName() + "), max(" + // GpsLogsDataTableFields.COLUMN_DATA_LAT.getFieldName() + ") " + // " FROM " + TABLE_GPSLOG_DATA; try (IHMStatement statement = connection.createStatement(); IHMResultSet rs = statement.executeQuery(query);) { if (rs.next()) { double minX = rs.getDouble(1); double maxX = rs.getDouble(2); double minY = rs.getDouble(3); double maxY = rs.getDouble(4); ReferencedEnvelope env = new ReferencedEnvelope(minX, maxX, minY, maxY, DefaultGeographicCRS.WGS84); return env; } } return null; }
java
public static ReferencedEnvelope getEnvelope( IHMConnection connection ) throws Exception { String query = "SELECT min(" + // GpsLogsDataTableFields.COLUMN_DATA_LON.getFieldName() + "), max(" + // GpsLogsDataTableFields.COLUMN_DATA_LON.getFieldName() + "), min(" + // GpsLogsDataTableFields.COLUMN_DATA_LAT.getFieldName() + "), max(" + // GpsLogsDataTableFields.COLUMN_DATA_LAT.getFieldName() + ") " + // " FROM " + TABLE_GPSLOG_DATA; try (IHMStatement statement = connection.createStatement(); IHMResultSet rs = statement.executeQuery(query);) { if (rs.next()) { double minX = rs.getDouble(1); double maxX = rs.getDouble(2); double minY = rs.getDouble(3); double maxY = rs.getDouble(4); ReferencedEnvelope env = new ReferencedEnvelope(minX, maxX, minY, maxY, DefaultGeographicCRS.WGS84); return env; } } return null; }
[ "public", "static", "ReferencedEnvelope", "getEnvelope", "(", "IHMConnection", "connection", ")", "throws", "Exception", "{", "String", "query", "=", "\"SELECT min(\"", "+", "//", "GpsLogsDataTableFields", ".", "COLUMN_DATA_LON", ".", "getFieldName", "(", ")", "+", ...
Get the current data envelope. @param connection the db connection. @return the envelope. @throws Exception
[ "Get", "the", "current", "data", "envelope", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/geopaparazzi/geopap4/DaoGpsLog.java#L374-L394
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/XSLTAttributeDef.java
XSLTAttributeDef.processCHAR
Object processCHAR( StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws org.xml.sax.SAXException { if (getSupportsAVT()) { try { AVT avt = new AVT(handler, uri, name, rawName, value, owner); // If an AVT wasn't used, validate the value if ((avt.isSimple()) && (value.length() != 1)) { handleError(handler, XSLTErrorResources.INVALID_TCHAR, new Object[] {name, value},null); return null; } return avt; } catch (TransformerException te) { throw new org.xml.sax.SAXException(te); } } else { if (value.length() != 1) { handleError(handler, XSLTErrorResources.INVALID_TCHAR, new Object[] {name, value},null); return null; } return new Character(value.charAt(0)); } }
java
Object processCHAR( StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws org.xml.sax.SAXException { if (getSupportsAVT()) { try { AVT avt = new AVT(handler, uri, name, rawName, value, owner); // If an AVT wasn't used, validate the value if ((avt.isSimple()) && (value.length() != 1)) { handleError(handler, XSLTErrorResources.INVALID_TCHAR, new Object[] {name, value},null); return null; } return avt; } catch (TransformerException te) { throw new org.xml.sax.SAXException(te); } } else { if (value.length() != 1) { handleError(handler, XSLTErrorResources.INVALID_TCHAR, new Object[] {name, value},null); return null; } return new Character(value.charAt(0)); } }
[ "Object", "processCHAR", "(", "StylesheetHandler", "handler", ",", "String", "uri", ",", "String", "name", ",", "String", "rawName", ",", "String", "value", ",", "ElemTemplateElement", "owner", ")", "throws", "org", ".", "xml", ".", "sax", ".", "SAXException",...
Process an attribute string of type T_CHAR into a Character value. @param handler non-null reference to current StylesheetHandler that is constructing the Templates. @param uri The Namespace URI, or an empty string. @param name The local name (without prefix), or empty string if not namespace processing. @param rawName The qualified name (with prefix). @param value Should be a string with a length of 1. @return Character object. @throws org.xml.sax.SAXException if the string is not a length of 1.
[ "Process", "an", "attribute", "string", "of", "type", "T_CHAR", "into", "a", "Character", "value", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/XSLTAttributeDef.java#L577-L606
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java
JobsImpl.listPreparationAndReleaseTaskStatusWithServiceResponseAsync
public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> listPreparationAndReleaseTaskStatusWithServiceResponseAsync(final String jobId, final JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions) { return listPreparationAndReleaseTaskStatusSinglePageAsync(jobId, jobListPreparationAndReleaseTaskStatusOptions) .concatMap(new Func1<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>, Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> call(ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = null; if (jobListPreparationAndReleaseTaskStatusOptions != null) { jobListPreparationAndReleaseTaskStatusNextOptions = new JobListPreparationAndReleaseTaskStatusNextOptions(); jobListPreparationAndReleaseTaskStatusNextOptions.withClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.clientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withReturnClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.returnClientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withOcpDate(jobListPreparationAndReleaseTaskStatusOptions.ocpDate()); } return Observable.just(page).concatWith(listPreparationAndReleaseTaskStatusNextWithServiceResponseAsync(nextPageLink, jobListPreparationAndReleaseTaskStatusNextOptions)); } }); }
java
public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> listPreparationAndReleaseTaskStatusWithServiceResponseAsync(final String jobId, final JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions) { return listPreparationAndReleaseTaskStatusSinglePageAsync(jobId, jobListPreparationAndReleaseTaskStatusOptions) .concatMap(new Func1<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>, Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> call(ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = null; if (jobListPreparationAndReleaseTaskStatusOptions != null) { jobListPreparationAndReleaseTaskStatusNextOptions = new JobListPreparationAndReleaseTaskStatusNextOptions(); jobListPreparationAndReleaseTaskStatusNextOptions.withClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.clientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withReturnClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.returnClientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withOcpDate(jobListPreparationAndReleaseTaskStatusOptions.ocpDate()); } return Observable.just(page).concatWith(listPreparationAndReleaseTaskStatusNextWithServiceResponseAsync(nextPageLink, jobListPreparationAndReleaseTaskStatusNextOptions)); } }); }
[ "public", "Observable", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "JobPreparationAndReleaseTaskExecutionInformation", ">", ",", "JobListPreparationAndReleaseTaskStatusHeaders", ">", ">", "listPreparationAndReleaseTaskStatusWithServiceResponseAsync", "(", "final", "String",...
Lists the execution status of the Job Preparation and Job Release task for the specified job across the compute nodes where the job has run. This API returns the Job Preparation and Job Release task status on all compute nodes that have run the Job Preparation or Job Release task. This includes nodes which have since been removed from the pool. If this API is invoked on a job which has no Job Preparation or Job Release task, the Batch service returns HTTP status code 409 (Conflict) with an error code of JobPreparationTaskNotSpecified. @param jobId The ID of the job. @param jobListPreparationAndReleaseTaskStatusOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;JobPreparationAndReleaseTaskExecutionInformation&gt; object
[ "Lists", "the", "execution", "status", "of", "the", "Job", "Preparation", "and", "Job", "Release", "task", "for", "the", "specified", "job", "across", "the", "compute", "nodes", "where", "the", "job", "has", "run", ".", "This", "API", "returns", "the", "Jo...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java#L3015-L3034
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/JobConf.java
JobConf.overrideConfiguration
public static void overrideConfiguration(JobConf conf, int instance) { final String CONFIG_KEYS[] = new String[]{"mapred.job.tracker", "mapred.local.dir", "mapred.fairscheduler.server.address"}; for (String configKey : CONFIG_KEYS) { String value = conf.get(configKey + "-" + instance); if (value != null) { conf.set(configKey, value); } else { LOG.warn("Configuration " + configKey + "-" + instance + " not found."); } } }
java
public static void overrideConfiguration(JobConf conf, int instance) { final String CONFIG_KEYS[] = new String[]{"mapred.job.tracker", "mapred.local.dir", "mapred.fairscheduler.server.address"}; for (String configKey : CONFIG_KEYS) { String value = conf.get(configKey + "-" + instance); if (value != null) { conf.set(configKey, value); } else { LOG.warn("Configuration " + configKey + "-" + instance + " not found."); } } }
[ "public", "static", "void", "overrideConfiguration", "(", "JobConf", "conf", ",", "int", "instance", ")", "{", "final", "String", "CONFIG_KEYS", "[", "]", "=", "new", "String", "[", "]", "{", "\"mapred.job.tracker\"", ",", "\"mapred.local.dir\"", ",", "\"mapred....
Replce the jobtracker configuration with the configuration of 0 or 1 instance. This allows switching two sets of configurations in the command line option. @param conf The jobConf to be overwritten @param instance 0 or 1 instance of the jobtracker
[ "Replce", "the", "jobtracker", "configuration", "with", "the", "configuration", "of", "0", "or", "1", "instance", ".", "This", "allows", "switching", "two", "sets", "of", "configurations", "in", "the", "command", "line", "option", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/JobConf.java#L2142-L2154
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/handlers/ResponseHandler.java
ResponseHandler.handleBinaryResponse
protected void handleBinaryResponse(HttpServerExchange exchange, Response response) { exchange.dispatch(exchange.getDispatchExecutor(), Application.getInstance(BinaryHandler.class).withResponse(response)); }
java
protected void handleBinaryResponse(HttpServerExchange exchange, Response response) { exchange.dispatch(exchange.getDispatchExecutor(), Application.getInstance(BinaryHandler.class).withResponse(response)); }
[ "protected", "void", "handleBinaryResponse", "(", "HttpServerExchange", "exchange", ",", "Response", "response", ")", "{", "exchange", ".", "dispatch", "(", "exchange", ".", "getDispatchExecutor", "(", ")", ",", "Application", ".", "getInstance", "(", "BinaryHandler...
Handles a binary response to the client by sending the binary content from the response to the undertow output stream @param exchange The Undertow HttpServerExchange @param response The response object @throws IOException
[ "Handles", "a", "binary", "response", "to", "the", "client", "by", "sending", "the", "binary", "content", "from", "the", "response", "to", "the", "undertow", "output", "stream" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/handlers/ResponseHandler.java#L53-L55
hankcs/HanLP
src/main/java/com/hankcs/hanlp/dependency/perceptron/transition/features/FeatureExtractor.java
FeatureExtractor.extractAllParseFeatures
public static Object[] extractAllParseFeatures(Configuration configuration, int length) { if (length == 26) return extractBasicFeatures(configuration, length); else if (length == 72) return extractExtendedFeatures(configuration, length); else return extractExtendedFeaturesWithBrownClusters(configuration, length); }
java
public static Object[] extractAllParseFeatures(Configuration configuration, int length) { if (length == 26) return extractBasicFeatures(configuration, length); else if (length == 72) return extractExtendedFeatures(configuration, length); else return extractExtendedFeaturesWithBrownClusters(configuration, length); }
[ "public", "static", "Object", "[", "]", "extractAllParseFeatures", "(", "Configuration", "configuration", ",", "int", "length", ")", "{", "if", "(", "length", "==", "26", ")", "return", "extractBasicFeatures", "(", "configuration", ",", "length", ")", ";", "el...
Given a list of templates, extracts all features for the given state @param configuration @return @throws Exception
[ "Given", "a", "list", "of", "templates", "extracts", "all", "features", "for", "the", "given", "state" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/dependency/perceptron/transition/features/FeatureExtractor.java#L21-L29
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/corona/PoolGroupSchedulable.java
PoolGroupSchedulable.getPool
public PoolSchedulable getPool(PoolInfo poolInfo) { PoolSchedulable pool = nameToMap.get(poolInfo); if (pool == null) { pool = new PoolSchedulable(poolInfo, getType(), configManager); PoolSchedulable prevPool = nameToMap.putIfAbsent(poolInfo, pool); if (prevPool != null) { pool = prevPool; } } return pool; }
java
public PoolSchedulable getPool(PoolInfo poolInfo) { PoolSchedulable pool = nameToMap.get(poolInfo); if (pool == null) { pool = new PoolSchedulable(poolInfo, getType(), configManager); PoolSchedulable prevPool = nameToMap.putIfAbsent(poolInfo, pool); if (prevPool != null) { pool = prevPool; } } return pool; }
[ "public", "PoolSchedulable", "getPool", "(", "PoolInfo", "poolInfo", ")", "{", "PoolSchedulable", "pool", "=", "nameToMap", ".", "get", "(", "poolInfo", ")", ";", "if", "(", "pool", "==", "null", ")", "{", "pool", "=", "new", "PoolSchedulable", "(", "poolI...
Get a pool, creating it if it does not exist. Note that these pools are never removed. @param poolInfo Pool info used @return Pool that existed or was created
[ "Get", "a", "pool", "creating", "it", "if", "it", "does", "not", "exist", ".", "Note", "that", "these", "pools", "are", "never", "removed", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/PoolGroupSchedulable.java#L193-L203
querydsl/querydsl
querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java
Expressions.asTime
public static <T extends Comparable<?>> TimeExpression<T> asTime(Expression<T> expr) { Expression<T> underlyingMixin = ExpressionUtils.extract(expr); if (underlyingMixin instanceof PathImpl) { return new TimePath<T>((PathImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof OperationImpl) { return new TimeOperation<T>((OperationImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof TemplateExpressionImpl) { return new TimeTemplate<T>((TemplateExpressionImpl<T>) underlyingMixin); } else { return new TimeExpression<T>(underlyingMixin) { private static final long serialVersionUID = -2402288239000668173L; @Override public <R, C> R accept(Visitor<R, C> v, C context) { return this.mixin.accept(v, context); } }; } }
java
public static <T extends Comparable<?>> TimeExpression<T> asTime(Expression<T> expr) { Expression<T> underlyingMixin = ExpressionUtils.extract(expr); if (underlyingMixin instanceof PathImpl) { return new TimePath<T>((PathImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof OperationImpl) { return new TimeOperation<T>((OperationImpl<T>) underlyingMixin); } else if (underlyingMixin instanceof TemplateExpressionImpl) { return new TimeTemplate<T>((TemplateExpressionImpl<T>) underlyingMixin); } else { return new TimeExpression<T>(underlyingMixin) { private static final long serialVersionUID = -2402288239000668173L; @Override public <R, C> R accept(Visitor<R, C> v, C context) { return this.mixin.accept(v, context); } }; } }
[ "public", "static", "<", "T", "extends", "Comparable", "<", "?", ">", ">", "TimeExpression", "<", "T", ">", "asTime", "(", "Expression", "<", "T", ">", "expr", ")", "{", "Expression", "<", "T", ">", "underlyingMixin", "=", "ExpressionUtils", ".", "extrac...
Create a new TimeExpression @param expr the time Expression @return new TimeExpression
[ "Create", "a", "new", "TimeExpression" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L2016-L2036
landawn/AbacusUtil
src/com/landawn/abacus/util/SQLExecutor.java
SQLExecutor.streamAll
@SafeVarargs public final <T> Stream<T> streamAll(final Class<T> targetClass, final List<String> sqls, final StatementSetter statementSetter, final JdbcSettings jdbcSettings, final Object... parameters) { final JdbcUtil.BiRecordGetter<T, RuntimeException> biRecordGetter = BiRecordGetter.to(targetClass); return streamAll(sqls, statementSetter, biRecordGetter, jdbcSettings, parameters); }
java
@SafeVarargs public final <T> Stream<T> streamAll(final Class<T> targetClass, final List<String> sqls, final StatementSetter statementSetter, final JdbcSettings jdbcSettings, final Object... parameters) { final JdbcUtil.BiRecordGetter<T, RuntimeException> biRecordGetter = BiRecordGetter.to(targetClass); return streamAll(sqls, statementSetter, biRecordGetter, jdbcSettings, parameters); }
[ "@", "SafeVarargs", "public", "final", "<", "T", ">", "Stream", "<", "T", ">", "streamAll", "(", "final", "Class", "<", "T", ">", "targetClass", ",", "final", "List", "<", "String", ">", "sqls", ",", "final", "StatementSetter", "statementSetter", ",", "f...
Remember to close the returned <code>Stream</code> list to close the underlying <code>ResultSet</code> list. {@code stream} operation won't be part of transaction or use the connection created by {@code Transaction} even it's in transaction block/range. @param sqls @param statementSetter @param jdbcSettings @param parameters @return
[ "Remember", "to", "close", "the", "returned", "<code", ">", "Stream<", "/", "code", ">", "list", "to", "close", "the", "underlying", "<code", ">", "ResultSet<", "/", "code", ">", "list", ".", "{", "@code", "stream", "}", "operation", "won", "t", "be", ...
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/SQLExecutor.java#L2959-L2965