repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
asterisk-java/asterisk-java
src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerConnection.java
CoherentManagerConnection.sendAction
public static ManagerResponse sendAction(final ManagerAction action, final int timeout) throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException { """ Sends an Asterisk action and waits for a ManagerRespose. @param action @param timeout timeout in milliseconds @return @throws IllegalArgumentException @throws IllegalStateException @throws IOException @throws TimeoutException @throws OperationNotSupportedException """ if (logger.isDebugEnabled()) CoherentManagerConnection.logger.debug("Sending Action: " + action.toString()); //$NON-NLS-1$ CoherentManagerConnection.getInstance(); if ((CoherentManagerConnection.managerConnection != null) && (CoherentManagerConnection.managerConnection.getState() == ManagerConnectionState.CONNECTED)) { final org.asteriskjava.manager.action.ManagerAction ajAction = action.getAJAction(); org.asteriskjava.manager.response.ManagerResponse response = CoherentManagerConnection.managerConnection .sendAction(ajAction, timeout); ManagerResponse convertedResponse = null; // UserEventActions always return a null if (response != null) convertedResponse = CoherentEventFactory.build(response); if ((convertedResponse != null) && (convertedResponse.getResponse().compareToIgnoreCase("Error") == 0))//$NON-NLS-1$ { CoherentManagerConnection.logger.warn("Action '" + ajAction + "' failed, Response: " //$NON-NLS-1$ //$NON-NLS-2$ + convertedResponse.getResponse() + " Message: " + convertedResponse.getMessage()); //$NON-NLS-1$ } return convertedResponse; } throw new IllegalStateException("not connected."); //$NON-NLS-1$ }
java
public static ManagerResponse sendAction(final ManagerAction action, final int timeout) throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException { if (logger.isDebugEnabled()) CoherentManagerConnection.logger.debug("Sending Action: " + action.toString()); //$NON-NLS-1$ CoherentManagerConnection.getInstance(); if ((CoherentManagerConnection.managerConnection != null) && (CoherentManagerConnection.managerConnection.getState() == ManagerConnectionState.CONNECTED)) { final org.asteriskjava.manager.action.ManagerAction ajAction = action.getAJAction(); org.asteriskjava.manager.response.ManagerResponse response = CoherentManagerConnection.managerConnection .sendAction(ajAction, timeout); ManagerResponse convertedResponse = null; // UserEventActions always return a null if (response != null) convertedResponse = CoherentEventFactory.build(response); if ((convertedResponse != null) && (convertedResponse.getResponse().compareToIgnoreCase("Error") == 0))//$NON-NLS-1$ { CoherentManagerConnection.logger.warn("Action '" + ajAction + "' failed, Response: " //$NON-NLS-1$ //$NON-NLS-2$ + convertedResponse.getResponse() + " Message: " + convertedResponse.getMessage()); //$NON-NLS-1$ } return convertedResponse; } throw new IllegalStateException("not connected."); //$NON-NLS-1$ }
[ "public", "static", "ManagerResponse", "sendAction", "(", "final", "ManagerAction", "action", ",", "final", "int", "timeout", ")", "throws", "IllegalArgumentException", ",", "IllegalStateException", ",", "IOException", ",", "TimeoutException", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "CoherentManagerConnection", ".", "logger", ".", "debug", "(", "\"Sending Action: \"", "+", "action", ".", "toString", "(", ")", ")", ";", "//$NON-NLS-1$\r", "CoherentManagerConnection", ".", "getInstance", "(", ")", ";", "if", "(", "(", "CoherentManagerConnection", ".", "managerConnection", "!=", "null", ")", "&&", "(", "CoherentManagerConnection", ".", "managerConnection", ".", "getState", "(", ")", "==", "ManagerConnectionState", ".", "CONNECTED", ")", ")", "{", "final", "org", ".", "asteriskjava", ".", "manager", ".", "action", ".", "ManagerAction", "ajAction", "=", "action", ".", "getAJAction", "(", ")", ";", "org", ".", "asteriskjava", ".", "manager", ".", "response", ".", "ManagerResponse", "response", "=", "CoherentManagerConnection", ".", "managerConnection", ".", "sendAction", "(", "ajAction", ",", "timeout", ")", ";", "ManagerResponse", "convertedResponse", "=", "null", ";", "// UserEventActions always return a null\r", "if", "(", "response", "!=", "null", ")", "convertedResponse", "=", "CoherentEventFactory", ".", "build", "(", "response", ")", ";", "if", "(", "(", "convertedResponse", "!=", "null", ")", "&&", "(", "convertedResponse", ".", "getResponse", "(", ")", ".", "compareToIgnoreCase", "(", "\"Error\"", ")", "==", "0", ")", ")", "//$NON-NLS-1$\r", "{", "CoherentManagerConnection", ".", "logger", ".", "warn", "(", "\"Action '\"", "+", "ajAction", "+", "\"' failed, Response: \"", "//$NON-NLS-1$ //$NON-NLS-2$\r", "+", "convertedResponse", ".", "getResponse", "(", ")", "+", "\" Message: \"", "+", "convertedResponse", ".", "getMessage", "(", ")", ")", ";", "//$NON-NLS-1$\r", "}", "return", "convertedResponse", ";", "}", "throw", "new", "IllegalStateException", "(", "\"not connected.\"", ")", ";", "//$NON-NLS-1$\r", "}" ]
Sends an Asterisk action and waits for a ManagerRespose. @param action @param timeout timeout in milliseconds @return @throws IllegalArgumentException @throws IllegalStateException @throws IOException @throws TimeoutException @throws OperationNotSupportedException
[ "Sends", "an", "Asterisk", "action", "and", "waits", "for", "a", "ManagerRespose", "." ]
train
https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerConnection.java#L327-L356
docusign/docusign-java-client
src/main/java/com/docusign/esign/api/PowerFormsApi.java
PowerFormsApi.getPowerFormData
public PowerFormsFormDataResponse getPowerFormData(String accountId, String powerFormId, PowerFormsApi.GetPowerFormDataOptions options) throws ApiException { """ Returns the form data associated with the usage of a PowerForm. @param accountId The external account number (int) or account ID Guid. (required) @param powerFormId (required) @param options for modifying the method behavior. @return PowerFormsFormDataResponse @throws ApiException if fails to make API call """ Object localVarPostBody = "{}"; // verify the required parameter 'accountId' is set if (accountId == null) { throw new ApiException(400, "Missing the required parameter 'accountId' when calling getPowerFormData"); } // verify the required parameter 'powerFormId' is set if (powerFormId == null) { throw new ApiException(400, "Missing the required parameter 'powerFormId' when calling getPowerFormData"); } // create path and map variables String localVarPath = "/v2/accounts/{accountId}/powerforms/{powerFormId}/form_data".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString())) .replaceAll("\\{" + "powerFormId" + "\\}", apiClient.escapeString(powerFormId.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("", "data_layout", options.dataLayout)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "from_date", options.fromDate)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "to_date", options.toDate)); } 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<PowerFormsFormDataResponse> localVarReturnType = new GenericType<PowerFormsFormDataResponse>() {}; return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); }
java
public PowerFormsFormDataResponse getPowerFormData(String accountId, String powerFormId, PowerFormsApi.GetPowerFormDataOptions 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 getPowerFormData"); } // verify the required parameter 'powerFormId' is set if (powerFormId == null) { throw new ApiException(400, "Missing the required parameter 'powerFormId' when calling getPowerFormData"); } // create path and map variables String localVarPath = "/v2/accounts/{accountId}/powerforms/{powerFormId}/form_data".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString())) .replaceAll("\\{" + "powerFormId" + "\\}", apiClient.escapeString(powerFormId.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("", "data_layout", options.dataLayout)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "from_date", options.fromDate)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "to_date", options.toDate)); } 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<PowerFormsFormDataResponse> localVarReturnType = new GenericType<PowerFormsFormDataResponse>() {}; return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); }
[ "public", "PowerFormsFormDataResponse", "getPowerFormData", "(", "String", "accountId", ",", "String", "powerFormId", ",", "PowerFormsApi", ".", "GetPowerFormDataOptions", "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 getPowerFormData\"", ")", ";", "}", "// verify the required parameter 'powerFormId' is set", "if", "(", "powerFormId", "==", "null", ")", "{", "throw", "new", "ApiException", "(", "400", ",", "\"Missing the required parameter 'powerFormId' when calling getPowerFormData\"", ")", ";", "}", "// create path and map variables", "String", "localVarPath", "=", "\"/v2/accounts/{accountId}/powerforms/{powerFormId}/form_data\"", ".", "replaceAll", "(", "\"\\\\{format\\\\}\"", ",", "\"json\"", ")", ".", "replaceAll", "(", "\"\\\\{\"", "+", "\"accountId\"", "+", "\"\\\\}\"", ",", "apiClient", ".", "escapeString", "(", "accountId", ".", "toString", "(", ")", ")", ")", ".", "replaceAll", "(", "\"\\\\{\"", "+", "\"powerFormId\"", "+", "\"\\\\}\"", ",", "apiClient", ".", "escapeString", "(", "powerFormId", ".", "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", "(", "\"\"", ",", "\"data_layout\"", ",", "options", ".", "dataLayout", ")", ")", ";", "localVarQueryParams", ".", "addAll", "(", "apiClient", ".", "parameterToPairs", "(", "\"\"", ",", "\"from_date\"", ",", "options", ".", "fromDate", ")", ")", ";", "localVarQueryParams", ".", "addAll", "(", "apiClient", ".", "parameterToPairs", "(", "\"\"", ",", "\"to_date\"", ",", "options", ".", "toDate", ")", ")", ";", "}", "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", "<", "PowerFormsFormDataResponse", ">", "localVarReturnType", "=", "new", "GenericType", "<", "PowerFormsFormDataResponse", ">", "(", ")", "{", "}", ";", "return", "apiClient", ".", "invokeAPI", "(", "localVarPath", ",", "\"GET\"", ",", "localVarQueryParams", ",", "localVarPostBody", ",", "localVarHeaderParams", ",", "localVarFormParams", ",", "localVarAccept", ",", "localVarContentType", ",", "localVarAuthNames", ",", "localVarReturnType", ")", ";", "}" ]
Returns the form data associated with the usage of a PowerForm. @param accountId The external account number (int) or account ID Guid. (required) @param powerFormId (required) @param options for modifying the method behavior. @return PowerFormsFormDataResponse @throws ApiException if fails to make API call
[ "Returns", "the", "form", "data", "associated", "with", "the", "usage", "of", "a", "PowerForm", "." ]
train
https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/PowerFormsApi.java#L286-L330
graphql-java/java-dataloader
src/main/java/org/dataloader/DataLoader.java
DataLoader.newMappedDataLoaderWithTry
public static <K, V> DataLoader<K, V> newMappedDataLoaderWithTry(MappedBatchLoaderWithContext<K, Try<V>> batchLoadFunction) { """ Creates new DataLoader with the specified batch loader function and default options (batching, caching and unlimited batch size) where the batch loader function returns a list of {@link org.dataloader.Try} objects. <p> If its important you to know the exact status of each item in a batch call and whether it threw exceptions then you can use this form to create the data loader. <p> Using Try objects allows you to capture a value returned or an exception that might have occurred trying to get a value. . @param batchLoadFunction the batch load function to use that uses {@link org.dataloader.Try} objects @param <K> the key type @param <V> the value type @return a new DataLoader """ return newMappedDataLoaderWithTry(batchLoadFunction, null); }
java
public static <K, V> DataLoader<K, V> newMappedDataLoaderWithTry(MappedBatchLoaderWithContext<K, Try<V>> batchLoadFunction) { return newMappedDataLoaderWithTry(batchLoadFunction, null); }
[ "public", "static", "<", "K", ",", "V", ">", "DataLoader", "<", "K", ",", "V", ">", "newMappedDataLoaderWithTry", "(", "MappedBatchLoaderWithContext", "<", "K", ",", "Try", "<", "V", ">", ">", "batchLoadFunction", ")", "{", "return", "newMappedDataLoaderWithTry", "(", "batchLoadFunction", ",", "null", ")", ";", "}" ]
Creates new DataLoader with the specified batch loader function and default options (batching, caching and unlimited batch size) where the batch loader function returns a list of {@link org.dataloader.Try} objects. <p> If its important you to know the exact status of each item in a batch call and whether it threw exceptions then you can use this form to create the data loader. <p> Using Try objects allows you to capture a value returned or an exception that might have occurred trying to get a value. . @param batchLoadFunction the batch load function to use that uses {@link org.dataloader.Try} objects @param <K> the key type @param <V> the value type @return a new DataLoader
[ "Creates", "new", "DataLoader", "with", "the", "specified", "batch", "loader", "function", "and", "default", "options", "(", "batching", "caching", "and", "unlimited", "batch", "size", ")", "where", "the", "batch", "loader", "function", "returns", "a", "list", "of", "{", "@link", "org", ".", "dataloader", ".", "Try", "}", "objects", ".", "<p", ">", "If", "its", "important", "you", "to", "know", "the", "exact", "status", "of", "each", "item", "in", "a", "batch", "call", "and", "whether", "it", "threw", "exceptions", "then", "you", "can", "use", "this", "form", "to", "create", "the", "data", "loader", ".", "<p", ">", "Using", "Try", "objects", "allows", "you", "to", "capture", "a", "value", "returned", "or", "an", "exception", "that", "might", "have", "occurred", "trying", "to", "get", "a", "value", ".", "." ]
train
https://github.com/graphql-java/java-dataloader/blob/dfdc8133ead10aa723f896b4a1fa4a1cec9a6fbc/src/main/java/org/dataloader/DataLoader.java#L313-L315
eurekaclinical/protempa
protempa-ksb-protege/src/main/java/org/protempa/backend/ksb/protege/ConnectionManager.java
ConnectionManager.getFromProtege
private <S, T> S getFromProtege(T obj, ProtegeCommand<S, T> getter) throws KnowledgeSourceReadException { """ Executes a command upon the Protege knowledge base, retrying if needed. @param <S> The type of what is returned by the getter. @param <T> The type of what is passed to protege as a parameter. @param obj What is passed to Protege as a parameter. @param getter the <code>ProtegeCommand</code>. @return what is returned from the Protege command. """ if (protegeKnowledgeBase != null && getter != null) { int tries = TRIES; Exception lastException = null; do { try { return getter.getHelper(obj); } catch (Exception e) { lastException = e; Util.logger().log( Level.WARNING, "Exception attempting to " + getter.getWhat() + " " + obj, e); tries--; } close(); try { init(); } catch (KnowledgeSourceBackendInitializationException e) { throw new KnowledgeSourceReadException( "Exception attempting to " + getter.getWhat() + " " + obj, e); } } while (tries > 0); throw new KnowledgeSourceReadException( "Failed to " + getter.getWhat() + " " + obj + " after " + TRIES + " tries", lastException); } return null; }
java
private <S, T> S getFromProtege(T obj, ProtegeCommand<S, T> getter) throws KnowledgeSourceReadException { if (protegeKnowledgeBase != null && getter != null) { int tries = TRIES; Exception lastException = null; do { try { return getter.getHelper(obj); } catch (Exception e) { lastException = e; Util.logger().log( Level.WARNING, "Exception attempting to " + getter.getWhat() + " " + obj, e); tries--; } close(); try { init(); } catch (KnowledgeSourceBackendInitializationException e) { throw new KnowledgeSourceReadException( "Exception attempting to " + getter.getWhat() + " " + obj, e); } } while (tries > 0); throw new KnowledgeSourceReadException( "Failed to " + getter.getWhat() + " " + obj + " after " + TRIES + " tries", lastException); } return null; }
[ "private", "<", "S", ",", "T", ">", "S", "getFromProtege", "(", "T", "obj", ",", "ProtegeCommand", "<", "S", ",", "T", ">", "getter", ")", "throws", "KnowledgeSourceReadException", "{", "if", "(", "protegeKnowledgeBase", "!=", "null", "&&", "getter", "!=", "null", ")", "{", "int", "tries", "=", "TRIES", ";", "Exception", "lastException", "=", "null", ";", "do", "{", "try", "{", "return", "getter", ".", "getHelper", "(", "obj", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "lastException", "=", "e", ";", "Util", ".", "logger", "(", ")", ".", "log", "(", "Level", ".", "WARNING", ",", "\"Exception attempting to \"", "+", "getter", ".", "getWhat", "(", ")", "+", "\" \"", "+", "obj", ",", "e", ")", ";", "tries", "--", ";", "}", "close", "(", ")", ";", "try", "{", "init", "(", ")", ";", "}", "catch", "(", "KnowledgeSourceBackendInitializationException", "e", ")", "{", "throw", "new", "KnowledgeSourceReadException", "(", "\"Exception attempting to \"", "+", "getter", ".", "getWhat", "(", ")", "+", "\" \"", "+", "obj", ",", "e", ")", ";", "}", "}", "while", "(", "tries", ">", "0", ")", ";", "throw", "new", "KnowledgeSourceReadException", "(", "\"Failed to \"", "+", "getter", ".", "getWhat", "(", ")", "+", "\" \"", "+", "obj", "+", "\" after \"", "+", "TRIES", "+", "\" tries\"", ",", "lastException", ")", ";", "}", "return", "null", ";", "}" ]
Executes a command upon the Protege knowledge base, retrying if needed. @param <S> The type of what is returned by the getter. @param <T> The type of what is passed to protege as a parameter. @param obj What is passed to Protege as a parameter. @param getter the <code>ProtegeCommand</code>. @return what is returned from the Protege command.
[ "Executes", "a", "command", "upon", "the", "Protege", "knowledge", "base", "retrying", "if", "needed", "." ]
train
https://github.com/eurekaclinical/protempa/blob/5a620d1a407c7a5426d1cf17d47b97717cf71634/protempa-ksb-protege/src/main/java/org/protempa/backend/ksb/protege/ConnectionManager.java#L233-L264
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.getEvseById
private Evse getEvseById(ChargingStationType chargingStationType, Long id) { """ Gets a Evse by id. @param chargingStationType charging station type. @param id evse id. @return evse @throws EntityNotFoundException if the Evse cannot be found. """ for (Evse evse:chargingStationType.getEvses()) { if(id.equals(evse.getId())) { return evse; } } throw new EntityNotFoundException(String.format("Unable to find evse with id '%s'", id)); }
java
private Evse getEvseById(ChargingStationType chargingStationType, Long id) { for (Evse evse:chargingStationType.getEvses()) { if(id.equals(evse.getId())) { return evse; } } throw new EntityNotFoundException(String.format("Unable to find evse with id '%s'", id)); }
[ "private", "Evse", "getEvseById", "(", "ChargingStationType", "chargingStationType", ",", "Long", "id", ")", "{", "for", "(", "Evse", "evse", ":", "chargingStationType", ".", "getEvses", "(", ")", ")", "{", "if", "(", "id", ".", "equals", "(", "evse", ".", "getId", "(", ")", ")", ")", "{", "return", "evse", ";", "}", "}", "throw", "new", "EntityNotFoundException", "(", "String", ".", "format", "(", "\"Unable to find evse with id '%s'\"", ",", "id", ")", ")", ";", "}" ]
Gets a Evse by id. @param chargingStationType charging station type. @param id evse id. @return evse @throws EntityNotFoundException if the Evse cannot be found.
[ "Gets", "a", "Evse", "by", "id", "." ]
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L395-L402
dkpro/dkpro-jwpl
de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/WikipediaTemplateInfo.java
WikipediaTemplateInfo.getRevisionIdsNotContainingTemplateFragments
public List<Integer> getRevisionIdsNotContainingTemplateFragments(List<String> templateFragments) throws WikiApiException { """ Returns a list containing the ids of all revisions that contain a template the name of which starts with any of the given Strings. @param templateFragments the beginning of the templates that have to be matched @return An list with the ids of the revisions that do not contain templates beginning with any String in templateFragments @throws WikiApiException If there was any error retrieving the page object (most likely if the template templates are corrupted) """ return getFragmentFilteredRevisionIds(templateFragments,false); }
java
public List<Integer> getRevisionIdsNotContainingTemplateFragments(List<String> templateFragments) throws WikiApiException{ return getFragmentFilteredRevisionIds(templateFragments,false); }
[ "public", "List", "<", "Integer", ">", "getRevisionIdsNotContainingTemplateFragments", "(", "List", "<", "String", ">", "templateFragments", ")", "throws", "WikiApiException", "{", "return", "getFragmentFilteredRevisionIds", "(", "templateFragments", ",", "false", ")", ";", "}" ]
Returns a list containing the ids of all revisions that contain a template the name of which starts with any of the given Strings. @param templateFragments the beginning of the templates that have to be matched @return An list with the ids of the revisions that do not contain templates beginning with any String in templateFragments @throws WikiApiException If there was any error retrieving the page object (most likely if the template templates are corrupted)
[ "Returns", "a", "list", "containing", "the", "ids", "of", "all", "revisions", "that", "contain", "a", "template", "the", "name", "of", "which", "starts", "with", "any", "of", "the", "given", "Strings", "." ]
train
https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/WikipediaTemplateInfo.java#L828-L830
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/UResourceBundle.java
UResourceBundle.getBundleInstance
public static UResourceBundle getBundleInstance(String baseName, String localeName) { """ <strong>[icu]</strong> Creates a resource bundle using the specified base name and locale. ICU_DATA_CLASS is used as the default root. @param baseName string containing the name of the data package. If null the default ICU package name is used. @param localeName the locale for which a resource bundle is desired @throws MissingResourceException If no resource bundle for the specified base name can be found @return a resource bundle for the given base name and locale """ return getBundleInstance(baseName, localeName, ICUResourceBundle.ICU_DATA_CLASS_LOADER, false); }
java
public static UResourceBundle getBundleInstance(String baseName, String localeName){ return getBundleInstance(baseName, localeName, ICUResourceBundle.ICU_DATA_CLASS_LOADER, false); }
[ "public", "static", "UResourceBundle", "getBundleInstance", "(", "String", "baseName", ",", "String", "localeName", ")", "{", "return", "getBundleInstance", "(", "baseName", ",", "localeName", ",", "ICUResourceBundle", ".", "ICU_DATA_CLASS_LOADER", ",", "false", ")", ";", "}" ]
<strong>[icu]</strong> Creates a resource bundle using the specified base name and locale. ICU_DATA_CLASS is used as the default root. @param baseName string containing the name of the data package. If null the default ICU package name is used. @param localeName the locale for which a resource bundle is desired @throws MissingResourceException If no resource bundle for the specified base name can be found @return a resource bundle for the given base name and locale
[ "<strong", ">", "[", "icu", "]", "<", "/", "strong", ">", "Creates", "a", "resource", "bundle", "using", "the", "specified", "base", "name", "and", "locale", ".", "ICU_DATA_CLASS", "is", "used", "as", "the", "default", "root", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/UResourceBundle.java#L109-L112
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/dependence/HoeffdingsDDependenceMeasure.java
HoeffdingsDDependenceMeasure.toPValue
public double toPValue(double d, int n) { """ Convert Hoeffding D value to a p-value. @param d D value @param n Data set size @return p-value """ double b = d / 30 + 1. / (36 * n); double z = .5 * MathUtil.PISQUARE * MathUtil.PISQUARE * n * b; // Exponential approximation if(z < 1.1 || z > 8.5) { double e = FastMath.exp(0.3885037 - 1.164879 * z); return (e > 1) ? 1 : (e < 0) ? 0 : e; } // Tabular approximation for(int i = 0; i < 86; i++) { if(TABPOS[i] >= z) { // Exact table value if(TABPOS[i] == z) { return TABVAL[i]; } // Linear interpolation double x1 = TABPOS[i], x0 = TABPOS[i - 1]; double y1 = TABVAL[i], y0 = TABVAL[i - 1]; return y0 + (y1 - y0) * (z - x0) / (x1 - x0); } } return -1; }
java
public double toPValue(double d, int n) { double b = d / 30 + 1. / (36 * n); double z = .5 * MathUtil.PISQUARE * MathUtil.PISQUARE * n * b; // Exponential approximation if(z < 1.1 || z > 8.5) { double e = FastMath.exp(0.3885037 - 1.164879 * z); return (e > 1) ? 1 : (e < 0) ? 0 : e; } // Tabular approximation for(int i = 0; i < 86; i++) { if(TABPOS[i] >= z) { // Exact table value if(TABPOS[i] == z) { return TABVAL[i]; } // Linear interpolation double x1 = TABPOS[i], x0 = TABPOS[i - 1]; double y1 = TABVAL[i], y0 = TABVAL[i - 1]; return y0 + (y1 - y0) * (z - x0) / (x1 - x0); } } return -1; }
[ "public", "double", "toPValue", "(", "double", "d", ",", "int", "n", ")", "{", "double", "b", "=", "d", "/", "30", "+", "1.", "/", "(", "36", "*", "n", ")", ";", "double", "z", "=", ".5", "*", "MathUtil", ".", "PISQUARE", "*", "MathUtil", ".", "PISQUARE", "*", "n", "*", "b", ";", "// Exponential approximation", "if", "(", "z", "<", "1.1", "||", "z", ">", "8.5", ")", "{", "double", "e", "=", "FastMath", ".", "exp", "(", "0.3885037", "-", "1.164879", "*", "z", ")", ";", "return", "(", "e", ">", "1", ")", "?", "1", ":", "(", "e", "<", "0", ")", "?", "0", ":", "e", ";", "}", "// Tabular approximation", "for", "(", "int", "i", "=", "0", ";", "i", "<", "86", ";", "i", "++", ")", "{", "if", "(", "TABPOS", "[", "i", "]", ">=", "z", ")", "{", "// Exact table value", "if", "(", "TABPOS", "[", "i", "]", "==", "z", ")", "{", "return", "TABVAL", "[", "i", "]", ";", "}", "// Linear interpolation", "double", "x1", "=", "TABPOS", "[", "i", "]", ",", "x0", "=", "TABPOS", "[", "i", "-", "1", "]", ";", "double", "y1", "=", "TABVAL", "[", "i", "]", ",", "y0", "=", "TABVAL", "[", "i", "-", "1", "]", ";", "return", "y0", "+", "(", "y1", "-", "y0", ")", "*", "(", "z", "-", "x0", ")", "/", "(", "x1", "-", "x0", ")", ";", "}", "}", "return", "-", "1", ";", "}" ]
Convert Hoeffding D value to a p-value. @param d D value @param n Data set size @return p-value
[ "Convert", "Hoeffding", "D", "value", "to", "a", "p", "-", "value", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/dependence/HoeffdingsDDependenceMeasure.java#L170-L193
oasp/oasp4j
modules/jpa-basic/src/main/java/io/oasp/module/jpa/dataaccess/api/QueryUtil.java
QueryUtil.findPaginated
public <E> Page<E> findPaginated(Pageable pageable, JPAQuery<E> query, boolean determineTotal) { """ Returns a {@link Page} of entities according to the supplied {@link Pageable} and {@link JPAQuery}. @param <E> generic type of the entity. @param pageable contains information about the requested page and sorting. @param query is a query which is pre-configured with the desired conditions for the search. @param determineTotal - {@code true} to determine the {@link Page#getTotalElements() total number of hits}, {@code false} otherwise. @return a paginated list. """ return findPaginatedGeneric(pageable, query, determineTotal); }
java
public <E> Page<E> findPaginated(Pageable pageable, JPAQuery<E> query, boolean determineTotal) { return findPaginatedGeneric(pageable, query, determineTotal); }
[ "public", "<", "E", ">", "Page", "<", "E", ">", "findPaginated", "(", "Pageable", "pageable", ",", "JPAQuery", "<", "E", ">", "query", ",", "boolean", "determineTotal", ")", "{", "return", "findPaginatedGeneric", "(", "pageable", ",", "query", ",", "determineTotal", ")", ";", "}" ]
Returns a {@link Page} of entities according to the supplied {@link Pageable} and {@link JPAQuery}. @param <E> generic type of the entity. @param pageable contains information about the requested page and sorting. @param query is a query which is pre-configured with the desired conditions for the search. @param determineTotal - {@code true} to determine the {@link Page#getTotalElements() total number of hits}, {@code false} otherwise. @return a paginated list.
[ "Returns", "a", "{", "@link", "Page", "}", "of", "entities", "according", "to", "the", "supplied", "{", "@link", "Pageable", "}", "and", "{", "@link", "JPAQuery", "}", "." ]
train
https://github.com/oasp/oasp4j/blob/03f90132699fad95e52ec8efa54aa391f8d3c7e4/modules/jpa-basic/src/main/java/io/oasp/module/jpa/dataaccess/api/QueryUtil.java#L102-L105
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/fork/Fork.java
Fork.verifyAndSetForkState
private void verifyAndSetForkState(ForkState expectedState, ForkState newState) { """ Compare and set the state of this {@link Fork} to a new state if and only if the current state is equal to the expected state. Throw an exception if the state did not match. """ if (!compareAndSetForkState(expectedState, newState)) { throw new IllegalStateException(String .format("Expected fork state %s; actual fork state %s", expectedState.name(), this.forkState.get().name())); } }
java
private void verifyAndSetForkState(ForkState expectedState, ForkState newState) { if (!compareAndSetForkState(expectedState, newState)) { throw new IllegalStateException(String .format("Expected fork state %s; actual fork state %s", expectedState.name(), this.forkState.get().name())); } }
[ "private", "void", "verifyAndSetForkState", "(", "ForkState", "expectedState", ",", "ForkState", "newState", ")", "{", "if", "(", "!", "compareAndSetForkState", "(", "expectedState", ",", "newState", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "String", ".", "format", "(", "\"Expected fork state %s; actual fork state %s\"", ",", "expectedState", ".", "name", "(", ")", ",", "this", ".", "forkState", ".", "get", "(", ")", ".", "name", "(", ")", ")", ")", ";", "}", "}" ]
Compare and set the state of this {@link Fork} to a new state if and only if the current state is equal to the expected state. Throw an exception if the state did not match.
[ "Compare", "and", "set", "the", "state", "of", "this", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/fork/Fork.java#L635-L640
looly/hutool
hutool-crypto/src/main/java/cn/hutool/crypto/SecureUtil.java
SecureUtil.signParams
public static String signParams(SymmetricCrypto crypto, Map<?, ?> params) { """ 对参数做签名<br> 参数签名为对Map参数按照key的顺序排序后拼接为字符串,然后根据提供的签名算法生成签名字符串<br> 拼接后的字符串键值对之间无符号,键值对之间无符号,忽略null值 @param crypto 对称加密算法 @param params 参数 @return 签名 @since 4.0.1 """ return signParams(crypto, params, StrUtil.EMPTY, StrUtil.EMPTY, true); }
java
public static String signParams(SymmetricCrypto crypto, Map<?, ?> params) { return signParams(crypto, params, StrUtil.EMPTY, StrUtil.EMPTY, true); }
[ "public", "static", "String", "signParams", "(", "SymmetricCrypto", "crypto", ",", "Map", "<", "?", ",", "?", ">", "params", ")", "{", "return", "signParams", "(", "crypto", ",", "params", ",", "StrUtil", ".", "EMPTY", ",", "StrUtil", ".", "EMPTY", ",", "true", ")", ";", "}" ]
对参数做签名<br> 参数签名为对Map参数按照key的顺序排序后拼接为字符串,然后根据提供的签名算法生成签名字符串<br> 拼接后的字符串键值对之间无符号,键值对之间无符号,忽略null值 @param crypto 对称加密算法 @param params 参数 @return 签名 @since 4.0.1
[ "对参数做签名<br", ">", "参数签名为对Map参数按照key的顺序排序后拼接为字符串,然后根据提供的签名算法生成签名字符串<br", ">", "拼接后的字符串键值对之间无符号,键值对之间无符号,忽略null值" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/SecureUtil.java#L831-L833
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.feature.core/src/com/ibm/ws/kernel/feature/internal/PackageInspectorImpl.java
PackageInspectorImpl.populateSPIInfo
final void populateSPIInfo(BundleContext bundleContext, FeatureManager fm) { """ This method creates and sets new instances of the two maps used to answer questions about packages in the system: <OL> <LI>The set of currently installed features is iterated querying the bundle resources for each feature <LI> The list of currently installed bundles (getBundles()) is iterated <LI> each bundle is checked against each feature definition <LI> feature definitions with matching bundles are added to the collection <LI> the collection is added to the map, keyed by bundle for faster checks during resolution. </OL> """ //if the bundleContext is null we aren't going to be able to do this if (bundleContext != null) { // We're going to rebuild new indices, so use local variables ProductPackages newPackageIndex = new ProductPackages(); // For figuring out SPI information, we need the installed features and the kernel features. Collection<ProvisioningFeatureDefinition> allInstalledFeatures = fm.getInstalledFeatureDefinitions(); allInstalledFeatures.addAll(KernelFeatureDefinitionImpl.getKernelFeatures(bundleContext, fm.getLocationService())); // For all installed features, get information about the declared product packages // and the declared osgi bundles.. for (ProvisioningFeatureDefinition def : allInstalledFeatures) { // Add package information to ProductPackages.. newPackageIndex.addPackages(def); } // compact the read-only index newPackageIndex.compact(); // Replace the member variables with the new instances packageIndex = newPackageIndex; } }
java
final void populateSPIInfo(BundleContext bundleContext, FeatureManager fm) { //if the bundleContext is null we aren't going to be able to do this if (bundleContext != null) { // We're going to rebuild new indices, so use local variables ProductPackages newPackageIndex = new ProductPackages(); // For figuring out SPI information, we need the installed features and the kernel features. Collection<ProvisioningFeatureDefinition> allInstalledFeatures = fm.getInstalledFeatureDefinitions(); allInstalledFeatures.addAll(KernelFeatureDefinitionImpl.getKernelFeatures(bundleContext, fm.getLocationService())); // For all installed features, get information about the declared product packages // and the declared osgi bundles.. for (ProvisioningFeatureDefinition def : allInstalledFeatures) { // Add package information to ProductPackages.. newPackageIndex.addPackages(def); } // compact the read-only index newPackageIndex.compact(); // Replace the member variables with the new instances packageIndex = newPackageIndex; } }
[ "final", "void", "populateSPIInfo", "(", "BundleContext", "bundleContext", ",", "FeatureManager", "fm", ")", "{", "//if the bundleContext is null we aren't going to be able to do this", "if", "(", "bundleContext", "!=", "null", ")", "{", "// We're going to rebuild new indices, so use local variables", "ProductPackages", "newPackageIndex", "=", "new", "ProductPackages", "(", ")", ";", "// For figuring out SPI information, we need the installed features and the kernel features.", "Collection", "<", "ProvisioningFeatureDefinition", ">", "allInstalledFeatures", "=", "fm", ".", "getInstalledFeatureDefinitions", "(", ")", ";", "allInstalledFeatures", ".", "addAll", "(", "KernelFeatureDefinitionImpl", ".", "getKernelFeatures", "(", "bundleContext", ",", "fm", ".", "getLocationService", "(", ")", ")", ")", ";", "// For all installed features, get information about the declared product packages", "// and the declared osgi bundles..", "for", "(", "ProvisioningFeatureDefinition", "def", ":", "allInstalledFeatures", ")", "{", "// Add package information to ProductPackages..", "newPackageIndex", ".", "addPackages", "(", "def", ")", ";", "}", "// compact the read-only index", "newPackageIndex", ".", "compact", "(", ")", ";", "// Replace the member variables with the new instances", "packageIndex", "=", "newPackageIndex", ";", "}", "}" ]
This method creates and sets new instances of the two maps used to answer questions about packages in the system: <OL> <LI>The set of currently installed features is iterated querying the bundle resources for each feature <LI> The list of currently installed bundles (getBundles()) is iterated <LI> each bundle is checked against each feature definition <LI> feature definitions with matching bundles are added to the collection <LI> the collection is added to the map, keyed by bundle for faster checks during resolution. </OL>
[ "This", "method", "creates", "and", "sets", "new", "instances", "of", "the", "two", "maps", "used", "to", "answer", "questions", "about", "packages", "in", "the", "system", ":", "<OL", ">", "<LI", ">", "The", "set", "of", "currently", "installed", "features", "is", "iterated", "querying", "the", "bundle", "resources", "for", "each", "feature", "<LI", ">", "The", "list", "of", "currently", "installed", "bundles", "(", "getBundles", "()", ")", "is", "iterated", "<LI", ">", "each", "bundle", "is", "checked", "against", "each", "feature", "definition", "<LI", ">", "feature", "definitions", "with", "matching", "bundles", "are", "added", "to", "the", "collection", "<LI", ">", "the", "collection", "is", "added", "to", "the", "map", "keyed", "by", "bundle", "for", "faster", "checks", "during", "resolution", ".", "<", "/", "OL", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.feature.core/src/com/ibm/ws/kernel/feature/internal/PackageInspectorImpl.java#L78-L103
OpenLiberty/open-liberty
dev/com.ibm.ws.artifact.zip/src/com/ibm/ws/artifact/zip/internal/ZipFileArtifactNotifier.java
ZipFileArtifactNotifier.validateNotification
@Trivial private String validateNotification(Collection<?> added, Collection<?> removed, Collection<?> updated) { """ Validate change data, which is expected to be collections of files or collections of entry paths. Since the single root zip file is registered, the change is expected to be a single element in exactly one of the change collections. Null changes are unexpected. Additions are unexpected. Updates with removals are unexpected. The net is to allow updates alone or removals alone. @return A validation message if unexpected changes are noted. Null if the changes are expected. """ boolean isAddition = !added.isEmpty(); boolean isRemoval = !removed.isEmpty(); boolean isUpdate = !updated.isEmpty(); if ( !isAddition && !isRemoval && !isUpdate ) { // Should never occur: // Completely null changes are detected and cause an early return // before reaching the validation method. return "null"; } else if ( isAddition ) { return "Addition of [ " + added.toString() + " ]"; } else if ( isUpdate && isRemoval ) { return "Update of [ " + updated.toString() + " ]" + " with removal of [ " + removed.toString() + " ]"; } else { return null; } }
java
@Trivial private String validateNotification(Collection<?> added, Collection<?> removed, Collection<?> updated) { boolean isAddition = !added.isEmpty(); boolean isRemoval = !removed.isEmpty(); boolean isUpdate = !updated.isEmpty(); if ( !isAddition && !isRemoval && !isUpdate ) { // Should never occur: // Completely null changes are detected and cause an early return // before reaching the validation method. return "null"; } else if ( isAddition ) { return "Addition of [ " + added.toString() + " ]"; } else if ( isUpdate && isRemoval ) { return "Update of [ " + updated.toString() + " ]" + " with removal of [ " + removed.toString() + " ]"; } else { return null; } }
[ "@", "Trivial", "private", "String", "validateNotification", "(", "Collection", "<", "?", ">", "added", ",", "Collection", "<", "?", ">", "removed", ",", "Collection", "<", "?", ">", "updated", ")", "{", "boolean", "isAddition", "=", "!", "added", ".", "isEmpty", "(", ")", ";", "boolean", "isRemoval", "=", "!", "removed", ".", "isEmpty", "(", ")", ";", "boolean", "isUpdate", "=", "!", "updated", ".", "isEmpty", "(", ")", ";", "if", "(", "!", "isAddition", "&&", "!", "isRemoval", "&&", "!", "isUpdate", ")", "{", "// Should never occur:", "// Completely null changes are detected and cause an early return", "// before reaching the validation method.", "return", "\"null\"", ";", "}", "else", "if", "(", "isAddition", ")", "{", "return", "\"Addition of [ \"", "+", "added", ".", "toString", "(", ")", "+", "\" ]\"", ";", "}", "else", "if", "(", "isUpdate", "&&", "isRemoval", ")", "{", "return", "\"Update of [ \"", "+", "updated", ".", "toString", "(", ")", "+", "\" ]\"", "+", "\" with removal of [ \"", "+", "removed", ".", "toString", "(", ")", "+", "\" ]\"", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Validate change data, which is expected to be collections of files or collections of entry paths. Since the single root zip file is registered, the change is expected to be a single element in exactly one of the change collections. Null changes are unexpected. Additions are unexpected. Updates with removals are unexpected. The net is to allow updates alone or removals alone. @return A validation message if unexpected changes are noted. Null if the changes are expected.
[ "Validate", "change", "data", "which", "is", "expected", "to", "be", "collections", "of", "files", "or", "collections", "of", "entry", "paths", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.artifact.zip/src/com/ibm/ws/artifact/zip/internal/ZipFileArtifactNotifier.java#L745-L767
katharsis-project/katharsis-framework
katharsis-core/src/main/java/io/katharsis/legacy/queryParams/QueryParamsBuilder.java
QueryParamsBuilder.buildQueryParams
public QueryParams buildQueryParams(Map<String, Set<String>> queryParams) { """ Decodes passed query parameters using the given raw map. Mainly intended to be used for testing purposes. For most cases, use {@link #buildQueryParams(QueryParamsParserContext context) instead.} @param queryParams Map of provided query params @return QueryParams containing filtered query params grouped by JSON:API standard @throws ParametersDeserializationException thrown when unsupported input format is detected """ return buildQueryParams(new SimpleQueryParamsParserContext(queryParams)); }
java
public QueryParams buildQueryParams(Map<String, Set<String>> queryParams) { return buildQueryParams(new SimpleQueryParamsParserContext(queryParams)); }
[ "public", "QueryParams", "buildQueryParams", "(", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "queryParams", ")", "{", "return", "buildQueryParams", "(", "new", "SimpleQueryParamsParserContext", "(", "queryParams", ")", ")", ";", "}" ]
Decodes passed query parameters using the given raw map. Mainly intended to be used for testing purposes. For most cases, use {@link #buildQueryParams(QueryParamsParserContext context) instead.} @param queryParams Map of provided query params @return QueryParams containing filtered query params grouped by JSON:API standard @throws ParametersDeserializationException thrown when unsupported input format is detected
[ "Decodes", "passed", "query", "parameters", "using", "the", "given", "raw", "map", ".", "Mainly", "intended", "to", "be", "used", "for", "testing", "purposes", ".", "For", "most", "cases", "use", "{", "@link", "#buildQueryParams", "(", "QueryParamsParserContext", "context", ")", "instead", ".", "}" ]
train
https://github.com/katharsis-project/katharsis-framework/blob/73d1a8763c49c5cf4643d43e2dbfedb647630c46/katharsis-core/src/main/java/io/katharsis/legacy/queryParams/QueryParamsBuilder.java#L44-L46
facebook/fresco
imagepipeline-base/src/main/java/com/facebook/imageformat/DefaultImageFormatChecker.java
DefaultImageFormatChecker.isBmpHeader
private static boolean isBmpHeader(final byte[] imageHeaderBytes, final int headerSize) { """ Checks if first headerSize bytes of imageHeaderBytes constitute a valid header for a bmp image. Details on BMP header can be found <a href="http://www.onicos.com/staff/iz/formats/bmp.html"> </a> @param imageHeaderBytes @param headerSize @return true if imageHeaderBytes is a valid header for a bmp image """ if (headerSize < BMP_HEADER.length) { return false; } return ImageFormatCheckerUtils.startsWithPattern(imageHeaderBytes, BMP_HEADER); }
java
private static boolean isBmpHeader(final byte[] imageHeaderBytes, final int headerSize) { if (headerSize < BMP_HEADER.length) { return false; } return ImageFormatCheckerUtils.startsWithPattern(imageHeaderBytes, BMP_HEADER); }
[ "private", "static", "boolean", "isBmpHeader", "(", "final", "byte", "[", "]", "imageHeaderBytes", ",", "final", "int", "headerSize", ")", "{", "if", "(", "headerSize", "<", "BMP_HEADER", ".", "length", ")", "{", "return", "false", ";", "}", "return", "ImageFormatCheckerUtils", ".", "startsWithPattern", "(", "imageHeaderBytes", ",", "BMP_HEADER", ")", ";", "}" ]
Checks if first headerSize bytes of imageHeaderBytes constitute a valid header for a bmp image. Details on BMP header can be found <a href="http://www.onicos.com/staff/iz/formats/bmp.html"> </a> @param imageHeaderBytes @param headerSize @return true if imageHeaderBytes is a valid header for a bmp image
[ "Checks", "if", "first", "headerSize", "bytes", "of", "imageHeaderBytes", "constitute", "a", "valid", "header", "for", "a", "bmp", "image", ".", "Details", "on", "BMP", "header", "can", "be", "found", "<a", "href", "=", "http", ":", "//", "www", ".", "onicos", ".", "com", "/", "staff", "/", "iz", "/", "formats", "/", "bmp", ".", "html", ">", "<", "/", "a", ">" ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageformat/DefaultImageFormatChecker.java#L212-L217
zaproxy/zaproxy
src/ch/csnc/extension/httpclient/SSLContextManager.java
SSLContextManager.initPKCS11
public int initPKCS11(PKCS11Configuration configuration, String kspassword) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { """ /* public int initCryptoApi() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{ Provider mscapi = new sun.security.mscapi.SunMSCAPI(); Security.addProvider(mscapi); KeyStore ks = KeyStore.getInstance("Windows-MY"); ks.load(null, null); return addKeyStore(ks, "CryptoAPI", null); } """ if (!isProviderAvailable(PKCS11_PROVIDER_TYPE)) { return -1; } Provider pkcs11 = createPKCS11Provider(configuration); Security.addProvider(pkcs11); // init the key store KeyStore ks = getPKCS11KeyStore(pkcs11.getName()); ks.load(null, kspassword == null ? null : kspassword.toCharArray()); return addKeyStore(ks, "PKCS#11: " + configuration.getName(), ""); // do not store pin code }
java
public int initPKCS11(PKCS11Configuration configuration, String kspassword) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { if (!isProviderAvailable(PKCS11_PROVIDER_TYPE)) { return -1; } Provider pkcs11 = createPKCS11Provider(configuration); Security.addProvider(pkcs11); // init the key store KeyStore ks = getPKCS11KeyStore(pkcs11.getName()); ks.load(null, kspassword == null ? null : kspassword.toCharArray()); return addKeyStore(ks, "PKCS#11: " + configuration.getName(), ""); // do not store pin code }
[ "public", "int", "initPKCS11", "(", "PKCS11Configuration", "configuration", ",", "String", "kspassword", ")", "throws", "IOException", ",", "KeyStoreException", ",", "CertificateException", ",", "NoSuchAlgorithmException", ",", "ClassNotFoundException", ",", "SecurityException", ",", "NoSuchMethodException", ",", "IllegalArgumentException", ",", "InstantiationException", ",", "IllegalAccessException", ",", "InvocationTargetException", "{", "if", "(", "!", "isProviderAvailable", "(", "PKCS11_PROVIDER_TYPE", ")", ")", "{", "return", "-", "1", ";", "}", "Provider", "pkcs11", "=", "createPKCS11Provider", "(", "configuration", ")", ";", "Security", ".", "addProvider", "(", "pkcs11", ")", ";", "// init the key store", "KeyStore", "ks", "=", "getPKCS11KeyStore", "(", "pkcs11", ".", "getName", "(", ")", ")", ";", "ks", ".", "load", "(", "null", ",", "kspassword", "==", "null", "?", "null", ":", "kspassword", ".", "toCharArray", "(", ")", ")", ";", "return", "addKeyStore", "(", "ks", ",", "\"PKCS#11: \"", "+", "configuration", ".", "getName", "(", ")", ",", "\"\"", ")", ";", "// do not store pin code", "}" ]
/* public int initCryptoApi() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{ Provider mscapi = new sun.security.mscapi.SunMSCAPI(); Security.addProvider(mscapi); KeyStore ks = KeyStore.getInstance("Windows-MY"); ks.load(null, null); return addKeyStore(ks, "CryptoAPI", null); }
[ "/", "*", "public", "int", "initCryptoApi", "()", "throws", "KeyStoreException", "NoSuchAlgorithmException", "CertificateException", "IOException", "{" ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/ch/csnc/extension/httpclient/SSLContextManager.java#L355-L374
alkacon/opencms-core
src/org/opencms/file/CmsProperty.java
CmsProperty.getLocalizedKey
public static String getLocalizedKey(Map<String, ?> propertiesMap, String key, Locale locale) { """ Returns the key for the best matching local-specific property version. @param propertiesMap the "raw" property map @param key the name of the property to search for @param locale the locale to search for @return the key for the best matching local-specific property version. """ List<String> localizedKeys = CmsLocaleManager.getLocaleVariants(key, locale, true, false); for (String localizedKey : localizedKeys) { if (propertiesMap.containsKey(localizedKey)) { return localizedKey; } } return key; }
java
public static String getLocalizedKey(Map<String, ?> propertiesMap, String key, Locale locale) { List<String> localizedKeys = CmsLocaleManager.getLocaleVariants(key, locale, true, false); for (String localizedKey : localizedKeys) { if (propertiesMap.containsKey(localizedKey)) { return localizedKey; } } return key; }
[ "public", "static", "String", "getLocalizedKey", "(", "Map", "<", "String", ",", "?", ">", "propertiesMap", ",", "String", "key", ",", "Locale", "locale", ")", "{", "List", "<", "String", ">", "localizedKeys", "=", "CmsLocaleManager", ".", "getLocaleVariants", "(", "key", ",", "locale", ",", "true", ",", "false", ")", ";", "for", "(", "String", "localizedKey", ":", "localizedKeys", ")", "{", "if", "(", "propertiesMap", ".", "containsKey", "(", "localizedKey", ")", ")", "{", "return", "localizedKey", ";", "}", "}", "return", "key", ";", "}" ]
Returns the key for the best matching local-specific property version. @param propertiesMap the "raw" property map @param key the name of the property to search for @param locale the locale to search for @return the key for the best matching local-specific property version.
[ "Returns", "the", "key", "for", "the", "best", "matching", "local", "-", "specific", "property", "version", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsProperty.java#L328-L337
OpenFeign/feign
core/src/main/java/feign/RequestTemplate.java
RequestTemplate.appendHeader
private RequestTemplate appendHeader(String name, Iterable<String> values) { """ Create a Header Template. @param name of the header @param values for the header, may be expressions. @return a RequestTemplate for chaining. """ if (!values.iterator().hasNext()) { /* empty value, clear the existing values */ this.headers.remove(name); return this; } this.headers.compute(name, (headerName, headerTemplate) -> { if (headerTemplate == null) { return HeaderTemplate.create(headerName, values); } else { return HeaderTemplate.append(headerTemplate, values); } }); return this; }
java
private RequestTemplate appendHeader(String name, Iterable<String> values) { if (!values.iterator().hasNext()) { /* empty value, clear the existing values */ this.headers.remove(name); return this; } this.headers.compute(name, (headerName, headerTemplate) -> { if (headerTemplate == null) { return HeaderTemplate.create(headerName, values); } else { return HeaderTemplate.append(headerTemplate, values); } }); return this; }
[ "private", "RequestTemplate", "appendHeader", "(", "String", "name", ",", "Iterable", "<", "String", ">", "values", ")", "{", "if", "(", "!", "values", ".", "iterator", "(", ")", ".", "hasNext", "(", ")", ")", "{", "/* empty value, clear the existing values */", "this", ".", "headers", ".", "remove", "(", "name", ")", ";", "return", "this", ";", "}", "this", ".", "headers", ".", "compute", "(", "name", ",", "(", "headerName", ",", "headerTemplate", ")", "->", "{", "if", "(", "headerTemplate", "==", "null", ")", "{", "return", "HeaderTemplate", ".", "create", "(", "headerName", ",", "values", ")", ";", "}", "else", "{", "return", "HeaderTemplate", ".", "append", "(", "headerTemplate", ",", "values", ")", ";", "}", "}", ")", ";", "return", "this", ";", "}" ]
Create a Header Template. @param name of the header @param values for the header, may be expressions. @return a RequestTemplate for chaining.
[ "Create", "a", "Header", "Template", "." ]
train
https://github.com/OpenFeign/feign/blob/318fb0e955b8cfcf64f70d6aeea0ba5795f8a7eb/core/src/main/java/feign/RequestTemplate.java#L685-L699
javagl/CommonUI
src/main/java/de/javagl/common/ui/table/renderer/SortOrderTableHeaderCellRenderer.java
SortOrderTableHeaderCellRenderer.getSortPriority
private static int getSortPriority(JTable table, int column) { """ Returns the sort priority of the specified column in the given table, where 0 means the highest priority, and -1 means that the column is not sorted. @param table The table @param column The column @return The sort priority """ List<? extends SortKey> sortKeys = table.getRowSorter().getSortKeys(); for (int i=0; i<sortKeys.size(); i++) { SortKey sortKey = sortKeys.get(i); if (sortKey.getColumn() == table.convertColumnIndexToModel(column)) { return i; } } return -1; }
java
private static int getSortPriority(JTable table, int column) { List<? extends SortKey> sortKeys = table.getRowSorter().getSortKeys(); for (int i=0; i<sortKeys.size(); i++) { SortKey sortKey = sortKeys.get(i); if (sortKey.getColumn() == table.convertColumnIndexToModel(column)) { return i; } } return -1; }
[ "private", "static", "int", "getSortPriority", "(", "JTable", "table", ",", "int", "column", ")", "{", "List", "<", "?", "extends", "SortKey", ">", "sortKeys", "=", "table", ".", "getRowSorter", "(", ")", ".", "getSortKeys", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sortKeys", ".", "size", "(", ")", ";", "i", "++", ")", "{", "SortKey", "sortKey", "=", "sortKeys", ".", "get", "(", "i", ")", ";", "if", "(", "sortKey", ".", "getColumn", "(", ")", "==", "table", ".", "convertColumnIndexToModel", "(", "column", ")", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
Returns the sort priority of the specified column in the given table, where 0 means the highest priority, and -1 means that the column is not sorted. @param table The table @param column The column @return The sort priority
[ "Returns", "the", "sort", "priority", "of", "the", "specified", "column", "in", "the", "given", "table", "where", "0", "means", "the", "highest", "priority", "and", "-", "1", "means", "that", "the", "column", "is", "not", "sorted", "." ]
train
https://github.com/javagl/CommonUI/blob/b2c7a7637d4e288271392ba148dc17e4c9780255/src/main/java/de/javagl/common/ui/table/renderer/SortOrderTableHeaderCellRenderer.java#L200-L212
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/filecache/FileCache.java
FileCache.createTmpFile
public Future<Path> createTmpFile(String name, DistributedCacheEntry entry, JobID jobID, ExecutionAttemptID executionId) throws Exception { """ If the file doesn't exists locally, retrieve the file from the blob-service. @param entry The cache entry descriptor (path, executable flag) @param jobID The ID of the job for which the file is copied. @return The handle to the task that copies the file. """ synchronized (lock) { Map<String, Future<Path>> jobEntries = entries.computeIfAbsent(jobID, k -> new HashMap<>()); // register reference holder final Set<ExecutionAttemptID> refHolders = jobRefHolders.computeIfAbsent(jobID, id -> new HashSet<>()); refHolders.add(executionId); Future<Path> fileEntry = jobEntries.get(name); if (fileEntry != null) { // file is already in the cache. return a future that // immediately returns the file return fileEntry; } else { // need to copy the file // create the target path File tempDirToUse = new File(storageDirectories[nextDirectory++], jobID.toString()); if (nextDirectory >= storageDirectories.length) { nextDirectory = 0; } // kick off the copying Callable<Path> cp; if (entry.blobKey != null) { cp = new CopyFromBlobProcess(entry, jobID, blobService, new Path(tempDirToUse.getAbsolutePath())); } else { cp = new CopyFromDFSProcess(entry, new Path(tempDirToUse.getAbsolutePath())); } FutureTask<Path> copyTask = new FutureTask<>(cp); executorService.submit(copyTask); // store our entry jobEntries.put(name, copyTask); return copyTask; } } }
java
public Future<Path> createTmpFile(String name, DistributedCacheEntry entry, JobID jobID, ExecutionAttemptID executionId) throws Exception { synchronized (lock) { Map<String, Future<Path>> jobEntries = entries.computeIfAbsent(jobID, k -> new HashMap<>()); // register reference holder final Set<ExecutionAttemptID> refHolders = jobRefHolders.computeIfAbsent(jobID, id -> new HashSet<>()); refHolders.add(executionId); Future<Path> fileEntry = jobEntries.get(name); if (fileEntry != null) { // file is already in the cache. return a future that // immediately returns the file return fileEntry; } else { // need to copy the file // create the target path File tempDirToUse = new File(storageDirectories[nextDirectory++], jobID.toString()); if (nextDirectory >= storageDirectories.length) { nextDirectory = 0; } // kick off the copying Callable<Path> cp; if (entry.blobKey != null) { cp = new CopyFromBlobProcess(entry, jobID, blobService, new Path(tempDirToUse.getAbsolutePath())); } else { cp = new CopyFromDFSProcess(entry, new Path(tempDirToUse.getAbsolutePath())); } FutureTask<Path> copyTask = new FutureTask<>(cp); executorService.submit(copyTask); // store our entry jobEntries.put(name, copyTask); return copyTask; } } }
[ "public", "Future", "<", "Path", ">", "createTmpFile", "(", "String", "name", ",", "DistributedCacheEntry", "entry", ",", "JobID", "jobID", ",", "ExecutionAttemptID", "executionId", ")", "throws", "Exception", "{", "synchronized", "(", "lock", ")", "{", "Map", "<", "String", ",", "Future", "<", "Path", ">", ">", "jobEntries", "=", "entries", ".", "computeIfAbsent", "(", "jobID", ",", "k", "->", "new", "HashMap", "<>", "(", ")", ")", ";", "// register reference holder", "final", "Set", "<", "ExecutionAttemptID", ">", "refHolders", "=", "jobRefHolders", ".", "computeIfAbsent", "(", "jobID", ",", "id", "->", "new", "HashSet", "<>", "(", ")", ")", ";", "refHolders", ".", "add", "(", "executionId", ")", ";", "Future", "<", "Path", ">", "fileEntry", "=", "jobEntries", ".", "get", "(", "name", ")", ";", "if", "(", "fileEntry", "!=", "null", ")", "{", "// file is already in the cache. return a future that", "// immediately returns the file", "return", "fileEntry", ";", "}", "else", "{", "// need to copy the file", "// create the target path", "File", "tempDirToUse", "=", "new", "File", "(", "storageDirectories", "[", "nextDirectory", "++", "]", ",", "jobID", ".", "toString", "(", ")", ")", ";", "if", "(", "nextDirectory", ">=", "storageDirectories", ".", "length", ")", "{", "nextDirectory", "=", "0", ";", "}", "// kick off the copying", "Callable", "<", "Path", ">", "cp", ";", "if", "(", "entry", ".", "blobKey", "!=", "null", ")", "{", "cp", "=", "new", "CopyFromBlobProcess", "(", "entry", ",", "jobID", ",", "blobService", ",", "new", "Path", "(", "tempDirToUse", ".", "getAbsolutePath", "(", ")", ")", ")", ";", "}", "else", "{", "cp", "=", "new", "CopyFromDFSProcess", "(", "entry", ",", "new", "Path", "(", "tempDirToUse", ".", "getAbsolutePath", "(", ")", ")", ")", ";", "}", "FutureTask", "<", "Path", ">", "copyTask", "=", "new", "FutureTask", "<>", "(", "cp", ")", ";", "executorService", ".", "submit", "(", "copyTask", ")", ";", "// store our entry", "jobEntries", ".", "put", "(", "name", ",", "copyTask", ")", ";", "return", "copyTask", ";", "}", "}", "}" ]
If the file doesn't exists locally, retrieve the file from the blob-service. @param entry The cache entry descriptor (path, executable flag) @param jobID The ID of the job for which the file is copied. @return The handle to the task that copies the file.
[ "If", "the", "file", "doesn", "t", "exists", "locally", "retrieve", "the", "file", "from", "the", "blob", "-", "service", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/filecache/FileCache.java#L174-L212
davidmoten/rxjava-jdbc
src/main/java/com/github/davidmoten/rx/jdbc/Util.java
Util.autoMap
static <T> ResultSetMapper<T> autoMap(final Class<T> cls) { """ Returns a function that converts the ResultSet column values into parameters to the constructor (with number of parameters equals the number of columns) of type <code>cls</code> then returns an instance of type <code>cls</code>. See {@link Builder#autoMap(Class)}. @param cls @return """ return new ResultSetMapper<T>() { @Override public T call(ResultSet rs) { return autoMap(rs, cls); } }; }
java
static <T> ResultSetMapper<T> autoMap(final Class<T> cls) { return new ResultSetMapper<T>() { @Override public T call(ResultSet rs) { return autoMap(rs, cls); } }; }
[ "static", "<", "T", ">", "ResultSetMapper", "<", "T", ">", "autoMap", "(", "final", "Class", "<", "T", ">", "cls", ")", "{", "return", "new", "ResultSetMapper", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "T", "call", "(", "ResultSet", "rs", ")", "{", "return", "autoMap", "(", "rs", ",", "cls", ")", ";", "}", "}", ";", "}" ]
Returns a function that converts the ResultSet column values into parameters to the constructor (with number of parameters equals the number of columns) of type <code>cls</code> then returns an instance of type <code>cls</code>. See {@link Builder#autoMap(Class)}. @param cls @return
[ "Returns", "a", "function", "that", "converts", "the", "ResultSet", "column", "values", "into", "parameters", "to", "the", "constructor", "(", "with", "number", "of", "parameters", "equals", "the", "number", "of", "columns", ")", "of", "type", "<code", ">", "cls<", "/", "code", ">", "then", "returns", "an", "instance", "of", "type", "<code", ">", "cls<", "/", "code", ">", ".", "See", "{", "@link", "Builder#autoMap", "(", "Class", ")", "}", "." ]
train
https://github.com/davidmoten/rxjava-jdbc/blob/81e157d7071a825086bde81107b8694684cdff14/src/main/java/com/github/davidmoten/rx/jdbc/Util.java#L256-L263
stevespringett/Alpine
alpine/src/main/java/alpine/crypto/DataEncryption.java
DataEncryption.decryptAsBytes
public static byte[] decryptAsBytes(final byte[] encryptedIvTextBytes) throws Exception { """ Decrypts the specified bytes using AES-256. This method uses the default secret key. @param encryptedIvTextBytes the text to decrypt @return the decrypted bytes @throws Exception a number of exceptions may be thrown @since 1.3.0 """ final SecretKey secretKey = KeyManager.getInstance().getSecretKey(); return decryptAsBytes(secretKey, encryptedIvTextBytes); }
java
public static byte[] decryptAsBytes(final byte[] encryptedIvTextBytes) throws Exception { final SecretKey secretKey = KeyManager.getInstance().getSecretKey(); return decryptAsBytes(secretKey, encryptedIvTextBytes); }
[ "public", "static", "byte", "[", "]", "decryptAsBytes", "(", "final", "byte", "[", "]", "encryptedIvTextBytes", ")", "throws", "Exception", "{", "final", "SecretKey", "secretKey", "=", "KeyManager", ".", "getInstance", "(", ")", ".", "getSecretKey", "(", ")", ";", "return", "decryptAsBytes", "(", "secretKey", ",", "encryptedIvTextBytes", ")", ";", "}" ]
Decrypts the specified bytes using AES-256. This method uses the default secret key. @param encryptedIvTextBytes the text to decrypt @return the decrypted bytes @throws Exception a number of exceptions may be thrown @since 1.3.0
[ "Decrypts", "the", "specified", "bytes", "using", "AES", "-", "256", ".", "This", "method", "uses", "the", "default", "secret", "key", "." ]
train
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/crypto/DataEncryption.java#L145-L148
phax/ph-commons
ph-xml/src/main/java/com/helger/xml/microdom/serialize/MicroWriter.java
MicroWriter.getNodeAsBytes
@Nullable public static byte [] getNodeAsBytes (@Nonnull final IMicroNode aNode, @Nonnull final IXMLWriterSettings aSettings) { """ Convert the passed micro node to an XML byte array using the provided settings. @param aNode The node to be converted to a byte array. May not be <code>null</code> . @param aSettings The XML writer settings to use. May not be <code>null</code>. @return The byte array representation of the passed node. @since 8.6.3 """ ValueEnforcer.notNull (aNode, "Node"); ValueEnforcer.notNull (aSettings, "Settings"); try ( final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream (50 * CGlobal.BYTES_PER_KILOBYTE)) { // start serializing if (writeToStream (aNode, aBAOS, aSettings).isSuccess ()) return aBAOS.toByteArray (); } catch (final Exception ex) { if (LOGGER.isErrorEnabled ()) LOGGER.error ("Error serializing MicroDOM with settings " + aSettings.toString (), ex); } return null; }
java
@Nullable public static byte [] getNodeAsBytes (@Nonnull final IMicroNode aNode, @Nonnull final IXMLWriterSettings aSettings) { ValueEnforcer.notNull (aNode, "Node"); ValueEnforcer.notNull (aSettings, "Settings"); try ( final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream (50 * CGlobal.BYTES_PER_KILOBYTE)) { // start serializing if (writeToStream (aNode, aBAOS, aSettings).isSuccess ()) return aBAOS.toByteArray (); } catch (final Exception ex) { if (LOGGER.isErrorEnabled ()) LOGGER.error ("Error serializing MicroDOM with settings " + aSettings.toString (), ex); } return null; }
[ "@", "Nullable", "public", "static", "byte", "[", "]", "getNodeAsBytes", "(", "@", "Nonnull", "final", "IMicroNode", "aNode", ",", "@", "Nonnull", "final", "IXMLWriterSettings", "aSettings", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aNode", ",", "\"Node\"", ")", ";", "ValueEnforcer", ".", "notNull", "(", "aSettings", ",", "\"Settings\"", ")", ";", "try", "(", "final", "NonBlockingByteArrayOutputStream", "aBAOS", "=", "new", "NonBlockingByteArrayOutputStream", "(", "50", "*", "CGlobal", ".", "BYTES_PER_KILOBYTE", ")", ")", "{", "// start serializing", "if", "(", "writeToStream", "(", "aNode", ",", "aBAOS", ",", "aSettings", ")", ".", "isSuccess", "(", ")", ")", "return", "aBAOS", ".", "toByteArray", "(", ")", ";", "}", "catch", "(", "final", "Exception", "ex", ")", "{", "if", "(", "LOGGER", ".", "isErrorEnabled", "(", ")", ")", "LOGGER", ".", "error", "(", "\"Error serializing MicroDOM with settings \"", "+", "aSettings", ".", "toString", "(", ")", ",", "ex", ")", ";", "}", "return", "null", ";", "}" ]
Convert the passed micro node to an XML byte array using the provided settings. @param aNode The node to be converted to a byte array. May not be <code>null</code> . @param aSettings The XML writer settings to use. May not be <code>null</code>. @return The byte array representation of the passed node. @since 8.6.3
[ "Convert", "the", "passed", "micro", "node", "to", "an", "XML", "byte", "array", "using", "the", "provided", "settings", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/microdom/serialize/MicroWriter.java#L310-L330
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.purgeDeletedStorageAccountAsync
public Observable<Void> purgeDeletedStorageAccountAsync(String vaultBaseUrl, String storageAccountName) { """ Permanently deletes the specified storage account. The purge deleted storage account operation removes the secret permanently, without the possibility of recovery. This operation can only be performed on a soft-delete enabled vault. This operation requires the storage/purge permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful. """ return purgeDeletedStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> purgeDeletedStorageAccountAsync(String vaultBaseUrl, String storageAccountName) { return purgeDeletedStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "purgeDeletedStorageAccountAsync", "(", "String", "vaultBaseUrl", ",", "String", "storageAccountName", ")", "{", "return", "purgeDeletedStorageAccountWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "storageAccountName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Permanently deletes the specified storage account. The purge deleted storage account operation removes the secret permanently, without the possibility of recovery. This operation can only be performed on a soft-delete enabled vault. This operation requires the storage/purge permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Permanently", "deletes", "the", "specified", "storage", "account", ".", "The", "purge", "deleted", "storage", "account", "operation", "removes", "the", "secret", "permanently", "without", "the", "possibility", "of", "recovery", ".", "This", "operation", "can", "only", "be", "performed", "on", "a", "soft", "-", "delete", "enabled", "vault", ".", "This", "operation", "requires", "the", "storage", "/", "purge", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L9371-L9378
softindex/datakernel
boot/src/main/java/io/datakernel/service/ServiceGraphModule.java
ServiceGraphModule.register
public <T> ServiceGraphModule register(Class<? extends T> type, ServiceAdapter<T> factory) { """ Puts an instance of class and its factory to the factoryMap @param <T> type of service @param type key with which the specified factory is to be associated @param factory value to be associated with the specified type @return ServiceGraphModule with change """ registeredServiceAdapters.put(type, factory); return this; }
java
public <T> ServiceGraphModule register(Class<? extends T> type, ServiceAdapter<T> factory) { registeredServiceAdapters.put(type, factory); return this; }
[ "public", "<", "T", ">", "ServiceGraphModule", "register", "(", "Class", "<", "?", "extends", "T", ">", "type", ",", "ServiceAdapter", "<", "T", ">", "factory", ")", "{", "registeredServiceAdapters", ".", "put", "(", "type", ",", "factory", ")", ";", "return", "this", ";", "}" ]
Puts an instance of class and its factory to the factoryMap @param <T> type of service @param type key with which the specified factory is to be associated @param factory value to be associated with the specified type @return ServiceGraphModule with change
[ "Puts", "an", "instance", "of", "class", "and", "its", "factory", "to", "the", "factoryMap" ]
train
https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/boot/src/main/java/io/datakernel/service/ServiceGraphModule.java#L143-L146
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java
AbstractContextSource.setupAuthenticatedEnvironment
protected void setupAuthenticatedEnvironment(Hashtable<String, Object> env, String principal, String credentials) { """ Default implementation of setting the environment up to be authenticated. This method should typically NOT be overridden; any customization to the authentication mechanism should be managed by setting a different {@link DirContextAuthenticationStrategy} on this instance. @param env the environment to modify. @param principal the principal to authenticate with. @param credentials the credentials to authenticate with. @see DirContextAuthenticationStrategy @see #setAuthenticationStrategy(DirContextAuthenticationStrategy) """ try { authenticationStrategy.setupEnvironment(env, principal, credentials); } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } }
java
protected void setupAuthenticatedEnvironment(Hashtable<String, Object> env, String principal, String credentials) { try { authenticationStrategy.setupEnvironment(env, principal, credentials); } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } }
[ "protected", "void", "setupAuthenticatedEnvironment", "(", "Hashtable", "<", "String", ",", "Object", ">", "env", ",", "String", "principal", ",", "String", "credentials", ")", "{", "try", "{", "authenticationStrategy", ".", "setupEnvironment", "(", "env", ",", "principal", ",", "credentials", ")", ";", "}", "catch", "(", "NamingException", "e", ")", "{", "throw", "LdapUtils", ".", "convertLdapException", "(", "e", ")", ";", "}", "}" ]
Default implementation of setting the environment up to be authenticated. This method should typically NOT be overridden; any customization to the authentication mechanism should be managed by setting a different {@link DirContextAuthenticationStrategy} on this instance. @param env the environment to modify. @param principal the principal to authenticate with. @param credentials the credentials to authenticate with. @see DirContextAuthenticationStrategy @see #setAuthenticationStrategy(DirContextAuthenticationStrategy)
[ "Default", "implementation", "of", "setting", "the", "environment", "up", "to", "be", "authenticated", ".", "This", "method", "should", "typically", "NOT", "be", "overridden", ";", "any", "customization", "to", "the", "authentication", "mechanism", "should", "be", "managed", "by", "setting", "a", "different", "{", "@link", "DirContextAuthenticationStrategy", "}", "on", "this", "instance", "." ]
train
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java#L192-L199
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConfigurationImpl.java
ConfigurationImpl.getContent
@Override public Content getContent(String key, Object o1, Object o2) { """ Get the configuration string as a content. @param key the key to look for in the configuration file @param o1 resource argument @param o2 resource argument @return a content tree for the text """ return contents.getContent(key, o1, o2); }
java
@Override public Content getContent(String key, Object o1, Object o2) { return contents.getContent(key, o1, o2); }
[ "@", "Override", "public", "Content", "getContent", "(", "String", "key", ",", "Object", "o1", ",", "Object", "o2", ")", "{", "return", "contents", ".", "getContent", "(", "key", ",", "o1", ",", "o2", ")", ";", "}" ]
Get the configuration string as a content. @param key the key to look for in the configuration file @param o1 resource argument @param o2 resource argument @return a content tree for the text
[ "Get", "the", "configuration", "string", "as", "a", "content", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConfigurationImpl.java#L501-L504
Impetus/Kundera
src/kundera-elastic-search/src/main/java/com/impetus/client/es/utils/ESResponseWrapper.java
ESResponseWrapper.filterBuckets
private Terms filterBuckets(Terms buckets, KunderaQuery query) { """ Filter buckets. @param buckets the buckets @param query the query @return the terms """ Expression havingClause = query.getSelectStatement().getHavingClause(); if (!(havingClause instanceof NullExpression) && havingClause != null) { Expression conditionalExpression = ((HavingClause) havingClause).getConditionalExpression(); for (Iterator<Bucket> bucketIterator = buckets.getBuckets().iterator(); bucketIterator.hasNext();) { InternalAggregations internalAgg = (InternalAggregations) bucketIterator.next().getAggregations(); if (!isValidBucket(internalAgg, query, conditionalExpression)) { bucketIterator.remove(); } } } return buckets; }
java
private Terms filterBuckets(Terms buckets, KunderaQuery query) { Expression havingClause = query.getSelectStatement().getHavingClause(); if (!(havingClause instanceof NullExpression) && havingClause != null) { Expression conditionalExpression = ((HavingClause) havingClause).getConditionalExpression(); for (Iterator<Bucket> bucketIterator = buckets.getBuckets().iterator(); bucketIterator.hasNext();) { InternalAggregations internalAgg = (InternalAggregations) bucketIterator.next().getAggregations(); if (!isValidBucket(internalAgg, query, conditionalExpression)) { bucketIterator.remove(); } } } return buckets; }
[ "private", "Terms", "filterBuckets", "(", "Terms", "buckets", ",", "KunderaQuery", "query", ")", "{", "Expression", "havingClause", "=", "query", ".", "getSelectStatement", "(", ")", ".", "getHavingClause", "(", ")", ";", "if", "(", "!", "(", "havingClause", "instanceof", "NullExpression", ")", "&&", "havingClause", "!=", "null", ")", "{", "Expression", "conditionalExpression", "=", "(", "(", "HavingClause", ")", "havingClause", ")", ".", "getConditionalExpression", "(", ")", ";", "for", "(", "Iterator", "<", "Bucket", ">", "bucketIterator", "=", "buckets", ".", "getBuckets", "(", ")", ".", "iterator", "(", ")", ";", "bucketIterator", ".", "hasNext", "(", ")", ";", ")", "{", "InternalAggregations", "internalAgg", "=", "(", "InternalAggregations", ")", "bucketIterator", ".", "next", "(", ")", ".", "getAggregations", "(", ")", ";", "if", "(", "!", "isValidBucket", "(", "internalAgg", ",", "query", ",", "conditionalExpression", ")", ")", "{", "bucketIterator", ".", "remove", "(", ")", ";", "}", "}", "}", "return", "buckets", ";", "}" ]
Filter buckets. @param buckets the buckets @param query the query @return the terms
[ "Filter", "buckets", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-elastic-search/src/main/java/com/impetus/client/es/utils/ESResponseWrapper.java#L364-L382
tango-controls/JTango
server/src/main/java/org/tango/server/servant/DeviceImpl.java
DeviceImpl.setAroundInvokeImpl
public void setAroundInvokeImpl(final AroundInvokeImpl aroundInvokeImpl) { """ Set around invoke method {@link AroundInvoke} @param aroundInvokeImpl """ this.aroundInvokeImpl = aroundInvokeImpl; final TangoCacheManager cacheManager = new TangoCacheManager(name, deviceLock, aroundInvokeImpl); pollingManager = new PollingManager(name, cacheManager, attributeList, commandList, minPolling, minCommandPolling, minAttributePolling, cmdPollRingDepth, attrPollRingDepth); if (initImpl != null) { initImpl.setPollingManager(pollingManager); } }
java
public void setAroundInvokeImpl(final AroundInvokeImpl aroundInvokeImpl) { this.aroundInvokeImpl = aroundInvokeImpl; final TangoCacheManager cacheManager = new TangoCacheManager(name, deviceLock, aroundInvokeImpl); pollingManager = new PollingManager(name, cacheManager, attributeList, commandList, minPolling, minCommandPolling, minAttributePolling, cmdPollRingDepth, attrPollRingDepth); if (initImpl != null) { initImpl.setPollingManager(pollingManager); } }
[ "public", "void", "setAroundInvokeImpl", "(", "final", "AroundInvokeImpl", "aroundInvokeImpl", ")", "{", "this", ".", "aroundInvokeImpl", "=", "aroundInvokeImpl", ";", "final", "TangoCacheManager", "cacheManager", "=", "new", "TangoCacheManager", "(", "name", ",", "deviceLock", ",", "aroundInvokeImpl", ")", ";", "pollingManager", "=", "new", "PollingManager", "(", "name", ",", "cacheManager", ",", "attributeList", ",", "commandList", ",", "minPolling", ",", "minCommandPolling", ",", "minAttributePolling", ",", "cmdPollRingDepth", ",", "attrPollRingDepth", ")", ";", "if", "(", "initImpl", "!=", "null", ")", "{", "initImpl", ".", "setPollingManager", "(", "pollingManager", ")", ";", "}", "}" ]
Set around invoke method {@link AroundInvoke} @param aroundInvokeImpl
[ "Set", "around", "invoke", "method", "{", "@link", "AroundInvoke", "}" ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/servant/DeviceImpl.java#L2324-L2332
arakelian/more-commons
src/main/java/com/arakelian/core/utils/ExecutorUtils.java
ExecutorUtils.newThreadFactory
public static ThreadFactory newThreadFactory(final String format, final boolean daemon) { """ Returns a new thread factory that uses the given pattern to set the thread name. @param format thread name pattern, where %d can be used to specify the thread number. @param daemon true for daemon threads @return thread factory that uses the given pattern to set the thread name """ final String nameFormat; if (!format.contains("%d")) { nameFormat = format + "-%d"; } else { nameFormat = format; } return new ThreadFactoryBuilder() // .setNameFormat(nameFormat) // .setDaemon(daemon) // .build(); }
java
public static ThreadFactory newThreadFactory(final String format, final boolean daemon) { final String nameFormat; if (!format.contains("%d")) { nameFormat = format + "-%d"; } else { nameFormat = format; } return new ThreadFactoryBuilder() // .setNameFormat(nameFormat) // .setDaemon(daemon) // .build(); }
[ "public", "static", "ThreadFactory", "newThreadFactory", "(", "final", "String", "format", ",", "final", "boolean", "daemon", ")", "{", "final", "String", "nameFormat", ";", "if", "(", "!", "format", ".", "contains", "(", "\"%d\"", ")", ")", "{", "nameFormat", "=", "format", "+", "\"-%d\"", ";", "}", "else", "{", "nameFormat", "=", "format", ";", "}", "return", "new", "ThreadFactoryBuilder", "(", ")", "//", ".", "setNameFormat", "(", "nameFormat", ")", "//", ".", "setDaemon", "(", "daemon", ")", "//", ".", "build", "(", ")", ";", "}" ]
Returns a new thread factory that uses the given pattern to set the thread name. @param format thread name pattern, where %d can be used to specify the thread number. @param daemon true for daemon threads @return thread factory that uses the given pattern to set the thread name
[ "Returns", "a", "new", "thread", "factory", "that", "uses", "the", "given", "pattern", "to", "set", "the", "thread", "name", "." ]
train
https://github.com/arakelian/more-commons/blob/83c607044f64a7f6c005a67866c0ef7cb68d6e29/src/main/java/com/arakelian/core/utils/ExecutorUtils.java#L89-L101
awslabs/amazon-sqs-java-messaging-lib
src/main/java/com/amazon/sqs/javamessaging/AmazonSQSMessagingClientWrapper.java
AmazonSQSMessagingClientWrapper.queueExists
public boolean queueExists(String queueName) throws JMSException { """ Check if the requested queue exists. This function calls <code>GetQueueUrl</code> for the given queue name, returning true on success, false if it gets <code>QueueDoesNotExistException</code>. @param queueName the queue to check @return true if the queue exists, false if it doesn't. @throws JMSException """ try { amazonSQSClient.getQueueUrl(prepareRequest(new GetQueueUrlRequest(queueName))); return true; } catch (QueueDoesNotExistException e) { return false; } catch (AmazonClientException e) { throw handleException(e, "getQueueUrl"); } }
java
public boolean queueExists(String queueName) throws JMSException { try { amazonSQSClient.getQueueUrl(prepareRequest(new GetQueueUrlRequest(queueName))); return true; } catch (QueueDoesNotExistException e) { return false; } catch (AmazonClientException e) { throw handleException(e, "getQueueUrl"); } }
[ "public", "boolean", "queueExists", "(", "String", "queueName", ")", "throws", "JMSException", "{", "try", "{", "amazonSQSClient", ".", "getQueueUrl", "(", "prepareRequest", "(", "new", "GetQueueUrlRequest", "(", "queueName", ")", ")", ")", ";", "return", "true", ";", "}", "catch", "(", "QueueDoesNotExistException", "e", ")", "{", "return", "false", ";", "}", "catch", "(", "AmazonClientException", "e", ")", "{", "throw", "handleException", "(", "e", ",", "\"getQueueUrl\"", ")", ";", "}", "}" ]
Check if the requested queue exists. This function calls <code>GetQueueUrl</code> for the given queue name, returning true on success, false if it gets <code>QueueDoesNotExistException</code>. @param queueName the queue to check @return true if the queue exists, false if it doesn't. @throws JMSException
[ "Check", "if", "the", "requested", "queue", "exists", ".", "This", "function", "calls", "<code", ">", "GetQueueUrl<", "/", "code", ">", "for", "the", "given", "queue", "name", "returning", "true", "on", "success", "false", "if", "it", "gets", "<code", ">", "QueueDoesNotExistException<", "/", "code", ">", "." ]
train
https://github.com/awslabs/amazon-sqs-java-messaging-lib/blob/efa716d34d51ef1c5572790626cdb795419cb342/src/main/java/com/amazon/sqs/javamessaging/AmazonSQSMessagingClientWrapper.java#L218-L227
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.deleteGroupMember
public void deleteGroupMember(GitlabGroup group, GitlabUser user) throws IOException { """ Delete a group member. @param group the GitlabGroup @param user the GitlabUser @throws IOException on gitlab api call error """ deleteGroupMember(group.getId(), user.getId()); }
java
public void deleteGroupMember(GitlabGroup group, GitlabUser user) throws IOException { deleteGroupMember(group.getId(), user.getId()); }
[ "public", "void", "deleteGroupMember", "(", "GitlabGroup", "group", ",", "GitlabUser", "user", ")", "throws", "IOException", "{", "deleteGroupMember", "(", "group", ".", "getId", "(", ")", ",", "user", ".", "getId", "(", ")", ")", ";", "}" ]
Delete a group member. @param group the GitlabGroup @param user the GitlabUser @throws IOException on gitlab api call error
[ "Delete", "a", "group", "member", "." ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L748-L750
BlueBrain/bluima
modules/bluima_typesystem/src/main/java/de/julielab/jules/types/ace/Document.java
Document.setValues
public void setValues(int i, Entity v) { """ indexed setter for values - sets an indexed value - @generated @param i index in the array to set @param v value to set into the array """ if (Document_Type.featOkTst && ((Document_Type)jcasType).casFeat_values == null) jcasType.jcas.throwFeatMissing("values", "de.julielab.jules.types.ace.Document"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_values), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_values), i, jcasType.ll_cas.ll_getFSRef(v));}
java
public void setValues(int i, Entity v) { if (Document_Type.featOkTst && ((Document_Type)jcasType).casFeat_values == null) jcasType.jcas.throwFeatMissing("values", "de.julielab.jules.types.ace.Document"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_values), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_values), i, jcasType.ll_cas.ll_getFSRef(v));}
[ "public", "void", "setValues", "(", "int", "i", ",", "Entity", "v", ")", "{", "if", "(", "Document_Type", ".", "featOkTst", "&&", "(", "(", "Document_Type", ")", "jcasType", ")", ".", "casFeat_values", "==", "null", ")", "jcasType", ".", "jcas", ".", "throwFeatMissing", "(", "\"values\"", ",", "\"de.julielab.jules.types.ace.Document\"", ")", ";", "jcasType", ".", "jcas", ".", "checkArrayBounds", "(", "jcasType", ".", "ll_cas", ".", "ll_getRefValue", "(", "addr", ",", "(", "(", "Document_Type", ")", "jcasType", ")", ".", "casFeatCode_values", ")", ",", "i", ")", ";", "jcasType", ".", "ll_cas", ".", "ll_setRefArrayValue", "(", "jcasType", ".", "ll_cas", ".", "ll_getRefValue", "(", "addr", ",", "(", "(", "Document_Type", ")", "jcasType", ")", ".", "casFeatCode_values", ")", ",", "i", ",", "jcasType", ".", "ll_cas", ".", "ll_getFSRef", "(", "v", ")", ")", ";", "}" ]
indexed setter for values - sets an indexed value - @generated @param i index in the array to set @param v value to set into the array
[ "indexed", "setter", "for", "values", "-", "sets", "an", "indexed", "value", "-" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/ace/Document.java#L182-L186
alkacon/opencms-core
src/org/opencms/loader/CmsDefaultFileNameGenerator.java
CmsDefaultFileNameGenerator.getNewFileName
public String getNewFileName(CmsObject cms, String namePattern, int defaultDigits, boolean explorerMode) throws CmsException { """ Returns a new resource name based on the provided OpenCms user context and name pattern.<p> The pattern in this default implementation must be a path which may contain the macro <code>%(number)</code>. This will be replaced by the first "n" digit sequence for which the resulting file name is not already used. For example the pattern <code>"/file_%(number).xml"</code> would result in something like <code>"/file_00003.xml"</code>.<p> Alternatively, the macro can have the form <code>%(number:n)</code> with <code>n = {1...9}</code>, for example <code>%(number:6)</code>. In this case the default digits will be ignored and instead the digits provided as "n" will be used.<p> @param cms the current OpenCms user context @param namePattern the pattern to be used when generating the new resource name @param defaultDigits the default number of digits to use for numbering the created file names @param explorerMode if true, the file name is first tried without a numeric macro, also underscores are inserted automatically before the number macro and don't need to be part of the name pattern @return a new resource name based on the provided OpenCms user context and name pattern @throws CmsException in case something goes wrong """ String checkPattern = cms.getRequestContext().removeSiteRoot(namePattern); String folderName = CmsResource.getFolderPath(checkPattern); // must check ALL resources in folder because name doesn't care for type List<CmsResource> resources = cms.readResources(folderName, CmsResourceFilter.ALL, false); // now create a list of all the file names List<String> fileNames = new ArrayList<String>(resources.size()); for (CmsResource res : resources) { fileNames.add(cms.getSitePath(res)); } return getNewFileNameFromList(fileNames, checkPattern, defaultDigits, explorerMode); }
java
public String getNewFileName(CmsObject cms, String namePattern, int defaultDigits, boolean explorerMode) throws CmsException { String checkPattern = cms.getRequestContext().removeSiteRoot(namePattern); String folderName = CmsResource.getFolderPath(checkPattern); // must check ALL resources in folder because name doesn't care for type List<CmsResource> resources = cms.readResources(folderName, CmsResourceFilter.ALL, false); // now create a list of all the file names List<String> fileNames = new ArrayList<String>(resources.size()); for (CmsResource res : resources) { fileNames.add(cms.getSitePath(res)); } return getNewFileNameFromList(fileNames, checkPattern, defaultDigits, explorerMode); }
[ "public", "String", "getNewFileName", "(", "CmsObject", "cms", ",", "String", "namePattern", ",", "int", "defaultDigits", ",", "boolean", "explorerMode", ")", "throws", "CmsException", "{", "String", "checkPattern", "=", "cms", ".", "getRequestContext", "(", ")", ".", "removeSiteRoot", "(", "namePattern", ")", ";", "String", "folderName", "=", "CmsResource", ".", "getFolderPath", "(", "checkPattern", ")", ";", "// must check ALL resources in folder because name doesn't care for type", "List", "<", "CmsResource", ">", "resources", "=", "cms", ".", "readResources", "(", "folderName", ",", "CmsResourceFilter", ".", "ALL", ",", "false", ")", ";", "// now create a list of all the file names", "List", "<", "String", ">", "fileNames", "=", "new", "ArrayList", "<", "String", ">", "(", "resources", ".", "size", "(", ")", ")", ";", "for", "(", "CmsResource", "res", ":", "resources", ")", "{", "fileNames", ".", "add", "(", "cms", ".", "getSitePath", "(", "res", ")", ")", ";", "}", "return", "getNewFileNameFromList", "(", "fileNames", ",", "checkPattern", ",", "defaultDigits", ",", "explorerMode", ")", ";", "}" ]
Returns a new resource name based on the provided OpenCms user context and name pattern.<p> The pattern in this default implementation must be a path which may contain the macro <code>%(number)</code>. This will be replaced by the first "n" digit sequence for which the resulting file name is not already used. For example the pattern <code>"/file_%(number).xml"</code> would result in something like <code>"/file_00003.xml"</code>.<p> Alternatively, the macro can have the form <code>%(number:n)</code> with <code>n = {1...9}</code>, for example <code>%(number:6)</code>. In this case the default digits will be ignored and instead the digits provided as "n" will be used.<p> @param cms the current OpenCms user context @param namePattern the pattern to be used when generating the new resource name @param defaultDigits the default number of digits to use for numbering the created file names @param explorerMode if true, the file name is first tried without a numeric macro, also underscores are inserted automatically before the number macro and don't need to be part of the name pattern @return a new resource name based on the provided OpenCms user context and name pattern @throws CmsException in case something goes wrong
[ "Returns", "a", "new", "resource", "name", "based", "on", "the", "provided", "OpenCms", "user", "context", "and", "name", "pattern", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/loader/CmsDefaultFileNameGenerator.java#L210-L226
Kickflip/kickflip-android-sdk
sdk/src/main/java/io/kickflip/sdk/FileUtils.java
FileUtils.getRootStorageDirectory
public static File getRootStorageDirectory(Context c, String directory_name) { """ Returns a Java File initialized to a directory of given name at the root storage location, with preference to external storage. If the directory did not exist, it will be created at the conclusion of this call. If a file with conflicting name exists, this method returns null; @param c the context to determine the internal storage location, if external is unavailable @param directory_name the name of the directory desired at the storage location @return a File pointing to the storage directory, or null if a file with conflicting name exists """ File result; // First, try getting access to the sdcard partition if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ Log.d(TAG,"Using sdcard"); result = new File(Environment.getExternalStorageDirectory(), directory_name); } else { // Else, use the internal storage directory for this application Log.d(TAG,"Using internal storage"); result = new File(c.getApplicationContext().getFilesDir(), directory_name); } if(!result.exists()) result.mkdir(); else if(result.isFile()){ return null; } Log.d("getRootStorageDirectory", result.getAbsolutePath()); return result; }
java
public static File getRootStorageDirectory(Context c, String directory_name){ File result; // First, try getting access to the sdcard partition if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ Log.d(TAG,"Using sdcard"); result = new File(Environment.getExternalStorageDirectory(), directory_name); } else { // Else, use the internal storage directory for this application Log.d(TAG,"Using internal storage"); result = new File(c.getApplicationContext().getFilesDir(), directory_name); } if(!result.exists()) result.mkdir(); else if(result.isFile()){ return null; } Log.d("getRootStorageDirectory", result.getAbsolutePath()); return result; }
[ "public", "static", "File", "getRootStorageDirectory", "(", "Context", "c", ",", "String", "directory_name", ")", "{", "File", "result", ";", "// First, try getting access to the sdcard partition", "if", "(", "Environment", ".", "getExternalStorageState", "(", ")", ".", "equals", "(", "Environment", ".", "MEDIA_MOUNTED", ")", ")", "{", "Log", ".", "d", "(", "TAG", ",", "\"Using sdcard\"", ")", ";", "result", "=", "new", "File", "(", "Environment", ".", "getExternalStorageDirectory", "(", ")", ",", "directory_name", ")", ";", "}", "else", "{", "// Else, use the internal storage directory for this application", "Log", ".", "d", "(", "TAG", ",", "\"Using internal storage\"", ")", ";", "result", "=", "new", "File", "(", "c", ".", "getApplicationContext", "(", ")", ".", "getFilesDir", "(", ")", ",", "directory_name", ")", ";", "}", "if", "(", "!", "result", ".", "exists", "(", ")", ")", "result", ".", "mkdir", "(", ")", ";", "else", "if", "(", "result", ".", "isFile", "(", ")", ")", "{", "return", "null", ";", "}", "Log", ".", "d", "(", "\"getRootStorageDirectory\"", ",", "result", ".", "getAbsolutePath", "(", ")", ")", ";", "return", "result", ";", "}" ]
Returns a Java File initialized to a directory of given name at the root storage location, with preference to external storage. If the directory did not exist, it will be created at the conclusion of this call. If a file with conflicting name exists, this method returns null; @param c the context to determine the internal storage location, if external is unavailable @param directory_name the name of the directory desired at the storage location @return a File pointing to the storage directory, or null if a file with conflicting name exists
[ "Returns", "a", "Java", "File", "initialized", "to", "a", "directory", "of", "given", "name", "at", "the", "root", "storage", "location", "with", "preference", "to", "external", "storage", ".", "If", "the", "directory", "did", "not", "exist", "it", "will", "be", "created", "at", "the", "conclusion", "of", "this", "call", ".", "If", "a", "file", "with", "conflicting", "name", "exists", "this", "method", "returns", "null", ";" ]
train
https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/FileUtils.java#L54-L73
marvinlabs/android-floatinglabel-widgets
library/src/main/java/com/marvinlabs/widget/floatinglabel/itempicker/AbstractPickerDialogFragment.java
AbstractPickerDialogFragment.buildCommonArgsBundle
protected static Bundle buildCommonArgsBundle(int pickerId, String title, String positiveButtonText, String negativeButtonText, boolean enableMultipleSelection, int[] selectedItemIndices) { """ Utility method for implementations to create the base argument bundle @param pickerId The id of the item picker @param title The title for the dialog @param positiveButtonText The text of the positive button @param negativeButtonText The text of the negative button @param enableMultipleSelection Whether or not to allow selecting multiple items @param selectedItemIndices The positions of the items already selected @return The arguments bundle """ Bundle args = new Bundle(); args.putInt(ARG_PICKER_ID, pickerId); args.putString(ARG_TITLE, title); args.putString(ARG_POSITIVE_BUTTON_TEXT, positiveButtonText); args.putString(ARG_NEGATIVE_BUTTON_TEXT, negativeButtonText); args.putBoolean(ARG_ENABLE_MULTIPLE_SELECTION, enableMultipleSelection); args.putIntArray(ARG_SELECTED_ITEMS_INDICES, selectedItemIndices); return args; }
java
protected static Bundle buildCommonArgsBundle(int pickerId, String title, String positiveButtonText, String negativeButtonText, boolean enableMultipleSelection, int[] selectedItemIndices) { Bundle args = new Bundle(); args.putInt(ARG_PICKER_ID, pickerId); args.putString(ARG_TITLE, title); args.putString(ARG_POSITIVE_BUTTON_TEXT, positiveButtonText); args.putString(ARG_NEGATIVE_BUTTON_TEXT, negativeButtonText); args.putBoolean(ARG_ENABLE_MULTIPLE_SELECTION, enableMultipleSelection); args.putIntArray(ARG_SELECTED_ITEMS_INDICES, selectedItemIndices); return args; }
[ "protected", "static", "Bundle", "buildCommonArgsBundle", "(", "int", "pickerId", ",", "String", "title", ",", "String", "positiveButtonText", ",", "String", "negativeButtonText", ",", "boolean", "enableMultipleSelection", ",", "int", "[", "]", "selectedItemIndices", ")", "{", "Bundle", "args", "=", "new", "Bundle", "(", ")", ";", "args", ".", "putInt", "(", "ARG_PICKER_ID", ",", "pickerId", ")", ";", "args", ".", "putString", "(", "ARG_TITLE", ",", "title", ")", ";", "args", ".", "putString", "(", "ARG_POSITIVE_BUTTON_TEXT", ",", "positiveButtonText", ")", ";", "args", ".", "putString", "(", "ARG_NEGATIVE_BUTTON_TEXT", ",", "negativeButtonText", ")", ";", "args", ".", "putBoolean", "(", "ARG_ENABLE_MULTIPLE_SELECTION", ",", "enableMultipleSelection", ")", ";", "args", ".", "putIntArray", "(", "ARG_SELECTED_ITEMS_INDICES", ",", "selectedItemIndices", ")", ";", "return", "args", ";", "}" ]
Utility method for implementations to create the base argument bundle @param pickerId The id of the item picker @param title The title for the dialog @param positiveButtonText The text of the positive button @param negativeButtonText The text of the negative button @param enableMultipleSelection Whether or not to allow selecting multiple items @param selectedItemIndices The positions of the items already selected @return The arguments bundle
[ "Utility", "method", "for", "implementations", "to", "create", "the", "base", "argument", "bundle" ]
train
https://github.com/marvinlabs/android-floatinglabel-widgets/blob/bb89889f1e75ed9b228b77d3ba895ceeeb41fe4f/library/src/main/java/com/marvinlabs/widget/floatinglabel/itempicker/AbstractPickerDialogFragment.java#L56-L65
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.msgstore/src/com/ibm/ws/sib/msgstore/cache/links/ReferenceStreamLink.java
ReferenceStreamLink.addReference
public final void addReference(ItemReference reference, long lockID, Transaction transaction) throws OutOfCacheSpace, ProtocolException, StreamIsFull, TransactionException, PersistenceException, SevereMessageStoreException { """ @see com.ibm.ws.sib.msgstore.ItemCollection#addReference(com.ibm.ws.sib.msgstore.ItemReference, com.ibm.ws.sib.msgstore.transactions.Transaction) @throws OutOfCacheSpace if there is not enough space in the unstoredCache and the storage strategy is AbstractItem.STORE_NEVER. @throws StreamIsFull if the size of the stream would exceed the maximum permissable size if an add were performed. @throws SevereMessageStoreException @throws {@ProtocolException} Thrown if an add is attempted when the transaction cannot allow any further work to be added i.e. after completion of the transaction. @throws {@TransactionException} Thrown if an unexpected error occurs. """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "addReference", new Object[] { reference, transaction}); _references(); final MessageStoreImpl messageStore = getMessageStoreImpl(); int strategy = reference.getStorageStrategy(); final long itemID = messageStore.getUniqueValue(strategy); TupleTypeEnum type = TupleTypeEnum.ITEM_REFERENCE; reference.setSizeRefsByMsgSize(messageStore.getJdbcSpillSizeMsgRefsByMsgSize()); // PK57207 Persistable childPersistable = getTuple().createPersistable(itemID, type); final AbstractItemLink link = new ItemReferenceLink(reference, this, childPersistable); // Defect 463642 // Revert to using spill limits previously removed in SIB0112d.ms.2 link.setParentWasSpillingAtAddTime(getListStatistics().isSpilling()); messageStore.registerLink(link, reference); link.cmdAdd(this, lockID, (PersistentTransaction)transaction); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "addReference"); }
java
public final void addReference(ItemReference reference, long lockID, Transaction transaction) throws OutOfCacheSpace, ProtocolException, StreamIsFull, TransactionException, PersistenceException, SevereMessageStoreException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "addReference", new Object[] { reference, transaction}); _references(); final MessageStoreImpl messageStore = getMessageStoreImpl(); int strategy = reference.getStorageStrategy(); final long itemID = messageStore.getUniqueValue(strategy); TupleTypeEnum type = TupleTypeEnum.ITEM_REFERENCE; reference.setSizeRefsByMsgSize(messageStore.getJdbcSpillSizeMsgRefsByMsgSize()); // PK57207 Persistable childPersistable = getTuple().createPersistable(itemID, type); final AbstractItemLink link = new ItemReferenceLink(reference, this, childPersistable); // Defect 463642 // Revert to using spill limits previously removed in SIB0112d.ms.2 link.setParentWasSpillingAtAddTime(getListStatistics().isSpilling()); messageStore.registerLink(link, reference); link.cmdAdd(this, lockID, (PersistentTransaction)transaction); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "addReference"); }
[ "public", "final", "void", "addReference", "(", "ItemReference", "reference", ",", "long", "lockID", ",", "Transaction", "transaction", ")", "throws", "OutOfCacheSpace", ",", "ProtocolException", ",", "StreamIsFull", ",", "TransactionException", ",", "PersistenceException", ",", "SevereMessageStoreException", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "this", ",", "tc", ",", "\"addReference\"", ",", "new", "Object", "[", "]", "{", "reference", ",", "transaction", "}", ")", ";", "_references", "(", ")", ";", "final", "MessageStoreImpl", "messageStore", "=", "getMessageStoreImpl", "(", ")", ";", "int", "strategy", "=", "reference", ".", "getStorageStrategy", "(", ")", ";", "final", "long", "itemID", "=", "messageStore", ".", "getUniqueValue", "(", "strategy", ")", ";", "TupleTypeEnum", "type", "=", "TupleTypeEnum", ".", "ITEM_REFERENCE", ";", "reference", ".", "setSizeRefsByMsgSize", "(", "messageStore", ".", "getJdbcSpillSizeMsgRefsByMsgSize", "(", ")", ")", ";", "// PK57207", "Persistable", "childPersistable", "=", "getTuple", "(", ")", ".", "createPersistable", "(", "itemID", ",", "type", ")", ";", "final", "AbstractItemLink", "link", "=", "new", "ItemReferenceLink", "(", "reference", ",", "this", ",", "childPersistable", ")", ";", "// Defect 463642", "// Revert to using spill limits previously removed in SIB0112d.ms.2", "link", ".", "setParentWasSpillingAtAddTime", "(", "getListStatistics", "(", ")", ".", "isSpilling", "(", ")", ")", ";", "messageStore", ".", "registerLink", "(", "link", ",", "reference", ")", ";", "link", ".", "cmdAdd", "(", "this", ",", "lockID", ",", "(", "PersistentTransaction", ")", "transaction", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "this", ",", "tc", ",", "\"addReference\"", ")", ";", "}" ]
@see com.ibm.ws.sib.msgstore.ItemCollection#addReference(com.ibm.ws.sib.msgstore.ItemReference, com.ibm.ws.sib.msgstore.transactions.Transaction) @throws OutOfCacheSpace if there is not enough space in the unstoredCache and the storage strategy is AbstractItem.STORE_NEVER. @throws StreamIsFull if the size of the stream would exceed the maximum permissable size if an add were performed. @throws SevereMessageStoreException @throws {@ProtocolException} Thrown if an add is attempted when the transaction cannot allow any further work to be added i.e. after completion of the transaction. @throws {@TransactionException} Thrown if an unexpected error occurs.
[ "@see", "com", ".", "ibm", ".", "ws", ".", "sib", ".", "msgstore", ".", "ItemCollection#addReference", "(", "com", ".", "ibm", ".", "ws", ".", "sib", ".", "msgstore", ".", "ItemReference", "com", ".", "ibm", ".", "ws", ".", "sib", ".", "msgstore", ".", "transactions", ".", "Transaction", ")" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.msgstore/src/com/ibm/ws/sib/msgstore/cache/links/ReferenceStreamLink.java#L189-L208
prestodb/presto
presto-spi/src/main/java/com/facebook/presto/spi/block/RowBlock.java
RowBlock.fromFieldBlocks
public static Block fromFieldBlocks(int positionCount, Optional<boolean[]> rowIsNull, Block[] fieldBlocks) { """ Create a row block directly from columnar nulls and field blocks. """ int[] fieldBlockOffsets = new int[positionCount + 1]; for (int position = 0; position < positionCount; position++) { fieldBlockOffsets[position + 1] = fieldBlockOffsets[position] + (rowIsNull.isPresent() && rowIsNull.get()[position] ? 0 : 1); } validateConstructorArguments(0, positionCount, rowIsNull.orElse(null), fieldBlockOffsets, fieldBlocks); return new RowBlock(0, positionCount, rowIsNull.orElse(null), fieldBlockOffsets, fieldBlocks); }
java
public static Block fromFieldBlocks(int positionCount, Optional<boolean[]> rowIsNull, Block[] fieldBlocks) { int[] fieldBlockOffsets = new int[positionCount + 1]; for (int position = 0; position < positionCount; position++) { fieldBlockOffsets[position + 1] = fieldBlockOffsets[position] + (rowIsNull.isPresent() && rowIsNull.get()[position] ? 0 : 1); } validateConstructorArguments(0, positionCount, rowIsNull.orElse(null), fieldBlockOffsets, fieldBlocks); return new RowBlock(0, positionCount, rowIsNull.orElse(null), fieldBlockOffsets, fieldBlocks); }
[ "public", "static", "Block", "fromFieldBlocks", "(", "int", "positionCount", ",", "Optional", "<", "boolean", "[", "]", ">", "rowIsNull", ",", "Block", "[", "]", "fieldBlocks", ")", "{", "int", "[", "]", "fieldBlockOffsets", "=", "new", "int", "[", "positionCount", "+", "1", "]", ";", "for", "(", "int", "position", "=", "0", ";", "position", "<", "positionCount", ";", "position", "++", ")", "{", "fieldBlockOffsets", "[", "position", "+", "1", "]", "=", "fieldBlockOffsets", "[", "position", "]", "+", "(", "rowIsNull", ".", "isPresent", "(", ")", "&&", "rowIsNull", ".", "get", "(", ")", "[", "position", "]", "?", "0", ":", "1", ")", ";", "}", "validateConstructorArguments", "(", "0", ",", "positionCount", ",", "rowIsNull", ".", "orElse", "(", "null", ")", ",", "fieldBlockOffsets", ",", "fieldBlocks", ")", ";", "return", "new", "RowBlock", "(", "0", ",", "positionCount", ",", "rowIsNull", ".", "orElse", "(", "null", ")", ",", "fieldBlockOffsets", ",", "fieldBlocks", ")", ";", "}" ]
Create a row block directly from columnar nulls and field blocks.
[ "Create", "a", "row", "block", "directly", "from", "columnar", "nulls", "and", "field", "blocks", "." ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-spi/src/main/java/com/facebook/presto/spi/block/RowBlock.java#L45-L53
google/closure-compiler
src/com/google/javascript/refactoring/Matchers.java
Matchers.newClass
public static Matcher newClass(final String className) { """ Returns a Matcher that matches constructing objects of the provided class name. This will match the NEW node of the JS Compiler AST. @param className The name of the class to return matching NEW nodes. """ return new Matcher() { @Override public boolean matches(Node node, NodeMetadata metadata) { if (!node.isNew()) { return false; } JSType providedJsType = getJsType(metadata, className); if (providedJsType == null) { return false; } JSType jsType = node.getJSType(); if (jsType == null) { return false; } jsType = jsType.restrictByNotNullOrUndefined(); return areTypesEquivalentIgnoringGenerics(jsType, providedJsType); } }; }
java
public static Matcher newClass(final String className) { return new Matcher() { @Override public boolean matches(Node node, NodeMetadata metadata) { if (!node.isNew()) { return false; } JSType providedJsType = getJsType(metadata, className); if (providedJsType == null) { return false; } JSType jsType = node.getJSType(); if (jsType == null) { return false; } jsType = jsType.restrictByNotNullOrUndefined(); return areTypesEquivalentIgnoringGenerics(jsType, providedJsType); } }; }
[ "public", "static", "Matcher", "newClass", "(", "final", "String", "className", ")", "{", "return", "new", "Matcher", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "Node", "node", ",", "NodeMetadata", "metadata", ")", "{", "if", "(", "!", "node", ".", "isNew", "(", ")", ")", "{", "return", "false", ";", "}", "JSType", "providedJsType", "=", "getJsType", "(", "metadata", ",", "className", ")", ";", "if", "(", "providedJsType", "==", "null", ")", "{", "return", "false", ";", "}", "JSType", "jsType", "=", "node", ".", "getJSType", "(", ")", ";", "if", "(", "jsType", "==", "null", ")", "{", "return", "false", ";", "}", "jsType", "=", "jsType", ".", "restrictByNotNullOrUndefined", "(", ")", ";", "return", "areTypesEquivalentIgnoringGenerics", "(", "jsType", ",", "providedJsType", ")", ";", "}", "}", ";", "}" ]
Returns a Matcher that matches constructing objects of the provided class name. This will match the NEW node of the JS Compiler AST. @param className The name of the class to return matching NEW nodes.
[ "Returns", "a", "Matcher", "that", "matches", "constructing", "objects", "of", "the", "provided", "class", "name", ".", "This", "will", "match", "the", "NEW", "node", "of", "the", "JS", "Compiler", "AST", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/refactoring/Matchers.java#L142-L161
janus-project/guava.janusproject.io
guava/src/com/google/common/collect/MapMaker.java
MapMaker.expireAfterWrite
@Deprecated @Override MapMaker expireAfterWrite(long duration, TimeUnit unit) { """ Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value. <p>When {@code duration} is zero, elements can be successfully added to the map, but are evicted immediately. This has a very similar effect to invoking {@link #maximumSize maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without a code change. <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or write operations. Expired entries are currently cleaned up during write operations, or during occasional read operations in the absense of writes; though this behavior may change in the future. @param duration the length of time after an entry is created that it should be automatically removed @param unit the unit that {@code duration} is expressed in @throws IllegalArgumentException if {@code duration} is negative @throws IllegalStateException if the time to live or time to idle was already set @deprecated Caching functionality in {@code MapMaker} has been moved to {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterWrite} being replaced by {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. Note that {@code CacheBuilder} is simply an enhanced API for an implementation which was branched from {@code MapMaker}. """ checkExpiration(duration, unit); this.expireAfterWriteNanos = unit.toNanos(duration); if (duration == 0 && this.nullRemovalCause == null) { // SIZE trumps EXPIRED this.nullRemovalCause = RemovalCause.EXPIRED; } useCustomMap = true; return this; }
java
@Deprecated @Override MapMaker expireAfterWrite(long duration, TimeUnit unit) { checkExpiration(duration, unit); this.expireAfterWriteNanos = unit.toNanos(duration); if (duration == 0 && this.nullRemovalCause == null) { // SIZE trumps EXPIRED this.nullRemovalCause = RemovalCause.EXPIRED; } useCustomMap = true; return this; }
[ "@", "Deprecated", "@", "Override", "MapMaker", "expireAfterWrite", "(", "long", "duration", ",", "TimeUnit", "unit", ")", "{", "checkExpiration", "(", "duration", ",", "unit", ")", ";", "this", ".", "expireAfterWriteNanos", "=", "unit", ".", "toNanos", "(", "duration", ")", ";", "if", "(", "duration", "==", "0", "&&", "this", ".", "nullRemovalCause", "==", "null", ")", "{", "// SIZE trumps EXPIRED", "this", ".", "nullRemovalCause", "=", "RemovalCause", ".", "EXPIRED", ";", "}", "useCustomMap", "=", "true", ";", "return", "this", ";", "}" ]
Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value. <p>When {@code duration} is zero, elements can be successfully added to the map, but are evicted immediately. This has a very similar effect to invoking {@link #maximumSize maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without a code change. <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or write operations. Expired entries are currently cleaned up during write operations, or during occasional read operations in the absense of writes; though this behavior may change in the future. @param duration the length of time after an entry is created that it should be automatically removed @param unit the unit that {@code duration} is expressed in @throws IllegalArgumentException if {@code duration} is negative @throws IllegalStateException if the time to live or time to idle was already set @deprecated Caching functionality in {@code MapMaker} has been moved to {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterWrite} being replaced by {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. Note that {@code CacheBuilder} is simply an enhanced API for an implementation which was branched from {@code MapMaker}.
[ "Specifies", "that", "each", "entry", "should", "be", "automatically", "removed", "from", "the", "map", "once", "a", "fixed", "duration", "has", "elapsed", "after", "the", "entry", "s", "creation", "or", "the", "most", "recent", "replacement", "of", "its", "value", "." ]
train
https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava/src/com/google/common/collect/MapMaker.java#L377-L388
kiswanij/jk-util
src/main/java/com/jk/util/JKObjectUtil.java
JKObjectUtil.isFieldExists
public static boolean isFieldExists(Class<?> clas, String fieldName) { """ Checks if is field exists. @param clas the clas @param fieldName the field name @return true, if is field exists """ Field[] fields = clas.getDeclaredFields(); for (Field field : fields) { if (field.getName().equals(fieldName)) { return true; } } if (clas.getSuperclass() != null) { return isFieldExists(clas.getSuperclass(), fieldName); } return false; }
java
public static boolean isFieldExists(Class<?> clas, String fieldName) { Field[] fields = clas.getDeclaredFields(); for (Field field : fields) { if (field.getName().equals(fieldName)) { return true; } } if (clas.getSuperclass() != null) { return isFieldExists(clas.getSuperclass(), fieldName); } return false; }
[ "public", "static", "boolean", "isFieldExists", "(", "Class", "<", "?", ">", "clas", ",", "String", "fieldName", ")", "{", "Field", "[", "]", "fields", "=", "clas", ".", "getDeclaredFields", "(", ")", ";", "for", "(", "Field", "field", ":", "fields", ")", "{", "if", "(", "field", ".", "getName", "(", ")", ".", "equals", "(", "fieldName", ")", ")", "{", "return", "true", ";", "}", "}", "if", "(", "clas", ".", "getSuperclass", "(", ")", "!=", "null", ")", "{", "return", "isFieldExists", "(", "clas", ".", "getSuperclass", "(", ")", ",", "fieldName", ")", ";", "}", "return", "false", ";", "}" ]
Checks if is field exists. @param clas the clas @param fieldName the field name @return true, if is field exists
[ "Checks", "if", "is", "field", "exists", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKObjectUtil.java#L829-L840
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/Stream.java
Stream.findLast
@NotNull public Optional<T> findLast() { """ Returns the last element wrapped by {@code Optional} class. If stream is empty, returns {@code Optional.empty()}. <p>This is a short-circuiting terminal operation. @return an {@code Optional} with the last element or {@code Optional.empty()} if the stream is empty @since 1.1.8 """ return reduce(new BinaryOperator<T>() { @Override public T apply(T left, T right) { return right; } }); }
java
@NotNull public Optional<T> findLast() { return reduce(new BinaryOperator<T>() { @Override public T apply(T left, T right) { return right; } }); }
[ "@", "NotNull", "public", "Optional", "<", "T", ">", "findLast", "(", ")", "{", "return", "reduce", "(", "new", "BinaryOperator", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "T", "apply", "(", "T", "left", ",", "T", "right", ")", "{", "return", "right", ";", "}", "}", ")", ";", "}" ]
Returns the last element wrapped by {@code Optional} class. If stream is empty, returns {@code Optional.empty()}. <p>This is a short-circuiting terminal operation. @return an {@code Optional} with the last element or {@code Optional.empty()} if the stream is empty @since 1.1.8
[ "Returns", "the", "last", "element", "wrapped", "by", "{", "@code", "Optional", "}", "class", ".", "If", "stream", "is", "empty", "returns", "{", "@code", "Optional", ".", "empty", "()", "}", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Stream.java#L2044-L2052
real-logic/simple-binary-encoding
sbe-tool/src/main/java/uk/co/real_logic/sbe/ir/Token.java
Token.matchOnLength
public CharSequence matchOnLength(final Supplier<CharSequence> one, final Supplier<CharSequence> many) { """ Match which approach to take based on the length of the token. If length is zero then an empty {@link String} is returned. @param one to be used when length is one. @param many to be used when length is greater than one. @return the {@link CharSequence} representing the token depending on the length. """ final int arrayLength = arrayLength(); if (arrayLength == 1) { return one.get(); } else if (arrayLength > 1) { return many.get(); } return ""; }
java
public CharSequence matchOnLength(final Supplier<CharSequence> one, final Supplier<CharSequence> many) { final int arrayLength = arrayLength(); if (arrayLength == 1) { return one.get(); } else if (arrayLength > 1) { return many.get(); } return ""; }
[ "public", "CharSequence", "matchOnLength", "(", "final", "Supplier", "<", "CharSequence", ">", "one", ",", "final", "Supplier", "<", "CharSequence", ">", "many", ")", "{", "final", "int", "arrayLength", "=", "arrayLength", "(", ")", ";", "if", "(", "arrayLength", "==", "1", ")", "{", "return", "one", ".", "get", "(", ")", ";", "}", "else", "if", "(", "arrayLength", ">", "1", ")", "{", "return", "many", ".", "get", "(", ")", ";", "}", "return", "\"\"", ";", "}" ]
Match which approach to take based on the length of the token. If length is zero then an empty {@link String} is returned. @param one to be used when length is one. @param many to be used when length is greater than one. @return the {@link CharSequence} representing the token depending on the length.
[ "Match", "which", "approach", "to", "take", "based", "on", "the", "length", "of", "the", "token", ".", "If", "length", "is", "zero", "then", "an", "empty", "{", "@link", "String", "}", "is", "returned", "." ]
train
https://github.com/real-logic/simple-binary-encoding/blob/9a7be490c86d98f0e430e4189bc6c8c4fbef658b/sbe-tool/src/main/java/uk/co/real_logic/sbe/ir/Token.java#L264-L278
lessthanoptimal/ejml
main/ejml-zdense/src/org/ejml/dense/row/CommonOps_ZDRM.java
CommonOps_ZDRM.multAddTransB
public static void multAddTransB(double realAlpha , double imagAlpha , ZMatrixRMaj a , ZMatrixRMaj b , ZMatrixRMaj c ) { """ <p> Performs the following operation:<br> <br> c = c + &alpha; * a * b<sup>H</sup><br> c<sub>ij</sub> = c<sub>ij</sub> + &alpha; * &sum;<sub>k=1:n</sub> { a<sub>ik</sub> * b<sub>jk</sub>} </p> @param realAlpha Real component of scaling factor. @param imagAlpha Imaginary component of scaling factor. @param a The left matrix in the multiplication operation. Not modified. @param b The right matrix in the multiplication operation. Not modified. @param c Where the results of the operation are stored. Modified. """ // TODO add a matrix vectory multiply here MatrixMatrixMult_ZDRM.multAddTransB(realAlpha,imagAlpha,a,b,c); }
java
public static void multAddTransB(double realAlpha , double imagAlpha , ZMatrixRMaj a , ZMatrixRMaj b , ZMatrixRMaj c ) { // TODO add a matrix vectory multiply here MatrixMatrixMult_ZDRM.multAddTransB(realAlpha,imagAlpha,a,b,c); }
[ "public", "static", "void", "multAddTransB", "(", "double", "realAlpha", ",", "double", "imagAlpha", ",", "ZMatrixRMaj", "a", ",", "ZMatrixRMaj", "b", ",", "ZMatrixRMaj", "c", ")", "{", "// TODO add a matrix vectory multiply here", "MatrixMatrixMult_ZDRM", ".", "multAddTransB", "(", "realAlpha", ",", "imagAlpha", ",", "a", ",", "b", ",", "c", ")", ";", "}" ]
<p> Performs the following operation:<br> <br> c = c + &alpha; * a * b<sup>H</sup><br> c<sub>ij</sub> = c<sub>ij</sub> + &alpha; * &sum;<sub>k=1:n</sub> { a<sub>ik</sub> * b<sub>jk</sub>} </p> @param realAlpha Real component of scaling factor. @param imagAlpha Imaginary component of scaling factor. @param a The left matrix in the multiplication operation. Not modified. @param b The right matrix in the multiplication operation. Not modified. @param c Where the results of the operation are stored. Modified.
[ "<p", ">", "Performs", "the", "following", "operation", ":", "<br", ">", "<br", ">", "c", "=", "c", "+", "&alpha", ";", "*", "a", "*", "b<sup", ">", "H<", "/", "sup", ">", "<br", ">", "c<sub", ">", "ij<", "/", "sub", ">", "=", "c<sub", ">", "ij<", "/", "sub", ">", "+", "&alpha", ";", "*", "&sum", ";", "<sub", ">", "k", "=", "1", ":", "n<", "/", "sub", ">", "{", "a<sub", ">", "ik<", "/", "sub", ">", "*", "b<sub", ">", "jk<", "/", "sub", ">", "}", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-zdense/src/org/ejml/dense/row/CommonOps_ZDRM.java#L650-L654
litsec/eidas-opensaml
opensaml3/src/main/java/se/litsec/eidas/opensaml/metadata/MetadataServiceListSignatureValidator.java
MetadataServiceListSignatureValidator.validateSignature
public void validateSignature(MetadataServiceList mdsl, X509Certificate signersCertificate) throws SignatureException { """ Validates the signature of the supplied {@code MetadataServiceList} element using the supplied certificate. @param mdsl the {@code MetadataServiceList} @param signersCertificate the certificate of the signer @throws SignatureException for validation errors """ // The signature to validate. // final Signature signature = mdsl.getSignature(); if (signature == null) { log.warn("Metadata service list is not signed"); throw new SignatureException("Metadata service list has no signature"); } // Is the signature correct according to the SAML signature profile? // try { this.signatureProfileValidator.validate(signature); } catch (SignatureException e) { log.warn("Signature failed pre-validation: " + e.getMessage()); throw e; } // Validate the signature. // CriteriaSet criteria = new CriteriaSet(new X509CertificateCriterion(signersCertificate)); try { if (!this.signatureTrustEngine.validate(signature, criteria)) { String msg = "Signature validation failed"; log.warn(msg); throw new SignatureException(msg); } } catch (SecurityException e) { String msg = String.format("A problem was encountered evaluating the signature: %s", e.getMessage()); log.warn(msg); throw new SignatureException(msg, e); } log.debug("Signature on MetadataServiceList successfully verified"); }
java
public void validateSignature(MetadataServiceList mdsl, X509Certificate signersCertificate) throws SignatureException { // The signature to validate. // final Signature signature = mdsl.getSignature(); if (signature == null) { log.warn("Metadata service list is not signed"); throw new SignatureException("Metadata service list has no signature"); } // Is the signature correct according to the SAML signature profile? // try { this.signatureProfileValidator.validate(signature); } catch (SignatureException e) { log.warn("Signature failed pre-validation: " + e.getMessage()); throw e; } // Validate the signature. // CriteriaSet criteria = new CriteriaSet(new X509CertificateCriterion(signersCertificate)); try { if (!this.signatureTrustEngine.validate(signature, criteria)) { String msg = "Signature validation failed"; log.warn(msg); throw new SignatureException(msg); } } catch (SecurityException e) { String msg = String.format("A problem was encountered evaluating the signature: %s", e.getMessage()); log.warn(msg); throw new SignatureException(msg, e); } log.debug("Signature on MetadataServiceList successfully verified"); }
[ "public", "void", "validateSignature", "(", "MetadataServiceList", "mdsl", ",", "X509Certificate", "signersCertificate", ")", "throws", "SignatureException", "{", "// The signature to validate.", "//", "final", "Signature", "signature", "=", "mdsl", ".", "getSignature", "(", ")", ";", "if", "(", "signature", "==", "null", ")", "{", "log", ".", "warn", "(", "\"Metadata service list is not signed\"", ")", ";", "throw", "new", "SignatureException", "(", "\"Metadata service list has no signature\"", ")", ";", "}", "// Is the signature correct according to the SAML signature profile?", "//", "try", "{", "this", ".", "signatureProfileValidator", ".", "validate", "(", "signature", ")", ";", "}", "catch", "(", "SignatureException", "e", ")", "{", "log", ".", "warn", "(", "\"Signature failed pre-validation: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "throw", "e", ";", "}", "// Validate the signature.", "//", "CriteriaSet", "criteria", "=", "new", "CriteriaSet", "(", "new", "X509CertificateCriterion", "(", "signersCertificate", ")", ")", ";", "try", "{", "if", "(", "!", "this", ".", "signatureTrustEngine", ".", "validate", "(", "signature", ",", "criteria", ")", ")", "{", "String", "msg", "=", "\"Signature validation failed\"", ";", "log", ".", "warn", "(", "msg", ")", ";", "throw", "new", "SignatureException", "(", "msg", ")", ";", "}", "}", "catch", "(", "SecurityException", "e", ")", "{", "String", "msg", "=", "String", ".", "format", "(", "\"A problem was encountered evaluating the signature: %s\"", ",", "e", ".", "getMessage", "(", ")", ")", ";", "log", ".", "warn", "(", "msg", ")", ";", "throw", "new", "SignatureException", "(", "msg", ",", "e", ")", ";", "}", "log", ".", "debug", "(", "\"Signature on MetadataServiceList successfully verified\"", ")", ";", "}" ]
Validates the signature of the supplied {@code MetadataServiceList} element using the supplied certificate. @param mdsl the {@code MetadataServiceList} @param signersCertificate the certificate of the signer @throws SignatureException for validation errors
[ "Validates", "the", "signature", "of", "the", "supplied", "{", "@code", "MetadataServiceList", "}", "element", "using", "the", "supplied", "certificate", "." ]
train
https://github.com/litsec/eidas-opensaml/blob/522ba6dba433a9524cb8a02464cc3b087b47a2b7/opensaml3/src/main/java/se/litsec/eidas/opensaml/metadata/MetadataServiceListSignatureValidator.java#L78-L115
yanzhenjie/AndServer
sample/src/main/java/com/yanzhenjie/andserver/sample/util/JsonUtils.java
JsonUtils.parseJson
public static <T> T parseJson(String json, Type type) { """ Parse json to object. @param json json string. @param type the type of object. @param <T> type. @return object. """ return JSON.parseObject(json, type); }
java
public static <T> T parseJson(String json, Type type) { return JSON.parseObject(json, type); }
[ "public", "static", "<", "T", ">", "T", "parseJson", "(", "String", "json", ",", "Type", "type", ")", "{", "return", "JSON", ".", "parseObject", "(", "json", ",", "type", ")", ";", "}" ]
Parse json to object. @param json json string. @param type the type of object. @param <T> type. @return object.
[ "Parse", "json", "to", "object", "." ]
train
https://github.com/yanzhenjie/AndServer/blob/f95f316cdfa5755d6a3fec3c6a1b5df783b81517/sample/src/main/java/com/yanzhenjie/andserver/sample/util/JsonUtils.java#L79-L81
wso2/transport-http
components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/common/Util.java
Util.sendAndCloseNoEntityBodyResp
public static void sendAndCloseNoEntityBodyResp(ChannelHandlerContext ctx, HttpResponseStatus status, HttpVersion httpVersion, String serverName) { """ Send back no entity body response and close the connection. This function is mostly used when we send back error messages. @param ctx connection @param status response status @param httpVersion of the response @param serverName server name """ HttpResponse outboundResponse = new DefaultHttpResponse(httpVersion, status); outboundResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); outboundResponse.headers().set(HttpHeaderNames.CONNECTION.toString(), Constants.CONNECTION_CLOSE); outboundResponse.headers().set(HttpHeaderNames.SERVER.toString(), serverName); ChannelFuture outboundRespFuture = ctx.channel().writeAndFlush(outboundResponse); outboundRespFuture.addListener( (ChannelFutureListener) channelFuture -> LOG.warn("Failed to send {}", status.reasonPhrase())); ctx.channel().close(); }
java
public static void sendAndCloseNoEntityBodyResp(ChannelHandlerContext ctx, HttpResponseStatus status, HttpVersion httpVersion, String serverName) { HttpResponse outboundResponse = new DefaultHttpResponse(httpVersion, status); outboundResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); outboundResponse.headers().set(HttpHeaderNames.CONNECTION.toString(), Constants.CONNECTION_CLOSE); outboundResponse.headers().set(HttpHeaderNames.SERVER.toString(), serverName); ChannelFuture outboundRespFuture = ctx.channel().writeAndFlush(outboundResponse); outboundRespFuture.addListener( (ChannelFutureListener) channelFuture -> LOG.warn("Failed to send {}", status.reasonPhrase())); ctx.channel().close(); }
[ "public", "static", "void", "sendAndCloseNoEntityBodyResp", "(", "ChannelHandlerContext", "ctx", ",", "HttpResponseStatus", "status", ",", "HttpVersion", "httpVersion", ",", "String", "serverName", ")", "{", "HttpResponse", "outboundResponse", "=", "new", "DefaultHttpResponse", "(", "httpVersion", ",", "status", ")", ";", "outboundResponse", ".", "headers", "(", ")", ".", "set", "(", "HttpHeaderNames", ".", "CONTENT_LENGTH", ",", "0", ")", ";", "outboundResponse", ".", "headers", "(", ")", ".", "set", "(", "HttpHeaderNames", ".", "CONNECTION", ".", "toString", "(", ")", ",", "Constants", ".", "CONNECTION_CLOSE", ")", ";", "outboundResponse", ".", "headers", "(", ")", ".", "set", "(", "HttpHeaderNames", ".", "SERVER", ".", "toString", "(", ")", ",", "serverName", ")", ";", "ChannelFuture", "outboundRespFuture", "=", "ctx", ".", "channel", "(", ")", ".", "writeAndFlush", "(", "outboundResponse", ")", ";", "outboundRespFuture", ".", "addListener", "(", "(", "ChannelFutureListener", ")", "channelFuture", "->", "LOG", ".", "warn", "(", "\"Failed to send {}\"", ",", "status", ".", "reasonPhrase", "(", ")", ")", ")", ";", "ctx", ".", "channel", "(", ")", ".", "close", "(", ")", ";", "}" ]
Send back no entity body response and close the connection. This function is mostly used when we send back error messages. @param ctx connection @param status response status @param httpVersion of the response @param serverName server name
[ "Send", "back", "no", "entity", "body", "response", "and", "close", "the", "connection", ".", "This", "function", "is", "mostly", "used", "when", "we", "send", "back", "error", "messages", "." ]
train
https://github.com/wso2/transport-http/blob/c51aa715b473db6c1b82a7d7b22f6e65f74df4c9/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/common/Util.java#L612-L622
apache/incubator-atlas
addons/hive-bridge/src/main/java/org/apache/atlas/hive/bridge/HiveMetaStoreBridge.java
HiveMetaStoreBridge.getTableQualifiedName
public static String getTableQualifiedName(String clusterName, String dbName, String tableName) { """ Construct the qualified name used to uniquely identify a Table instance in Atlas. @param clusterName Name of the cluster to which the Hive component belongs @param dbName Name of the Hive database to which the Table belongs @param tableName Name of the Hive table @return Unique qualified name to identify the Table instance in Atlas. """ return getTableQualifiedName(clusterName, dbName, tableName, false); }
java
public static String getTableQualifiedName(String clusterName, String dbName, String tableName) { return getTableQualifiedName(clusterName, dbName, tableName, false); }
[ "public", "static", "String", "getTableQualifiedName", "(", "String", "clusterName", ",", "String", "dbName", ",", "String", "tableName", ")", "{", "return", "getTableQualifiedName", "(", "clusterName", ",", "dbName", ",", "tableName", ",", "false", ")", ";", "}" ]
Construct the qualified name used to uniquely identify a Table instance in Atlas. @param clusterName Name of the cluster to which the Hive component belongs @param dbName Name of the Hive database to which the Table belongs @param tableName Name of the Hive table @return Unique qualified name to identify the Table instance in Atlas.
[ "Construct", "the", "qualified", "name", "used", "to", "uniquely", "identify", "a", "Table", "instance", "in", "Atlas", "." ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/addons/hive-bridge/src/main/java/org/apache/atlas/hive/bridge/HiveMetaStoreBridge.java#L411-L413
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/postprocessor/AbstractPostProcessorChainFactory.java
AbstractPostProcessorChainFactory.getCustomProcessorWrapper
protected ChainedResourceBundlePostProcessor getCustomProcessorWrapper(ResourceBundlePostProcessor customProcessor, String key, boolean isVariantPostProcessor) { """ Returns the custom processor wrapper @param customProcessor the custom processor @param key the id of the custom processor @param isVariantPostProcessor the flag indicating if it's a variant postprocessor @return the custom processor wrapper """ return new CustomPostProcessorChainWrapper(key, customProcessor, isVariantPostProcessor); }
java
protected ChainedResourceBundlePostProcessor getCustomProcessorWrapper(ResourceBundlePostProcessor customProcessor, String key, boolean isVariantPostProcessor) { return new CustomPostProcessorChainWrapper(key, customProcessor, isVariantPostProcessor); }
[ "protected", "ChainedResourceBundlePostProcessor", "getCustomProcessorWrapper", "(", "ResourceBundlePostProcessor", "customProcessor", ",", "String", "key", ",", "boolean", "isVariantPostProcessor", ")", "{", "return", "new", "CustomPostProcessorChainWrapper", "(", "key", ",", "customProcessor", ",", "isVariantPostProcessor", ")", ";", "}" ]
Returns the custom processor wrapper @param customProcessor the custom processor @param key the id of the custom processor @param isVariantPostProcessor the flag indicating if it's a variant postprocessor @return the custom processor wrapper
[ "Returns", "the", "custom", "processor", "wrapper" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/postprocessor/AbstractPostProcessorChainFactory.java#L191-L194
fernandospr/javapns-jdk16
src/main/java/javapns/Push.java
Push.sendPayload
private static PushedNotifications sendPayload(Payload payload, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException { """ Push a preformatted payload to a list of devices. @param payload a simple or complex payload to push. @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) @param password the keystore's password. @param production true to use Apple's production servers, false to use the sandbox servers. @param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device} @return a list of pushed notifications, each with details on transmission results and error (if any) @throws KeystoreException thrown if an error occurs when loading the keystore @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers """ PushedNotifications notifications = new PushedNotifications(); if (payload == null) return notifications; PushNotificationManager pushManager = new PushNotificationManager(); try { AppleNotificationServer server = new AppleNotificationServerBasicImpl(keystore, password, production); pushManager.initializeConnection(server); List<Device> deviceList = Devices.asDevices(devices); notifications.setMaxRetained(deviceList.size()); for (Device device : deviceList) { try { BasicDevice.validateTokenFormat(device.getToken()); PushedNotification notification = pushManager.sendNotification(device, payload, false); notifications.add(notification); } catch (InvalidDeviceTokenFormatException e) { notifications.add(new PushedNotification(device, payload, e)); } } } finally { try { pushManager.stopConnection(); } catch (Exception e) { } } return notifications; }
java
private static PushedNotifications sendPayload(Payload payload, Object keystore, String password, boolean production, Object devices) throws CommunicationException, KeystoreException { PushedNotifications notifications = new PushedNotifications(); if (payload == null) return notifications; PushNotificationManager pushManager = new PushNotificationManager(); try { AppleNotificationServer server = new AppleNotificationServerBasicImpl(keystore, password, production); pushManager.initializeConnection(server); List<Device> deviceList = Devices.asDevices(devices); notifications.setMaxRetained(deviceList.size()); for (Device device : deviceList) { try { BasicDevice.validateTokenFormat(device.getToken()); PushedNotification notification = pushManager.sendNotification(device, payload, false); notifications.add(notification); } catch (InvalidDeviceTokenFormatException e) { notifications.add(new PushedNotification(device, payload, e)); } } } finally { try { pushManager.stopConnection(); } catch (Exception e) { } } return notifications; }
[ "private", "static", "PushedNotifications", "sendPayload", "(", "Payload", "payload", ",", "Object", "keystore", ",", "String", "password", ",", "boolean", "production", ",", "Object", "devices", ")", "throws", "CommunicationException", ",", "KeystoreException", "{", "PushedNotifications", "notifications", "=", "new", "PushedNotifications", "(", ")", ";", "if", "(", "payload", "==", "null", ")", "return", "notifications", ";", "PushNotificationManager", "pushManager", "=", "new", "PushNotificationManager", "(", ")", ";", "try", "{", "AppleNotificationServer", "server", "=", "new", "AppleNotificationServerBasicImpl", "(", "keystore", ",", "password", ",", "production", ")", ";", "pushManager", ".", "initializeConnection", "(", "server", ")", ";", "List", "<", "Device", ">", "deviceList", "=", "Devices", ".", "asDevices", "(", "devices", ")", ";", "notifications", ".", "setMaxRetained", "(", "deviceList", ".", "size", "(", ")", ")", ";", "for", "(", "Device", "device", ":", "deviceList", ")", "{", "try", "{", "BasicDevice", ".", "validateTokenFormat", "(", "device", ".", "getToken", "(", ")", ")", ";", "PushedNotification", "notification", "=", "pushManager", ".", "sendNotification", "(", "device", ",", "payload", ",", "false", ")", ";", "notifications", ".", "add", "(", "notification", ")", ";", "}", "catch", "(", "InvalidDeviceTokenFormatException", "e", ")", "{", "notifications", ".", "add", "(", "new", "PushedNotification", "(", "device", ",", "payload", ",", "e", ")", ")", ";", "}", "}", "}", "finally", "{", "try", "{", "pushManager", ".", "stopConnection", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "return", "notifications", ";", "}" ]
Push a preformatted payload to a list of devices. @param payload a simple or complex payload to push. @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) @param password the keystore's password. @param production true to use Apple's production servers, false to use the sandbox servers. @param devices a list or an array of tokens or devices: {@link java.lang.String String[]}, {@link java.util.List}<{@link java.lang.String}>, {@link javapns.devices.Device Device[]}, {@link java.util.List}<{@link javapns.devices.Device}>, {@link java.lang.String} or {@link javapns.devices.Device} @return a list of pushed notifications, each with details on transmission results and error (if any) @throws KeystoreException thrown if an error occurs when loading the keystore @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers
[ "Push", "a", "preformatted", "payload", "to", "a", "list", "of", "devices", "." ]
train
https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/Push.java#L165-L190
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java
GenericGenerators.ifIntegersEqual
public static InsnList ifIntegersEqual(InsnList lhs, InsnList rhs, InsnList action) { """ Compares two integers and performs some action if the integers are equal. @param lhs left hand side instruction list -- must leave an int on the stack @param rhs right hand side instruction list -- must leave an int on the stack @param action action to perform if results of {@code lhs} and {@code rhs} are equal @return instructions instruction list to perform some action if two ints are equal @throws NullPointerException if any argument is {@code null} """ Validate.notNull(lhs); Validate.notNull(rhs); Validate.notNull(action); InsnList ret = new InsnList(); LabelNode notEqualLabelNode = new LabelNode(); ret.add(lhs); ret.add(rhs); ret.add(new JumpInsnNode(Opcodes.IF_ICMPNE, notEqualLabelNode)); ret.add(action); ret.add(notEqualLabelNode); return ret; }
java
public static InsnList ifIntegersEqual(InsnList lhs, InsnList rhs, InsnList action) { Validate.notNull(lhs); Validate.notNull(rhs); Validate.notNull(action); InsnList ret = new InsnList(); LabelNode notEqualLabelNode = new LabelNode(); ret.add(lhs); ret.add(rhs); ret.add(new JumpInsnNode(Opcodes.IF_ICMPNE, notEqualLabelNode)); ret.add(action); ret.add(notEqualLabelNode); return ret; }
[ "public", "static", "InsnList", "ifIntegersEqual", "(", "InsnList", "lhs", ",", "InsnList", "rhs", ",", "InsnList", "action", ")", "{", "Validate", ".", "notNull", "(", "lhs", ")", ";", "Validate", ".", "notNull", "(", "rhs", ")", ";", "Validate", ".", "notNull", "(", "action", ")", ";", "InsnList", "ret", "=", "new", "InsnList", "(", ")", ";", "LabelNode", "notEqualLabelNode", "=", "new", "LabelNode", "(", ")", ";", "ret", ".", "add", "(", "lhs", ")", ";", "ret", ".", "add", "(", "rhs", ")", ";", "ret", ".", "add", "(", "new", "JumpInsnNode", "(", "Opcodes", ".", "IF_ICMPNE", ",", "notEqualLabelNode", ")", ")", ";", "ret", ".", "add", "(", "action", ")", ";", "ret", ".", "add", "(", "notEqualLabelNode", ")", ";", "return", "ret", ";", "}" ]
Compares two integers and performs some action if the integers are equal. @param lhs left hand side instruction list -- must leave an int on the stack @param rhs right hand side instruction list -- must leave an int on the stack @param action action to perform if results of {@code lhs} and {@code rhs} are equal @return instructions instruction list to perform some action if two ints are equal @throws NullPointerException if any argument is {@code null}
[ "Compares", "two", "integers", "and", "performs", "some", "action", "if", "the", "integers", "are", "equal", "." ]
train
https://github.com/offbynull/coroutines/blob/b1b83c293945f53a2f63fca8f15a53e88b796bf5/instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java#L621-L638
pippo-java/pippo
pippo-core/src/main/java/ro/pippo/core/PippoSettings.java
PippoSettings.getDurationInHours
public long getDurationInHours(String name, long defaultValue) { """ Gets the duration setting and converts it to hours. <p/> The setting must be use one of the following conventions: <ul> <li>n MILLISECONDS <li>n SECONDS <li>n MINUTES <li>n HOURS <li>n DAYS </ul> @param name @param defaultValue in hours @return hours """ TimeUnit timeUnit = extractTimeUnit(name, defaultValue + " HOURS"); long duration = getLong(name, defaultValue); return timeUnit.toHours(duration); }
java
public long getDurationInHours(String name, long defaultValue) { TimeUnit timeUnit = extractTimeUnit(name, defaultValue + " HOURS"); long duration = getLong(name, defaultValue); return timeUnit.toHours(duration); }
[ "public", "long", "getDurationInHours", "(", "String", "name", ",", "long", "defaultValue", ")", "{", "TimeUnit", "timeUnit", "=", "extractTimeUnit", "(", "name", ",", "defaultValue", "+", "\" HOURS\"", ")", ";", "long", "duration", "=", "getLong", "(", "name", ",", "defaultValue", ")", ";", "return", "timeUnit", ".", "toHours", "(", "duration", ")", ";", "}" ]
Gets the duration setting and converts it to hours. <p/> The setting must be use one of the following conventions: <ul> <li>n MILLISECONDS <li>n SECONDS <li>n MINUTES <li>n HOURS <li>n DAYS </ul> @param name @param defaultValue in hours @return hours
[ "Gets", "the", "duration", "setting", "and", "converts", "it", "to", "hours", ".", "<p", "/", ">", "The", "setting", "must", "be", "use", "one", "of", "the", "following", "conventions", ":", "<ul", ">", "<li", ">", "n", "MILLISECONDS", "<li", ">", "n", "SECONDS", "<li", ">", "n", "MINUTES", "<li", ">", "n", "HOURS", "<li", ">", "n", "DAYS", "<", "/", "ul", ">" ]
train
https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/PippoSettings.java#L929-L934
intel/jndn-utils
src/main/java/com/intel/jndn/utils/impl/SegmentationHelper.java
SegmentationHelper.parseSegment
public static long parseSegment(Name name, byte marker) throws EncodingException { """ Retrieve the segment number from the last component of a name. @param name the name of a packet @param marker the marker type (the initial byte of the component) @return the segment number @throws EncodingException if the name does not have a final component of the correct marker type """ if (name.size() == 0) { throw new EncodingException("No components to parse."); } return name.get(-1).toNumberWithMarker(marker); }
java
public static long parseSegment(Name name, byte marker) throws EncodingException { if (name.size() == 0) { throw new EncodingException("No components to parse."); } return name.get(-1).toNumberWithMarker(marker); }
[ "public", "static", "long", "parseSegment", "(", "Name", "name", ",", "byte", "marker", ")", "throws", "EncodingException", "{", "if", "(", "name", ".", "size", "(", ")", "==", "0", ")", "{", "throw", "new", "EncodingException", "(", "\"No components to parse.\"", ")", ";", "}", "return", "name", ".", "get", "(", "-", "1", ")", ".", "toNumberWithMarker", "(", "marker", ")", ";", "}" ]
Retrieve the segment number from the last component of a name. @param name the name of a packet @param marker the marker type (the initial byte of the component) @return the segment number @throws EncodingException if the name does not have a final component of the correct marker type
[ "Retrieve", "the", "segment", "number", "from", "the", "last", "component", "of", "a", "name", "." ]
train
https://github.com/intel/jndn-utils/blob/7f670b259484c35d51a6c5acce5715b0573faedd/src/main/java/com/intel/jndn/utils/impl/SegmentationHelper.java#L68-L73
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java
HashMap.putMapEntries
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) { """ Implements Map.putAll and Map constructor @param m the map @param evict false when initially constructing this map, else true (relayed to method afterNodeInsertion). """ int s = m.size(); if (s > 0) { if (table == null) { // pre-size float ft = ((float)s / loadFactor) + 1.0F; int t = ((ft < (float)MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY); if (t > threshold) threshold = tableSizeFor(t); } else if (s > threshold) resize(); for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) { K key = e.getKey(); V value = e.getValue(); putVal(hash(key), key, value, false, evict); } } }
java
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) { int s = m.size(); if (s > 0) { if (table == null) { // pre-size float ft = ((float)s / loadFactor) + 1.0F; int t = ((ft < (float)MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY); if (t > threshold) threshold = tableSizeFor(t); } else if (s > threshold) resize(); for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) { K key = e.getKey(); V value = e.getValue(); putVal(hash(key), key, value, false, evict); } } }
[ "final", "void", "putMapEntries", "(", "Map", "<", "?", "extends", "K", ",", "?", "extends", "V", ">", "m", ",", "boolean", "evict", ")", "{", "int", "s", "=", "m", ".", "size", "(", ")", ";", "if", "(", "s", ">", "0", ")", "{", "if", "(", "table", "==", "null", ")", "{", "// pre-size", "float", "ft", "=", "(", "(", "float", ")", "s", "/", "loadFactor", ")", "+", "1.0F", ";", "int", "t", "=", "(", "(", "ft", "<", "(", "float", ")", "MAXIMUM_CAPACITY", ")", "?", "(", "int", ")", "ft", ":", "MAXIMUM_CAPACITY", ")", ";", "if", "(", "t", ">", "threshold", ")", "threshold", "=", "tableSizeFor", "(", "t", ")", ";", "}", "else", "if", "(", "s", ">", "threshold", ")", "resize", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "?", "extends", "K", ",", "?", "extends", "V", ">", "e", ":", "m", ".", "entrySet", "(", ")", ")", "{", "K", "key", "=", "e", ".", "getKey", "(", ")", ";", "V", "value", "=", "e", ".", "getValue", "(", ")", ";", "putVal", "(", "hash", "(", "key", ")", ",", "key", ",", "value", ",", "false", ",", "evict", ")", ";", "}", "}", "}" ]
Implements Map.putAll and Map constructor @param m the map @param evict false when initially constructing this map, else true (relayed to method afterNodeInsertion).
[ "Implements", "Map", ".", "putAll", "and", "Map", "constructor" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java#L505-L523
alkacon/opencms-core
src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java
CmsDefaultXmlContentHandler.addNestedFormatter
protected void addNestedFormatter(String elementName, CmsXmlContentDefinition contentDefinition) throws CmsXmlException { """ Adds a nested formatter element.<p> @param elementName the element name @param contentDefinition the content definition @throws CmsXmlException in case something goes wrong """ if (contentDefinition.getSchemaType(elementName) == null) { throw new CmsXmlException( Messages.get().container(Messages.ERR_XMLCONTENT_INVALID_ELEM_MAPPING_1, elementName)); } m_nestedFormatterElements.add(elementName); }
java
protected void addNestedFormatter(String elementName, CmsXmlContentDefinition contentDefinition) throws CmsXmlException { if (contentDefinition.getSchemaType(elementName) == null) { throw new CmsXmlException( Messages.get().container(Messages.ERR_XMLCONTENT_INVALID_ELEM_MAPPING_1, elementName)); } m_nestedFormatterElements.add(elementName); }
[ "protected", "void", "addNestedFormatter", "(", "String", "elementName", ",", "CmsXmlContentDefinition", "contentDefinition", ")", "throws", "CmsXmlException", "{", "if", "(", "contentDefinition", ".", "getSchemaType", "(", "elementName", ")", "==", "null", ")", "{", "throw", "new", "CmsXmlException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_XMLCONTENT_INVALID_ELEM_MAPPING_1", ",", "elementName", ")", ")", ";", "}", "m_nestedFormatterElements", ".", "add", "(", "elementName", ")", ";", "}" ]
Adds a nested formatter element.<p> @param elementName the element name @param contentDefinition the content definition @throws CmsXmlException in case something goes wrong
[ "Adds", "a", "nested", "formatter", "element", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java#L2042-L2050
UrielCh/ovh-java-sdk
ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java
ApiOvhSms.serviceName_senders_sender_GET
public OvhSender serviceName_senders_sender_GET(String serviceName, String sender) throws IOException { """ Get this object properties REST: GET /sms/{serviceName}/senders/{sender} @param serviceName [required] The internal name of your SMS offer @param sender [required] The sms sender """ String qPath = "/sms/{serviceName}/senders/{sender}"; StringBuilder sb = path(qPath, serviceName, sender); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhSender.class); }
java
public OvhSender serviceName_senders_sender_GET(String serviceName, String sender) throws IOException { String qPath = "/sms/{serviceName}/senders/{sender}"; StringBuilder sb = path(qPath, serviceName, sender); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhSender.class); }
[ "public", "OvhSender", "serviceName_senders_sender_GET", "(", "String", "serviceName", ",", "String", "sender", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/sms/{serviceName}/senders/{sender}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "sender", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhSender", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /sms/{serviceName}/senders/{sender} @param serviceName [required] The internal name of your SMS offer @param sender [required] The sms sender
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java#L182-L187
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/networking/nio/SelectorOptimizer.java
SelectorOptimizer.newSelector
static Selector newSelector(ILogger logger) { """ Creates a new Selector and will optimize it if possible. @param logger the logger used for the optimization process. @return the created Selector. @throws NullPointerException if logger is null. """ checkNotNull(logger, "logger"); Selector selector; try { selector = Selector.open(); } catch (IOException e) { throw new HazelcastException("Failed to open a Selector", e); } boolean optimize = Boolean.parseBoolean(System.getProperty("hazelcast.io.optimizeselector", "true")); if (optimize) { optimize(selector, logger); } return selector; }
java
static Selector newSelector(ILogger logger) { checkNotNull(logger, "logger"); Selector selector; try { selector = Selector.open(); } catch (IOException e) { throw new HazelcastException("Failed to open a Selector", e); } boolean optimize = Boolean.parseBoolean(System.getProperty("hazelcast.io.optimizeselector", "true")); if (optimize) { optimize(selector, logger); } return selector; }
[ "static", "Selector", "newSelector", "(", "ILogger", "logger", ")", "{", "checkNotNull", "(", "logger", ",", "\"logger\"", ")", ";", "Selector", "selector", ";", "try", "{", "selector", "=", "Selector", ".", "open", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "HazelcastException", "(", "\"Failed to open a Selector\"", ",", "e", ")", ";", "}", "boolean", "optimize", "=", "Boolean", ".", "parseBoolean", "(", "System", ".", "getProperty", "(", "\"hazelcast.io.optimizeselector\"", ",", "\"true\"", ")", ")", ";", "if", "(", "optimize", ")", "{", "optimize", "(", "selector", ",", "logger", ")", ";", "}", "return", "selector", ";", "}" ]
Creates a new Selector and will optimize it if possible. @param logger the logger used for the optimization process. @return the created Selector. @throws NullPointerException if logger is null.
[ "Creates", "a", "new", "Selector", "and", "will", "optimize", "it", "if", "possible", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/networking/nio/SelectorOptimizer.java#L55-L70
ops4j/org.ops4j.base
ops4j-base-util-collections/src/main/java/org/ops4j/util/collections/PropertiesUtils.java
PropertiesUtils.readProps
public static Properties readProps( URL propsUrl, Properties mappings ) throws IOException { """ Read a set of properties from a property file specificed by a url. @param propsUrl the url of the property file to read @param mappings Properties that will be available for translations initially. @return the resolved properties @throws IOException if an io error occurs @see #readProperties(java.io.InputStream,java.util.Properties,boolean) """ InputStream stream = propsUrl.openStream(); return readProperties( stream, mappings, true ); }
java
public static Properties readProps( URL propsUrl, Properties mappings ) throws IOException { InputStream stream = propsUrl.openStream(); return readProperties( stream, mappings, true ); }
[ "public", "static", "Properties", "readProps", "(", "URL", "propsUrl", ",", "Properties", "mappings", ")", "throws", "IOException", "{", "InputStream", "stream", "=", "propsUrl", ".", "openStream", "(", ")", ";", "return", "readProperties", "(", "stream", ",", "mappings", ",", "true", ")", ";", "}" ]
Read a set of properties from a property file specificed by a url. @param propsUrl the url of the property file to read @param mappings Properties that will be available for translations initially. @return the resolved properties @throws IOException if an io error occurs @see #readProperties(java.io.InputStream,java.util.Properties,boolean)
[ "Read", "a", "set", "of", "properties", "from", "a", "property", "file", "specificed", "by", "a", "url", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-util-collections/src/main/java/org/ops4j/util/collections/PropertiesUtils.java#L54-L59
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/circle/EllipseClustersIntoRegularGrid.java
EllipseClustersIntoRegularGrid.createRegularGrid
static void createRegularGrid( List<List<NodeInfo>> gridByRows , Grid g) { """ Combines the inner and outer grid into one grid for output. See {@link Grid} for a discussion on how elements are ordered internally. """ g.reset(); g.columns = gridByRows.get(0).size(); g.rows = gridByRows.size(); for (int row = 0; row < g.rows; row++) { List<NodeInfo> list = gridByRows.get(row); for (int i = 0; i < g.columns; i++) { g.ellipses.add(list.get(i).ellipse ); } } }
java
static void createRegularGrid( List<List<NodeInfo>> gridByRows , Grid g) { g.reset(); g.columns = gridByRows.get(0).size(); g.rows = gridByRows.size(); for (int row = 0; row < g.rows; row++) { List<NodeInfo> list = gridByRows.get(row); for (int i = 0; i < g.columns; i++) { g.ellipses.add(list.get(i).ellipse ); } } }
[ "static", "void", "createRegularGrid", "(", "List", "<", "List", "<", "NodeInfo", ">", ">", "gridByRows", ",", "Grid", "g", ")", "{", "g", ".", "reset", "(", ")", ";", "g", ".", "columns", "=", "gridByRows", ".", "get", "(", "0", ")", ".", "size", "(", ")", ";", "g", ".", "rows", "=", "gridByRows", ".", "size", "(", ")", ";", "for", "(", "int", "row", "=", "0", ";", "row", "<", "g", ".", "rows", ";", "row", "++", ")", "{", "List", "<", "NodeInfo", ">", "list", "=", "gridByRows", ".", "get", "(", "row", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "g", ".", "columns", ";", "i", "++", ")", "{", "g", ".", "ellipses", ".", "add", "(", "list", ".", "get", "(", "i", ")", ".", "ellipse", ")", ";", "}", "}", "}" ]
Combines the inner and outer grid into one grid for output. See {@link Grid} for a discussion on how elements are ordered internally.
[ "Combines", "the", "inner", "and", "outer", "grid", "into", "one", "grid", "for", "output", ".", "See", "{" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/circle/EllipseClustersIntoRegularGrid.java#L136-L148
DDTH/ddth-zookeeper
src/main/java/com/github/ddth/zookeeper/ZooKeeperClient.java
ZooKeeperClient.setData
public boolean setData(String path, String value, boolean createNodes) throws ZooKeeperException { """ Writes data to a node. @param path @param value @param createNodes {@code true} to have nodes to be created if not exist @return {@code true} if write successfully, {@code false} otherwise (note does not exist, for example) @throws ZooKeeperException """ return _write(path, value != null ? value.getBytes(UTF8) : null, createNodes); }
java
public boolean setData(String path, String value, boolean createNodes) throws ZooKeeperException { return _write(path, value != null ? value.getBytes(UTF8) : null, createNodes); }
[ "public", "boolean", "setData", "(", "String", "path", ",", "String", "value", ",", "boolean", "createNodes", ")", "throws", "ZooKeeperException", "{", "return", "_write", "(", "path", ",", "value", "!=", "null", "?", "value", ".", "getBytes", "(", "UTF8", ")", ":", "null", ",", "createNodes", ")", ";", "}" ]
Writes data to a node. @param path @param value @param createNodes {@code true} to have nodes to be created if not exist @return {@code true} if write successfully, {@code false} otherwise (note does not exist, for example) @throws ZooKeeperException
[ "Writes", "data", "to", "a", "node", "." ]
train
https://github.com/DDTH/ddth-zookeeper/blob/0994eea8b25fa3d885f3da4579768b7d08c1c32b/src/main/java/com/github/ddth/zookeeper/ZooKeeperClient.java#L685-L688
carewebframework/carewebframework-core
org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/util/ThemeUtil.java
ThemeUtil.applyThemeClass
public static void applyThemeClass(BaseUIComponent component, IThemeClass... themeClasses) { """ Applies one or more theme classes to a component. @param component Component to receive the theme classes. @param themeClasses A list of theme classes to apply. """ StringBuilder sb = new StringBuilder(); for (IThemeClass themeClass : themeClasses) { String cls = themeClass == null ? null : themeClass.getThemeClass(); if (cls != null) { sb.append(sb.length() > 0 ? " " : "").append(themeClass.getThemeClass()); } } component.addClass(sb.toString()); }
java
public static void applyThemeClass(BaseUIComponent component, IThemeClass... themeClasses) { StringBuilder sb = new StringBuilder(); for (IThemeClass themeClass : themeClasses) { String cls = themeClass == null ? null : themeClass.getThemeClass(); if (cls != null) { sb.append(sb.length() > 0 ? " " : "").append(themeClass.getThemeClass()); } } component.addClass(sb.toString()); }
[ "public", "static", "void", "applyThemeClass", "(", "BaseUIComponent", "component", ",", "IThemeClass", "...", "themeClasses", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "IThemeClass", "themeClass", ":", "themeClasses", ")", "{", "String", "cls", "=", "themeClass", "==", "null", "?", "null", ":", "themeClass", ".", "getThemeClass", "(", ")", ";", "if", "(", "cls", "!=", "null", ")", "{", "sb", ".", "append", "(", "sb", ".", "length", "(", ")", ">", "0", "?", "\" \"", ":", "\"\"", ")", ".", "append", "(", "themeClass", ".", "getThemeClass", "(", ")", ")", ";", "}", "}", "component", ".", "addClass", "(", "sb", ".", "toString", "(", ")", ")", ";", "}" ]
Applies one or more theme classes to a component. @param component Component to receive the theme classes. @param themeClasses A list of theme classes to apply.
[ "Applies", "one", "or", "more", "theme", "classes", "to", "a", "component", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/util/ThemeUtil.java#L46-L58
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/factory/fiducial/FactoryFiducialCalibration.java
FactoryFiducialCalibration.circleRegularGrid
public static CalibrationDetectorCircleRegularGrid circleRegularGrid( @Nullable ConfigCircleRegularGrid config , ConfigGridDimen configGrid ) { """ Detector for regular grid of circles. All circles must be entirely inside of the image. @param config Configuration for target @return The detector """ if( config == null ) config = new ConfigCircleRegularGrid(); config.checkValidity(); return new CalibrationDetectorCircleRegularGrid(config,configGrid); }
java
public static CalibrationDetectorCircleRegularGrid circleRegularGrid( @Nullable ConfigCircleRegularGrid config , ConfigGridDimen configGrid ) { if( config == null ) config = new ConfigCircleRegularGrid(); config.checkValidity(); return new CalibrationDetectorCircleRegularGrid(config,configGrid); }
[ "public", "static", "CalibrationDetectorCircleRegularGrid", "circleRegularGrid", "(", "@", "Nullable", "ConfigCircleRegularGrid", "config", ",", "ConfigGridDimen", "configGrid", ")", "{", "if", "(", "config", "==", "null", ")", "config", "=", "new", "ConfigCircleRegularGrid", "(", ")", ";", "config", ".", "checkValidity", "(", ")", ";", "return", "new", "CalibrationDetectorCircleRegularGrid", "(", "config", ",", "configGrid", ")", ";", "}" ]
Detector for regular grid of circles. All circles must be entirely inside of the image. @param config Configuration for target @return The detector
[ "Detector", "for", "regular", "grid", "of", "circles", ".", "All", "circles", "must", "be", "entirely", "inside", "of", "the", "image", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/factory/fiducial/FactoryFiducialCalibration.java#L122-L129
apache/flink
flink-core/src/main/java/org/apache/flink/util/AbstractCloseableRegistry.java
AbstractCloseableRegistry.registerCloseable
public final void registerCloseable(C closeable) throws IOException { """ Registers a {@link Closeable} with the registry. In case the registry is already closed, this method throws an {@link IllegalStateException} and closes the passed {@link Closeable}. @param closeable Closeable tor register @throws IOException exception when the registry was closed before """ if (null == closeable) { return; } synchronized (getSynchronizationLock()) { if (!closed) { doRegister(closeable, closeableToRef); return; } } IOUtils.closeQuietly(closeable); throw new IOException("Cannot register Closeable, registry is already closed. Closing argument."); }
java
public final void registerCloseable(C closeable) throws IOException { if (null == closeable) { return; } synchronized (getSynchronizationLock()) { if (!closed) { doRegister(closeable, closeableToRef); return; } } IOUtils.closeQuietly(closeable); throw new IOException("Cannot register Closeable, registry is already closed. Closing argument."); }
[ "public", "final", "void", "registerCloseable", "(", "C", "closeable", ")", "throws", "IOException", "{", "if", "(", "null", "==", "closeable", ")", "{", "return", ";", "}", "synchronized", "(", "getSynchronizationLock", "(", ")", ")", "{", "if", "(", "!", "closed", ")", "{", "doRegister", "(", "closeable", ",", "closeableToRef", ")", ";", "return", ";", "}", "}", "IOUtils", ".", "closeQuietly", "(", "closeable", ")", ";", "throw", "new", "IOException", "(", "\"Cannot register Closeable, registry is already closed. Closing argument.\"", ")", ";", "}" ]
Registers a {@link Closeable} with the registry. In case the registry is already closed, this method throws an {@link IllegalStateException} and closes the passed {@link Closeable}. @param closeable Closeable tor register @throws IOException exception when the registry was closed before
[ "Registers", "a", "{", "@link", "Closeable", "}", "with", "the", "registry", ".", "In", "case", "the", "registry", "is", "already", "closed", "this", "method", "throws", "an", "{", "@link", "IllegalStateException", "}", "and", "closes", "the", "passed", "{", "@link", "Closeable", "}", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/AbstractCloseableRegistry.java#L71-L86
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/BindM2MBuilder.java
BindM2MBuilder.generateDaoPart
private void generateDaoPart(M2MEntity entity) { """ Generate dao part. @param entity the entity @throws IOException Signals that an I/O exception has occurred. """ String daoClassName = entity.daoName.simpleName(); String daoPackageName = entity.daoName.packageName(); String entityPackageName = entity.getPackageName(); String generatedDaoClassName = "Generated" + daoClassName; AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDaoMany2Many.class, daoPackageName, generatedDaoClassName); // @formatter:off classBuilder = TypeSpec.interfaceBuilder(generatedDaoClassName).addModifiers(Modifier.PUBLIC) .addAnnotation(AnnotationSpec.builder(BindDao.class) .addMember("value", "$T.class", TypeUtility.className(entityPackageName, entity.name)).build()) .addAnnotation(AnnotationSpec.builder(BindGeneratedDao.class) .addMember("dao", "$T.class", entity.daoName).build()) .addAnnotation(AnnotationSpec.builder(BindDaoMany2Many.class) .addMember("entity1", "$T.class", entity.entity1Name) .addMember("entity2", "$T.class", entity.entity2Name).build()) .addSuperinterface(entity.daoName); // @formatter:on JavadocUtility.generateJavadocGeneratedBy(classBuilder); if (entity.generateMethods) { generateSelects(entity, entityPackageName); generateDeletes(entity, entityPackageName); generateInsert(entity, entityPackageName); } TypeSpec typeSpec = classBuilder.build(); try { JavaWriterHelper.writeJava2File(filer, daoPackageName, typeSpec); } catch (IOException e) { throw new KriptonRuntimeException(e); } GeneratedTypeElement daoPartElement = new GeneratedTypeElement(daoPackageName, classBuilder.build(), null, null); daoResult.add(daoPartElement); }
java
private void generateDaoPart(M2MEntity entity) { String daoClassName = entity.daoName.simpleName(); String daoPackageName = entity.daoName.packageName(); String entityPackageName = entity.getPackageName(); String generatedDaoClassName = "Generated" + daoClassName; AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDaoMany2Many.class, daoPackageName, generatedDaoClassName); // @formatter:off classBuilder = TypeSpec.interfaceBuilder(generatedDaoClassName).addModifiers(Modifier.PUBLIC) .addAnnotation(AnnotationSpec.builder(BindDao.class) .addMember("value", "$T.class", TypeUtility.className(entityPackageName, entity.name)).build()) .addAnnotation(AnnotationSpec.builder(BindGeneratedDao.class) .addMember("dao", "$T.class", entity.daoName).build()) .addAnnotation(AnnotationSpec.builder(BindDaoMany2Many.class) .addMember("entity1", "$T.class", entity.entity1Name) .addMember("entity2", "$T.class", entity.entity2Name).build()) .addSuperinterface(entity.daoName); // @formatter:on JavadocUtility.generateJavadocGeneratedBy(classBuilder); if (entity.generateMethods) { generateSelects(entity, entityPackageName); generateDeletes(entity, entityPackageName); generateInsert(entity, entityPackageName); } TypeSpec typeSpec = classBuilder.build(); try { JavaWriterHelper.writeJava2File(filer, daoPackageName, typeSpec); } catch (IOException e) { throw new KriptonRuntimeException(e); } GeneratedTypeElement daoPartElement = new GeneratedTypeElement(daoPackageName, classBuilder.build(), null, null); daoResult.add(daoPartElement); }
[ "private", "void", "generateDaoPart", "(", "M2MEntity", "entity", ")", "{", "String", "daoClassName", "=", "entity", ".", "daoName", ".", "simpleName", "(", ")", ";", "String", "daoPackageName", "=", "entity", ".", "daoName", ".", "packageName", "(", ")", ";", "String", "entityPackageName", "=", "entity", ".", "getPackageName", "(", ")", ";", "String", "generatedDaoClassName", "=", "\"Generated\"", "+", "daoClassName", ";", "AnnotationProcessorUtilis", ".", "infoOnGeneratedClasses", "(", "BindDaoMany2Many", ".", "class", ",", "daoPackageName", ",", "generatedDaoClassName", ")", ";", "// @formatter:off", "classBuilder", "=", "TypeSpec", ".", "interfaceBuilder", "(", "generatedDaoClassName", ")", ".", "addModifiers", "(", "Modifier", ".", "PUBLIC", ")", ".", "addAnnotation", "(", "AnnotationSpec", ".", "builder", "(", "BindDao", ".", "class", ")", ".", "addMember", "(", "\"value\"", ",", "\"$T.class\"", ",", "TypeUtility", ".", "className", "(", "entityPackageName", ",", "entity", ".", "name", ")", ")", ".", "build", "(", ")", ")", ".", "addAnnotation", "(", "AnnotationSpec", ".", "builder", "(", "BindGeneratedDao", ".", "class", ")", ".", "addMember", "(", "\"dao\"", ",", "\"$T.class\"", ",", "entity", ".", "daoName", ")", ".", "build", "(", ")", ")", ".", "addAnnotation", "(", "AnnotationSpec", ".", "builder", "(", "BindDaoMany2Many", ".", "class", ")", ".", "addMember", "(", "\"entity1\"", ",", "\"$T.class\"", ",", "entity", ".", "entity1Name", ")", ".", "addMember", "(", "\"entity2\"", ",", "\"$T.class\"", ",", "entity", ".", "entity2Name", ")", ".", "build", "(", ")", ")", ".", "addSuperinterface", "(", "entity", ".", "daoName", ")", ";", "// @formatter:on", "JavadocUtility", ".", "generateJavadocGeneratedBy", "(", "classBuilder", ")", ";", "if", "(", "entity", ".", "generateMethods", ")", "{", "generateSelects", "(", "entity", ",", "entityPackageName", ")", ";", "generateDeletes", "(", "entity", ",", "entityPackageName", ")", ";", "generateInsert", "(", "entity", ",", "entityPackageName", ")", ";", "}", "TypeSpec", "typeSpec", "=", "classBuilder", ".", "build", "(", ")", ";", "try", "{", "JavaWriterHelper", ".", "writeJava2File", "(", "filer", ",", "daoPackageName", ",", "typeSpec", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "KriptonRuntimeException", "(", "e", ")", ";", "}", "GeneratedTypeElement", "daoPartElement", "=", "new", "GeneratedTypeElement", "(", "daoPackageName", ",", "classBuilder", ".", "build", "(", ")", ",", "null", ",", "null", ")", ";", "daoResult", ".", "add", "(", "daoPartElement", ")", ";", "}" ]
Generate dao part. @param entity the entity @throws IOException Signals that an I/O exception has occurred.
[ "Generate", "dao", "part", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/BindM2MBuilder.java#L183-L222
spring-projects/spring-android
spring-android-core/src/main/java/org/springframework/core/CollectionFactory.java
CollectionFactory.createApproximateMap
@SuppressWarnings("unchecked") public static Map createApproximateMap(Object map, int initialCapacity) { """ Create the most approximate map for the given map. <p>Creates a TreeMap or linked Map for a SortedMap or Map, respectively. @param map the original Map object @param initialCapacity the initial capacity @return the new Map instance @see java.util.TreeMap @see java.util.LinkedHashMap """ if (map instanceof SortedMap) { return new TreeMap(((SortedMap) map).comparator()); } else { return new LinkedHashMap(initialCapacity); } }
java
@SuppressWarnings("unchecked") public static Map createApproximateMap(Object map, int initialCapacity) { if (map instanceof SortedMap) { return new TreeMap(((SortedMap) map).comparator()); } else { return new LinkedHashMap(initialCapacity); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "Map", "createApproximateMap", "(", "Object", "map", ",", "int", "initialCapacity", ")", "{", "if", "(", "map", "instanceof", "SortedMap", ")", "{", "return", "new", "TreeMap", "(", "(", "(", "SortedMap", ")", "map", ")", ".", "comparator", "(", ")", ")", ";", "}", "else", "{", "return", "new", "LinkedHashMap", "(", "initialCapacity", ")", ";", "}", "}" ]
Create the most approximate map for the given map. <p>Creates a TreeMap or linked Map for a SortedMap or Map, respectively. @param map the original Map object @param initialCapacity the initial capacity @return the new Map instance @see java.util.TreeMap @see java.util.LinkedHashMap
[ "Create", "the", "most", "approximate", "map", "for", "the", "given", "map", ".", "<p", ">", "Creates", "a", "TreeMap", "or", "linked", "Map", "for", "a", "SortedMap", "or", "Map", "respectively", "." ]
train
https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-core/src/main/java/org/springframework/core/CollectionFactory.java#L279-L287
cdk/cdk
base/standard/src/main/java/org/openscience/cdk/geometry/BondTools.java
BondTools.closeEnoughToBond
public static boolean closeEnoughToBond(IAtom atom1, IAtom atom2, double distanceFudgeFactor) { """ Returns true if the two atoms are within the distance fudge factor of each other. @param atom1 Description of Parameter @param atom2 Description of Parameter @param distanceFudgeFactor Description of Parameter @return Description of the Returned Value @cdk.keyword join-the-dots @cdk.keyword bond creation """ if (!atom1.equals(atom2)) { double distanceBetweenAtoms = atom1.getPoint3d().distance(atom2.getPoint3d()); double bondingDistance = atom1.getCovalentRadius() + atom2.getCovalentRadius(); if (distanceBetweenAtoms <= (distanceFudgeFactor * bondingDistance)) { return true; } } return false; }
java
public static boolean closeEnoughToBond(IAtom atom1, IAtom atom2, double distanceFudgeFactor) { if (!atom1.equals(atom2)) { double distanceBetweenAtoms = atom1.getPoint3d().distance(atom2.getPoint3d()); double bondingDistance = atom1.getCovalentRadius() + atom2.getCovalentRadius(); if (distanceBetweenAtoms <= (distanceFudgeFactor * bondingDistance)) { return true; } } return false; }
[ "public", "static", "boolean", "closeEnoughToBond", "(", "IAtom", "atom1", ",", "IAtom", "atom2", ",", "double", "distanceFudgeFactor", ")", "{", "if", "(", "!", "atom1", ".", "equals", "(", "atom2", ")", ")", "{", "double", "distanceBetweenAtoms", "=", "atom1", ".", "getPoint3d", "(", ")", ".", "distance", "(", "atom2", ".", "getPoint3d", "(", ")", ")", ";", "double", "bondingDistance", "=", "atom1", ".", "getCovalentRadius", "(", ")", "+", "atom2", ".", "getCovalentRadius", "(", ")", ";", "if", "(", "distanceBetweenAtoms", "<=", "(", "distanceFudgeFactor", "*", "bondingDistance", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if the two atoms are within the distance fudge factor of each other. @param atom1 Description of Parameter @param atom2 Description of Parameter @param distanceFudgeFactor Description of Parameter @return Description of the Returned Value @cdk.keyword join-the-dots @cdk.keyword bond creation
[ "Returns", "true", "if", "the", "two", "atoms", "are", "within", "the", "distance", "fudge", "factor", "of", "each", "other", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/geometry/BondTools.java#L133-L143
jcuda/jcusparse
JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java
JCusparse.cusparseXcsrgemmNnz
public static int cusparseXcsrgemmNnz( cusparseHandle handle, int transA, int transB, int m, int n, int k, cusparseMatDescr descrA, int nnzA, Pointer csrSortedRowPtrA, Pointer csrSortedColIndA, cusparseMatDescr descrB, int nnzB, Pointer csrSortedRowPtrB, Pointer csrSortedColIndB, cusparseMatDescr descrC, Pointer csrSortedRowPtrC, Pointer nnzTotalDevHostPtr) { """ Description: Compute sparse - sparse matrix multiplication for matrices stored in CSR format. """ return checkResult(cusparseXcsrgemmNnzNative(handle, transA, transB, m, n, k, descrA, nnzA, csrSortedRowPtrA, csrSortedColIndA, descrB, nnzB, csrSortedRowPtrB, csrSortedColIndB, descrC, csrSortedRowPtrC, nnzTotalDevHostPtr)); }
java
public static int cusparseXcsrgemmNnz( cusparseHandle handle, int transA, int transB, int m, int n, int k, cusparseMatDescr descrA, int nnzA, Pointer csrSortedRowPtrA, Pointer csrSortedColIndA, cusparseMatDescr descrB, int nnzB, Pointer csrSortedRowPtrB, Pointer csrSortedColIndB, cusparseMatDescr descrC, Pointer csrSortedRowPtrC, Pointer nnzTotalDevHostPtr) { return checkResult(cusparseXcsrgemmNnzNative(handle, transA, transB, m, n, k, descrA, nnzA, csrSortedRowPtrA, csrSortedColIndA, descrB, nnzB, csrSortedRowPtrB, csrSortedColIndB, descrC, csrSortedRowPtrC, nnzTotalDevHostPtr)); }
[ "public", "static", "int", "cusparseXcsrgemmNnz", "(", "cusparseHandle", "handle", ",", "int", "transA", ",", "int", "transB", ",", "int", "m", ",", "int", "n", ",", "int", "k", ",", "cusparseMatDescr", "descrA", ",", "int", "nnzA", ",", "Pointer", "csrSortedRowPtrA", ",", "Pointer", "csrSortedColIndA", ",", "cusparseMatDescr", "descrB", ",", "int", "nnzB", ",", "Pointer", "csrSortedRowPtrB", ",", "Pointer", "csrSortedColIndB", ",", "cusparseMatDescr", "descrC", ",", "Pointer", "csrSortedRowPtrC", ",", "Pointer", "nnzTotalDevHostPtr", ")", "{", "return", "checkResult", "(", "cusparseXcsrgemmNnzNative", "(", "handle", ",", "transA", ",", "transB", ",", "m", ",", "n", ",", "k", ",", "descrA", ",", "nnzA", ",", "csrSortedRowPtrA", ",", "csrSortedColIndA", ",", "descrB", ",", "nnzB", ",", "csrSortedRowPtrB", ",", "csrSortedColIndB", ",", "descrC", ",", "csrSortedRowPtrC", ",", "nnzTotalDevHostPtr", ")", ")", ";", "}" ]
Description: Compute sparse - sparse matrix multiplication for matrices stored in CSR format.
[ "Description", ":", "Compute", "sparse", "-", "sparse", "matrix", "multiplication", "for", "matrices", "stored", "in", "CSR", "format", "." ]
train
https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L9354-L9374
citrusframework/citrus
modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/SoapClientActionBuilder.java
SoapClientActionBuilder.send
public SoapClientRequestActionBuilder send() { """ Generic request builder with request method and path. @return """ SoapClientRequestActionBuilder soapClientRequestActionBuilder; if (soapClient != null) { soapClientRequestActionBuilder = new SoapClientRequestActionBuilder(action, soapClient); } else { soapClientRequestActionBuilder = new SoapClientRequestActionBuilder(action, soapClientUri); } soapClientRequestActionBuilder.withApplicationContext(applicationContext); return soapClientRequestActionBuilder; }
java
public SoapClientRequestActionBuilder send() { SoapClientRequestActionBuilder soapClientRequestActionBuilder; if (soapClient != null) { soapClientRequestActionBuilder = new SoapClientRequestActionBuilder(action, soapClient); } else { soapClientRequestActionBuilder = new SoapClientRequestActionBuilder(action, soapClientUri); } soapClientRequestActionBuilder.withApplicationContext(applicationContext); return soapClientRequestActionBuilder; }
[ "public", "SoapClientRequestActionBuilder", "send", "(", ")", "{", "SoapClientRequestActionBuilder", "soapClientRequestActionBuilder", ";", "if", "(", "soapClient", "!=", "null", ")", "{", "soapClientRequestActionBuilder", "=", "new", "SoapClientRequestActionBuilder", "(", "action", ",", "soapClient", ")", ";", "}", "else", "{", "soapClientRequestActionBuilder", "=", "new", "SoapClientRequestActionBuilder", "(", "action", ",", "soapClientUri", ")", ";", "}", "soapClientRequestActionBuilder", ".", "withApplicationContext", "(", "applicationContext", ")", ";", "return", "soapClientRequestActionBuilder", ";", "}" ]
Generic request builder with request method and path. @return
[ "Generic", "request", "builder", "with", "request", "method", "and", "path", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/SoapClientActionBuilder.java#L76-L87
landawn/AbacusUtil
src/com/landawn/abacus/util/JdbcUtil.java
JdbcUtil.importData
@SuppressWarnings("rawtypes") public static int importData(final DataSet dataset, final PreparedStatement stmt, final Map<String, ? extends Type> columnTypeMap) throws UncheckedSQLException { """ Imports the data from <code>DataSet</code> to database. @param dataset @param stmt the column order in the sql must be consistent with the column order in the DataSet. @param columnTypeMap @return @throws UncheckedSQLException """ return importData(dataset, 0, dataset.size(), stmt, columnTypeMap); }
java
@SuppressWarnings("rawtypes") public static int importData(final DataSet dataset, final PreparedStatement stmt, final Map<String, ? extends Type> columnTypeMap) throws UncheckedSQLException { return importData(dataset, 0, dataset.size(), stmt, columnTypeMap); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "public", "static", "int", "importData", "(", "final", "DataSet", "dataset", ",", "final", "PreparedStatement", "stmt", ",", "final", "Map", "<", "String", ",", "?", "extends", "Type", ">", "columnTypeMap", ")", "throws", "UncheckedSQLException", "{", "return", "importData", "(", "dataset", ",", "0", ",", "dataset", ".", "size", "(", ")", ",", "stmt", ",", "columnTypeMap", ")", ";", "}" ]
Imports the data from <code>DataSet</code> to database. @param dataset @param stmt the column order in the sql must be consistent with the column order in the DataSet. @param columnTypeMap @return @throws UncheckedSQLException
[ "Imports", "the", "data", "from", "<code", ">", "DataSet<", "/", "code", ">", "to", "database", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/JdbcUtil.java#L2260-L2264
apache/groovy
src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java
IOGroovyMethods.withWriter
public static <T> T withWriter(OutputStream stream, @ClosureParams(value=SimpleType.class, options="java.io.Writer") Closure<T> closure) throws IOException { """ Creates a writer from this stream, passing it to the given closure. This method ensures the stream is closed after the closure returns. @param stream the stream which is used and then closed @param closure the closure that the writer is passed into @return the value returned by the closure @throws IOException if an IOException occurs. @see #withWriter(java.io.Writer, groovy.lang.Closure) @since 1.5.2 """ return withWriter(new OutputStreamWriter(stream), closure); }
java
public static <T> T withWriter(OutputStream stream, @ClosureParams(value=SimpleType.class, options="java.io.Writer") Closure<T> closure) throws IOException { return withWriter(new OutputStreamWriter(stream), closure); }
[ "public", "static", "<", "T", ">", "T", "withWriter", "(", "OutputStream", "stream", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"java.io.Writer\"", ")", "Closure", "<", "T", ">", "closure", ")", "throws", "IOException", "{", "return", "withWriter", "(", "new", "OutputStreamWriter", "(", "stream", ")", ",", "closure", ")", ";", "}" ]
Creates a writer from this stream, passing it to the given closure. This method ensures the stream is closed after the closure returns. @param stream the stream which is used and then closed @param closure the closure that the writer is passed into @return the value returned by the closure @throws IOException if an IOException occurs. @see #withWriter(java.io.Writer, groovy.lang.Closure) @since 1.5.2
[ "Creates", "a", "writer", "from", "this", "stream", "passing", "it", "to", "the", "given", "closure", ".", "This", "method", "ensures", "the", "stream", "is", "closed", "after", "the", "closure", "returns", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java#L1241-L1243
Netflix/Nicobar
nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossModuleClassLoader.java
JBossModuleClassLoader.createFactory
protected static ModuleClassLoaderFactory createFactory(final ScriptArchive scriptArchive) { """ Creates a ModuleClassLoaderFactory that produces a {@link JBossModuleClassLoader}. This method is necessary to inject our custom {@link ModuleClassLoader} into the {@link ModuleSpec} """ return new ModuleClassLoaderFactory() { public ModuleClassLoader create(final Configuration configuration) { return AccessController.doPrivileged( new PrivilegedAction<JBossModuleClassLoader>() { public JBossModuleClassLoader run() { return new JBossModuleClassLoader(configuration, scriptArchive); } }); } }; }
java
protected static ModuleClassLoaderFactory createFactory(final ScriptArchive scriptArchive) { return new ModuleClassLoaderFactory() { public ModuleClassLoader create(final Configuration configuration) { return AccessController.doPrivileged( new PrivilegedAction<JBossModuleClassLoader>() { public JBossModuleClassLoader run() { return new JBossModuleClassLoader(configuration, scriptArchive); } }); } }; }
[ "protected", "static", "ModuleClassLoaderFactory", "createFactory", "(", "final", "ScriptArchive", "scriptArchive", ")", "{", "return", "new", "ModuleClassLoaderFactory", "(", ")", "{", "public", "ModuleClassLoader", "create", "(", "final", "Configuration", "configuration", ")", "{", "return", "AccessController", ".", "doPrivileged", "(", "new", "PrivilegedAction", "<", "JBossModuleClassLoader", ">", "(", ")", "{", "public", "JBossModuleClassLoader", "run", "(", ")", "{", "return", "new", "JBossModuleClassLoader", "(", "configuration", ",", "scriptArchive", ")", ";", "}", "}", ")", ";", "}", "}", ";", "}" ]
Creates a ModuleClassLoaderFactory that produces a {@link JBossModuleClassLoader}. This method is necessary to inject our custom {@link ModuleClassLoader} into the {@link ModuleSpec}
[ "Creates", "a", "ModuleClassLoaderFactory", "that", "produces", "a", "{" ]
train
https://github.com/Netflix/Nicobar/blob/507173dcae4a86a955afc3df222a855862fab8d7/nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossModuleClassLoader.java#L63-L74
maxirosson/jdroid-android
jdroid-android-google-inappbilling/src/main/java/com/jdroid/android/google/inappbilling/client/InAppBillingClient.java
InAppBillingClient.launchPurchaseFlow
private void launchPurchaseFlow(Activity activity, Product product, ItemType itemType, String oldProductId) { """ Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase, which will involve bringing up the Google Play screen. The calling activity will be paused while the user interacts with Google Play This method MUST be called from the UI thread of the Activity. @param activity The calling activity. @param product The product to purchase. @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS) @param oldProductId The SKU which the new SKU is replacing or null if there is none """ executeServiceRequest(new Runnable() { @Override public void run() { if (itemType.equals(ItemType.SUBSCRIPTION) && !isSubscriptionsSupported()) { LOGGER.debug("Failed in-app purchase flow for product id " + product.getId() + ", item type: " + itemType + ". Subscriptions not supported."); if (listener != null) { listener.onPurchaseFailed(InAppBillingErrorCode.SUBSCRIPTIONS_NOT_AVAILABLE.newErrorCodeException()); } } else { LOGGER.debug("Launching in-app purchase flow for product id " + product.getId() + ", item type: " + itemType); String productIdToBuy = InAppBillingAppModule.get().getInAppBillingContext().isStaticResponsesEnabled() ? product.getProductType().getTestProductId() : product.getId(); BillingFlowParams purchaseParams = BillingFlowParams.newBuilder() .setSku(productIdToBuy) .setType(itemType.getType()) .setOldSku(oldProductId) .build(); int responseCode = billingClient.launchBillingFlow(activity, purchaseParams); InAppBillingErrorCode inAppBillingErrorCode = InAppBillingErrorCode.findByErrorResponseCode(responseCode); if (inAppBillingErrorCode != null) { if (listener != null) { AbstractApplication.get().getExceptionHandler().logHandledException(inAppBillingErrorCode.newErrorCodeException()); listener.onPurchaseFailed(inAppBillingErrorCode.newErrorCodeException()); } } } } }); }
java
private void launchPurchaseFlow(Activity activity, Product product, ItemType itemType, String oldProductId) { executeServiceRequest(new Runnable() { @Override public void run() { if (itemType.equals(ItemType.SUBSCRIPTION) && !isSubscriptionsSupported()) { LOGGER.debug("Failed in-app purchase flow for product id " + product.getId() + ", item type: " + itemType + ". Subscriptions not supported."); if (listener != null) { listener.onPurchaseFailed(InAppBillingErrorCode.SUBSCRIPTIONS_NOT_AVAILABLE.newErrorCodeException()); } } else { LOGGER.debug("Launching in-app purchase flow for product id " + product.getId() + ", item type: " + itemType); String productIdToBuy = InAppBillingAppModule.get().getInAppBillingContext().isStaticResponsesEnabled() ? product.getProductType().getTestProductId() : product.getId(); BillingFlowParams purchaseParams = BillingFlowParams.newBuilder() .setSku(productIdToBuy) .setType(itemType.getType()) .setOldSku(oldProductId) .build(); int responseCode = billingClient.launchBillingFlow(activity, purchaseParams); InAppBillingErrorCode inAppBillingErrorCode = InAppBillingErrorCode.findByErrorResponseCode(responseCode); if (inAppBillingErrorCode != null) { if (listener != null) { AbstractApplication.get().getExceptionHandler().logHandledException(inAppBillingErrorCode.newErrorCodeException()); listener.onPurchaseFailed(inAppBillingErrorCode.newErrorCodeException()); } } } } }); }
[ "private", "void", "launchPurchaseFlow", "(", "Activity", "activity", ",", "Product", "product", ",", "ItemType", "itemType", ",", "String", "oldProductId", ")", "{", "executeServiceRequest", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "itemType", ".", "equals", "(", "ItemType", ".", "SUBSCRIPTION", ")", "&&", "!", "isSubscriptionsSupported", "(", ")", ")", "{", "LOGGER", ".", "debug", "(", "\"Failed in-app purchase flow for product id \"", "+", "product", ".", "getId", "(", ")", "+", "\", item type: \"", "+", "itemType", "+", "\". Subscriptions not supported.\"", ")", ";", "if", "(", "listener", "!=", "null", ")", "{", "listener", ".", "onPurchaseFailed", "(", "InAppBillingErrorCode", ".", "SUBSCRIPTIONS_NOT_AVAILABLE", ".", "newErrorCodeException", "(", ")", ")", ";", "}", "}", "else", "{", "LOGGER", ".", "debug", "(", "\"Launching in-app purchase flow for product id \"", "+", "product", ".", "getId", "(", ")", "+", "\", item type: \"", "+", "itemType", ")", ";", "String", "productIdToBuy", "=", "InAppBillingAppModule", ".", "get", "(", ")", ".", "getInAppBillingContext", "(", ")", ".", "isStaticResponsesEnabled", "(", ")", "?", "product", ".", "getProductType", "(", ")", ".", "getTestProductId", "(", ")", ":", "product", ".", "getId", "(", ")", ";", "BillingFlowParams", "purchaseParams", "=", "BillingFlowParams", ".", "newBuilder", "(", ")", ".", "setSku", "(", "productIdToBuy", ")", ".", "setType", "(", "itemType", ".", "getType", "(", ")", ")", ".", "setOldSku", "(", "oldProductId", ")", ".", "build", "(", ")", ";", "int", "responseCode", "=", "billingClient", ".", "launchBillingFlow", "(", "activity", ",", "purchaseParams", ")", ";", "InAppBillingErrorCode", "inAppBillingErrorCode", "=", "InAppBillingErrorCode", ".", "findByErrorResponseCode", "(", "responseCode", ")", ";", "if", "(", "inAppBillingErrorCode", "!=", "null", ")", "{", "if", "(", "listener", "!=", "null", ")", "{", "AbstractApplication", ".", "get", "(", ")", ".", "getExceptionHandler", "(", ")", ".", "logHandledException", "(", "inAppBillingErrorCode", ".", "newErrorCodeException", "(", ")", ")", ";", "listener", ".", "onPurchaseFailed", "(", "inAppBillingErrorCode", ".", "newErrorCodeException", "(", ")", ")", ";", "}", "}", "}", "}", "}", ")", ";", "}" ]
Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase, which will involve bringing up the Google Play screen. The calling activity will be paused while the user interacts with Google Play This method MUST be called from the UI thread of the Activity. @param activity The calling activity. @param product The product to purchase. @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS) @param oldProductId The SKU which the new SKU is replacing or null if there is none
[ "Initiate", "the", "UI", "flow", "for", "an", "in", "-", "app", "purchase", ".", "Call", "this", "method", "to", "initiate", "an", "in", "-", "app", "purchase", "which", "will", "involve", "bringing", "up", "the", "Google", "Play", "screen", ".", "The", "calling", "activity", "will", "be", "paused", "while", "the", "user", "interacts", "with", "Google", "Play", "This", "method", "MUST", "be", "called", "from", "the", "UI", "thread", "of", "the", "Activity", "." ]
train
https://github.com/maxirosson/jdroid-android/blob/1ba9cae56a16fa36bdb2c9c04379853f0300707f/jdroid-android-google-inappbilling/src/main/java/com/jdroid/android/google/inappbilling/client/InAppBillingClient.java#L393-L422
Azure/azure-sdk-for-java
network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/RoutesInner.java
RoutesInner.beginCreateOrUpdateAsync
public Observable<RouteInner> beginCreateOrUpdateAsync(String resourceGroupName, String routeTableName, String routeName, RouteInner routeParameters) { """ Creates or updates a route in the specified route table. @param resourceGroupName The name of the resource group. @param routeTableName The name of the route table. @param routeName The name of the route. @param routeParameters Parameters supplied to the create or update route operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RouteInner object """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, routeTableName, routeName, routeParameters).map(new Func1<ServiceResponse<RouteInner>, RouteInner>() { @Override public RouteInner call(ServiceResponse<RouteInner> response) { return response.body(); } }); }
java
public Observable<RouteInner> beginCreateOrUpdateAsync(String resourceGroupName, String routeTableName, String routeName, RouteInner routeParameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, routeTableName, routeName, routeParameters).map(new Func1<ServiceResponse<RouteInner>, RouteInner>() { @Override public RouteInner call(ServiceResponse<RouteInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RouteInner", ">", "beginCreateOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "routeTableName", ",", "String", "routeName", ",", "RouteInner", "routeParameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "routeTableName", ",", "routeName", ",", "routeParameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "RouteInner", ">", ",", "RouteInner", ">", "(", ")", "{", "@", "Override", "public", "RouteInner", "call", "(", "ServiceResponse", "<", "RouteInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates or updates a route in the specified route table. @param resourceGroupName The name of the resource group. @param routeTableName The name of the route table. @param routeName The name of the route. @param routeParameters Parameters supplied to the create or update route operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RouteInner object
[ "Creates", "or", "updates", "a", "route", "in", "the", "specified", "route", "table", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/RoutesInner.java#L473-L480
BigBadaboom/androidsvg
androidsvg/src/main/java/com/caverock/androidsvg/SVG.java
SVG.renderToCanvas
@SuppressWarnings( { """ Renders this SVG document to a Canvas object. @param canvas the canvas to which the document should be rendered. @param renderOptions options that describe how to render this SVG on the Canvas. @since 1.3 """"WeakerAccess", "unused"}) public void renderToCanvas(Canvas canvas, RenderOptions renderOptions) { if (renderOptions == null) renderOptions = new RenderOptions(); if (!renderOptions.hasViewPort()) { renderOptions.viewPort(0f, 0f, (float) canvas.getWidth(), (float) canvas.getHeight()); } SVGAndroidRenderer renderer = new SVGAndroidRenderer(canvas, this.renderDPI); renderer.renderDocument(this, renderOptions); }
java
@SuppressWarnings({"WeakerAccess", "unused"}) public void renderToCanvas(Canvas canvas, RenderOptions renderOptions) { if (renderOptions == null) renderOptions = new RenderOptions(); if (!renderOptions.hasViewPort()) { renderOptions.viewPort(0f, 0f, (float) canvas.getWidth(), (float) canvas.getHeight()); } SVGAndroidRenderer renderer = new SVGAndroidRenderer(canvas, this.renderDPI); renderer.renderDocument(this, renderOptions); }
[ "@", "SuppressWarnings", "(", "{", "\"WeakerAccess\"", ",", "\"unused\"", "}", ")", "public", "void", "renderToCanvas", "(", "Canvas", "canvas", ",", "RenderOptions", "renderOptions", ")", "{", "if", "(", "renderOptions", "==", "null", ")", "renderOptions", "=", "new", "RenderOptions", "(", ")", ";", "if", "(", "!", "renderOptions", ".", "hasViewPort", "(", ")", ")", "{", "renderOptions", ".", "viewPort", "(", "0f", ",", "0f", ",", "(", "float", ")", "canvas", ".", "getWidth", "(", ")", ",", "(", "float", ")", "canvas", ".", "getHeight", "(", ")", ")", ";", "}", "SVGAndroidRenderer", "renderer", "=", "new", "SVGAndroidRenderer", "(", "canvas", ",", "this", ".", "renderDPI", ")", ";", "renderer", ".", "renderDocument", "(", "this", ",", "renderOptions", ")", ";", "}" ]
Renders this SVG document to a Canvas object. @param canvas the canvas to which the document should be rendered. @param renderOptions options that describe how to render this SVG on the Canvas. @since 1.3
[ "Renders", "this", "SVG", "document", "to", "a", "Canvas", "object", "." ]
train
https://github.com/BigBadaboom/androidsvg/blob/0d1614dd1a4da10ea4afe3b0cea1361a4ac6b45a/androidsvg/src/main/java/com/caverock/androidsvg/SVG.java#L528-L541
lordcodes/SnackbarBuilder
snackbarbuilder/src/main/java/com/github/andrewlord1990/snackbarbuilder/SnackbarWrapper.java
SnackbarWrapper.setIcon
@NonNull @SuppressWarnings("WeakerAccess") public SnackbarWrapper setIcon(@DrawableRes int icon) { """ Set the icon at the start of the Snackbar. If there is no icon it will be added, or if there is then it will be replaced. @param icon The icon drawable resource to display. @return This instance. """ return setIcon(ContextCompat.getDrawable(context, icon)); }
java
@NonNull @SuppressWarnings("WeakerAccess") public SnackbarWrapper setIcon(@DrawableRes int icon) { return setIcon(ContextCompat.getDrawable(context, icon)); }
[ "@", "NonNull", "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "public", "SnackbarWrapper", "setIcon", "(", "@", "DrawableRes", "int", "icon", ")", "{", "return", "setIcon", "(", "ContextCompat", ".", "getDrawable", "(", "context", ",", "icon", ")", ")", ";", "}" ]
Set the icon at the start of the Snackbar. If there is no icon it will be added, or if there is then it will be replaced. @param icon The icon drawable resource to display. @return This instance.
[ "Set", "the", "icon", "at", "the", "start", "of", "the", "Snackbar", ".", "If", "there", "is", "no", "icon", "it", "will", "be", "added", "or", "if", "there", "is", "then", "it", "will", "be", "replaced", "." ]
train
https://github.com/lordcodes/SnackbarBuilder/blob/a104a753c78ed66940c19d295e141a521cf81d73/snackbarbuilder/src/main/java/com/github/andrewlord1990/snackbarbuilder/SnackbarWrapper.java#L538-L542
OpenLiberty/open-liberty
dev/com.ibm.ws.ras.instrument/src/com/ibm/ws/ras/instrument/internal/bci/AbstractRasClassAdapter.java
AbstractRasClassAdapter.visitInnerClass
@Override public void visitInnerClass(String name, String outerName, String innerName, int access) { """ Visit the information about an inner class. We use this to determine whether or not the we're visiting an inner class. This callback is also used to ensure that appropriate class level annotations exist. """ // Make sure the class is annotated. ensureAnnotated(); if (name.equals(getClassInternalName())) { StringBuilder sb = new StringBuilder(); sb.append(outerName); sb.append("$"); sb.append(innerName); isInnerClass = name.equals(sb.toString()); } super.visitInnerClass(name, outerName, innerName, access); }
java
@Override public void visitInnerClass(String name, String outerName, String innerName, int access) { // Make sure the class is annotated. ensureAnnotated(); if (name.equals(getClassInternalName())) { StringBuilder sb = new StringBuilder(); sb.append(outerName); sb.append("$"); sb.append(innerName); isInnerClass = name.equals(sb.toString()); } super.visitInnerClass(name, outerName, innerName, access); }
[ "@", "Override", "public", "void", "visitInnerClass", "(", "String", "name", ",", "String", "outerName", ",", "String", "innerName", ",", "int", "access", ")", "{", "// Make sure the class is annotated.", "ensureAnnotated", "(", ")", ";", "if", "(", "name", ".", "equals", "(", "getClassInternalName", "(", ")", ")", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "outerName", ")", ";", "sb", ".", "append", "(", "\"$\"", ")", ";", "sb", ".", "append", "(", "innerName", ")", ";", "isInnerClass", "=", "name", ".", "equals", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "super", ".", "visitInnerClass", "(", "name", ",", "outerName", ",", "innerName", ",", "access", ")", ";", "}" ]
Visit the information about an inner class. We use this to determine whether or not the we're visiting an inner class. This callback is also used to ensure that appropriate class level annotations exist.
[ "Visit", "the", "information", "about", "an", "inner", "class", ".", "We", "use", "this", "to", "determine", "whether", "or", "not", "the", "we", "re", "visiting", "an", "inner", "class", ".", "This", "callback", "is", "also", "used", "to", "ensure", "that", "appropriate", "class", "level", "annotations", "exist", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ras.instrument/src/com/ibm/ws/ras/instrument/internal/bci/AbstractRasClassAdapter.java#L176-L190
nakamura5akihito/six-util
src/main/java/jp/go/aist/six/util/core/web/spring/SpringHttpClientImpl.java
SpringHttpClientImpl.postByRead
public String postByRead( final String url, final InputStream input, final String media_type ) { """ HTTP POST: Reads the contents from the specified stream and sends them to the URL. @return the location, as an URI, where the resource is created. @throws HttpException when an exceptional condition occurred during the HTTP method execution. """ InputStreamRequestCallback callback = new InputStreamRequestCallback( input, MediaType.valueOf( media_type ) ); String location = _execute( url, HttpMethod.POST, callback, new LocationHeaderResponseExtractor() ); return location; }
java
public String postByRead( final String url, final InputStream input, final String media_type ) { InputStreamRequestCallback callback = new InputStreamRequestCallback( input, MediaType.valueOf( media_type ) ); String location = _execute( url, HttpMethod.POST, callback, new LocationHeaderResponseExtractor() ); return location; }
[ "public", "String", "postByRead", "(", "final", "String", "url", ",", "final", "InputStream", "input", ",", "final", "String", "media_type", ")", "{", "InputStreamRequestCallback", "callback", "=", "new", "InputStreamRequestCallback", "(", "input", ",", "MediaType", ".", "valueOf", "(", "media_type", ")", ")", ";", "String", "location", "=", "_execute", "(", "url", ",", "HttpMethod", ".", "POST", ",", "callback", ",", "new", "LocationHeaderResponseExtractor", "(", ")", ")", ";", "return", "location", ";", "}" ]
HTTP POST: Reads the contents from the specified stream and sends them to the URL. @return the location, as an URI, where the resource is created. @throws HttpException when an exceptional condition occurred during the HTTP method execution.
[ "HTTP", "POST", ":", "Reads", "the", "contents", "from", "the", "specified", "stream", "and", "sends", "them", "to", "the", "URL", "." ]
train
https://github.com/nakamura5akihito/six-util/blob/a6db388a345e220cea2b1fa6324d15c80c6278b6/src/main/java/jp/go/aist/six/util/core/web/spring/SpringHttpClientImpl.java#L379-L392
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAddressPersistenceImpl.java
CommerceAddressPersistenceImpl.removeByG_C_C
@Override public void removeByG_C_C(long groupId, long classNameId, long classPK) { """ Removes all the commerce addresses where groupId = &#63; and classNameId = &#63; and classPK = &#63; from the database. @param groupId the group ID @param classNameId the class name ID @param classPK the class pk """ for (CommerceAddress commerceAddress : findByG_C_C(groupId, classNameId, classPK, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceAddress); } }
java
@Override public void removeByG_C_C(long groupId, long classNameId, long classPK) { for (CommerceAddress commerceAddress : findByG_C_C(groupId, classNameId, classPK, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceAddress); } }
[ "@", "Override", "public", "void", "removeByG_C_C", "(", "long", "groupId", ",", "long", "classNameId", ",", "long", "classPK", ")", "{", "for", "(", "CommerceAddress", "commerceAddress", ":", "findByG_C_C", "(", "groupId", ",", "classNameId", ",", "classPK", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ")", "{", "remove", "(", "commerceAddress", ")", ";", "}", "}" ]
Removes all the commerce addresses where groupId = &#63; and classNameId = &#63; and classPK = &#63; from the database. @param groupId the group ID @param classNameId the class name ID @param classPK the class pk
[ "Removes", "all", "the", "commerce", "addresses", "where", "groupId", "=", "&#63", ";", "and", "classNameId", "=", "&#63", ";", "and", "classPK", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAddressPersistenceImpl.java#L2194-L2200
BioPAX/Paxtools
paxtools-query/src/main/java/org/biopax/paxtools/query/wrapperL3undirected/InteractionWrapper.java
InteractionWrapper.addToDownstream
protected void addToDownstream(BioPAXElement pe, Graph graph) { """ Binds the given PhysicalEntity to the downstream. @param pe PhysicalEntity to bind @param graph Owner graph """ AbstractNode node = (AbstractNode) graph.getGraphObject(pe); if (node != null) { EdgeL3 edge = new EdgeL3(this, node, graph); edge.setTranscription(true); node.getUpstreamNoInit().add(edge); this.getDownstreamNoInit().add(edge); } }
java
protected void addToDownstream(BioPAXElement pe, Graph graph) { AbstractNode node = (AbstractNode) graph.getGraphObject(pe); if (node != null) { EdgeL3 edge = new EdgeL3(this, node, graph); edge.setTranscription(true); node.getUpstreamNoInit().add(edge); this.getDownstreamNoInit().add(edge); } }
[ "protected", "void", "addToDownstream", "(", "BioPAXElement", "pe", ",", "Graph", "graph", ")", "{", "AbstractNode", "node", "=", "(", "AbstractNode", ")", "graph", ".", "getGraphObject", "(", "pe", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "EdgeL3", "edge", "=", "new", "EdgeL3", "(", "this", ",", "node", ",", "graph", ")", ";", "edge", ".", "setTranscription", "(", "true", ")", ";", "node", ".", "getUpstreamNoInit", "(", ")", ".", "add", "(", "edge", ")", ";", "this", ".", "getDownstreamNoInit", "(", ")", ".", "add", "(", "edge", ")", ";", "}", "}" ]
Binds the given PhysicalEntity to the downstream. @param pe PhysicalEntity to bind @param graph Owner graph
[ "Binds", "the", "given", "PhysicalEntity", "to", "the", "downstream", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-query/src/main/java/org/biopax/paxtools/query/wrapperL3undirected/InteractionWrapper.java#L83-L95
googleapis/google-cloud-java
google-cloud-clients/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageOptions.java
CloudStorageOptions.withUserMetadata
public static CloudStorageOption.OpenCopy withUserMetadata(String key, String value) { """ Sets an unmodifiable piece of user metadata on a Cloud Storage object. @see "https://developers.google.com/storage/docs/reference-headers#xgoogmeta" """ return OptionUserMetadata.create(key, value); }
java
public static CloudStorageOption.OpenCopy withUserMetadata(String key, String value) { return OptionUserMetadata.create(key, value); }
[ "public", "static", "CloudStorageOption", ".", "OpenCopy", "withUserMetadata", "(", "String", "key", ",", "String", "value", ")", "{", "return", "OptionUserMetadata", ".", "create", "(", "key", ",", "value", ")", ";", "}" ]
Sets an unmodifiable piece of user metadata on a Cloud Storage object. @see "https://developers.google.com/storage/docs/reference-headers#xgoogmeta"
[ "Sets", "an", "unmodifiable", "piece", "of", "user", "metadata", "on", "a", "Cloud", "Storage", "object", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageOptions.java#L75-L77
facebookarchive/hadoop-20
src/core/org/apache/hadoop/io/compress/CompressionCodecFactory.java
CompressionCodecFactory.removeSuffix
public static String removeSuffix(String filename, String suffix) { """ Removes a suffix from a filename, if it has it. @param filename the filename to strip @param suffix the suffix to remove @return the shortened filename """ if (filename.endsWith(suffix)) { return filename.substring(0, filename.length() - suffix.length()); } return filename; }
java
public static String removeSuffix(String filename, String suffix) { if (filename.endsWith(suffix)) { return filename.substring(0, filename.length() - suffix.length()); } return filename; }
[ "public", "static", "String", "removeSuffix", "(", "String", "filename", ",", "String", "suffix", ")", "{", "if", "(", "filename", ".", "endsWith", "(", "suffix", ")", ")", "{", "return", "filename", ".", "substring", "(", "0", ",", "filename", ".", "length", "(", ")", "-", "suffix", ".", "length", "(", ")", ")", ";", "}", "return", "filename", ";", "}" ]
Removes a suffix from a filename, if it has it. @param filename the filename to strip @param suffix the suffix to remove @return the shortened filename
[ "Removes", "a", "suffix", "from", "a", "filename", "if", "it", "has", "it", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/io/compress/CompressionCodecFactory.java#L195-L200
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/utils/ValueMap.java
ValueMap.withLong
public ValueMap withLong(String key, long val) { """ Sets the value of the specified key in the current ValueMap to the given value. """ return withNumber(key, Long.valueOf(val)); }
java
public ValueMap withLong(String key, long val) { return withNumber(key, Long.valueOf(val)); }
[ "public", "ValueMap", "withLong", "(", "String", "key", ",", "long", "val", ")", "{", "return", "withNumber", "(", "key", ",", "Long", ".", "valueOf", "(", "val", ")", ")", ";", "}" ]
Sets the value of the specified key in the current ValueMap to the given value.
[ "Sets", "the", "value", "of", "the", "specified", "key", "in", "the", "current", "ValueMap", "to", "the", "given", "value", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/utils/ValueMap.java#L76-L78
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
ArrowSerde.addDataForArr
public static int addDataForArr(FlatBufferBuilder bufferBuilder, INDArray arr) { """ Create a {@link Buffer} representing the location metadata of the actual data contents for the ndarrays' {@link DataBuffer} @param bufferBuilder the buffer builder in use @param arr the array to add the underlying data for @return the offset added """ DataBuffer toAdd = arr.isView() ? arr.dup().data() : arr.data(); int offset = DataBufferStruct.createDataBufferStruct(bufferBuilder,toAdd); int ret = Buffer.createBuffer(bufferBuilder,offset,toAdd.length() * toAdd.getElementSize()); return ret; }
java
public static int addDataForArr(FlatBufferBuilder bufferBuilder, INDArray arr) { DataBuffer toAdd = arr.isView() ? arr.dup().data() : arr.data(); int offset = DataBufferStruct.createDataBufferStruct(bufferBuilder,toAdd); int ret = Buffer.createBuffer(bufferBuilder,offset,toAdd.length() * toAdd.getElementSize()); return ret; }
[ "public", "static", "int", "addDataForArr", "(", "FlatBufferBuilder", "bufferBuilder", ",", "INDArray", "arr", ")", "{", "DataBuffer", "toAdd", "=", "arr", ".", "isView", "(", ")", "?", "arr", ".", "dup", "(", ")", ".", "data", "(", ")", ":", "arr", ".", "data", "(", ")", ";", "int", "offset", "=", "DataBufferStruct", ".", "createDataBufferStruct", "(", "bufferBuilder", ",", "toAdd", ")", ";", "int", "ret", "=", "Buffer", ".", "createBuffer", "(", "bufferBuilder", ",", "offset", ",", "toAdd", ".", "length", "(", ")", "*", "toAdd", ".", "getElementSize", "(", ")", ")", ";", "return", "ret", ";", "}" ]
Create a {@link Buffer} representing the location metadata of the actual data contents for the ndarrays' {@link DataBuffer} @param bufferBuilder the buffer builder in use @param arr the array to add the underlying data for @return the offset added
[ "Create", "a", "{" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java#L104-L110
Axway/Grapes
server/src/main/java/org/axway/grapes/server/core/DependencyHandler.java
DependencyHandler.getDependencyReport
public DependencyReport getDependencyReport(final String moduleId, final FiltersHolder filters) { """ Generate a report about the targeted module dependencies @param moduleId String @param filters FiltersHolder @return DependencyReport """ final DbModule module = moduleHandler.getModule(moduleId); final DbOrganization organization = moduleHandler.getOrganization(module); filters.setCorporateFilter(new CorporateFilter(organization)); final DependencyReport report = new DependencyReport(moduleId); final List<String> done = new ArrayList<String>(); for(final DbModule submodule: DataUtils.getAllSubmodules(module)){ done.add(submodule.getId()); } addModuleToReport(report, module, filters, done, 1); return report; }
java
public DependencyReport getDependencyReport(final String moduleId, final FiltersHolder filters) { final DbModule module = moduleHandler.getModule(moduleId); final DbOrganization organization = moduleHandler.getOrganization(module); filters.setCorporateFilter(new CorporateFilter(organization)); final DependencyReport report = new DependencyReport(moduleId); final List<String> done = new ArrayList<String>(); for(final DbModule submodule: DataUtils.getAllSubmodules(module)){ done.add(submodule.getId()); } addModuleToReport(report, module, filters, done, 1); return report; }
[ "public", "DependencyReport", "getDependencyReport", "(", "final", "String", "moduleId", ",", "final", "FiltersHolder", "filters", ")", "{", "final", "DbModule", "module", "=", "moduleHandler", ".", "getModule", "(", "moduleId", ")", ";", "final", "DbOrganization", "organization", "=", "moduleHandler", ".", "getOrganization", "(", "module", ")", ";", "filters", ".", "setCorporateFilter", "(", "new", "CorporateFilter", "(", "organization", ")", ")", ";", "final", "DependencyReport", "report", "=", "new", "DependencyReport", "(", "moduleId", ")", ";", "final", "List", "<", "String", ">", "done", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "final", "DbModule", "submodule", ":", "DataUtils", ".", "getAllSubmodules", "(", "module", ")", ")", "{", "done", ".", "add", "(", "submodule", ".", "getId", "(", ")", ")", ";", "}", "addModuleToReport", "(", "report", ",", "module", ",", "filters", ",", "done", ",", "1", ")", ";", "return", "report", ";", "}" ]
Generate a report about the targeted module dependencies @param moduleId String @param filters FiltersHolder @return DependencyReport
[ "Generate", "a", "report", "about", "the", "targeted", "module", "dependencies" ]
train
https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/server/src/main/java/org/axway/grapes/server/core/DependencyHandler.java#L92-L106
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/utility/ResourceCache.java
ResourceCache.wrapCallback
public static TextureCallback wrapCallback( ResourceCache<GVRImage> cache, TextureCallback callback) { """ Wrap the callback, to cache the {@link TextureCallback#loaded(GVRHybridObject, GVRAndroidResource) loaded()} resource """ return new TextureCallbackWrapper(cache, callback); }
java
public static TextureCallback wrapCallback( ResourceCache<GVRImage> cache, TextureCallback callback) { return new TextureCallbackWrapper(cache, callback); }
[ "public", "static", "TextureCallback", "wrapCallback", "(", "ResourceCache", "<", "GVRImage", ">", "cache", ",", "TextureCallback", "callback", ")", "{", "return", "new", "TextureCallbackWrapper", "(", "cache", ",", "callback", ")", ";", "}" ]
Wrap the callback, to cache the {@link TextureCallback#loaded(GVRHybridObject, GVRAndroidResource) loaded()} resource
[ "Wrap", "the", "callback", "to", "cache", "the", "{" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/utility/ResourceCache.java#L97-L100
kaazing/gateway
util/src/main/java/org/kaazing/gateway/util/asn1/Asn1Utils.java
Asn1Utils.encodeInteger
public static int encodeInteger(int value, ByteBuffer buf) { """ Encode an ASN.1 INTEGER. @param value the value to be encoded @param buf the buffer with space to the left of current position where the value will be encoded @return the length of the encoded data """ int pos = buf.position(); int contentLength = 0; do { pos--; buf.put(pos, (byte) (value & 0xff)); value >>>= 8; contentLength++; } while (value != 0); buf.position(buf.position() - contentLength); int headerLen = DerUtils.encodeIdAndLength(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE, ASN1_INTEGER_TAG_NUM, contentLength, buf); return headerLen + contentLength; }
java
public static int encodeInteger(int value, ByteBuffer buf) { int pos = buf.position(); int contentLength = 0; do { pos--; buf.put(pos, (byte) (value & 0xff)); value >>>= 8; contentLength++; } while (value != 0); buf.position(buf.position() - contentLength); int headerLen = DerUtils.encodeIdAndLength(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE, ASN1_INTEGER_TAG_NUM, contentLength, buf); return headerLen + contentLength; }
[ "public", "static", "int", "encodeInteger", "(", "int", "value", ",", "ByteBuffer", "buf", ")", "{", "int", "pos", "=", "buf", ".", "position", "(", ")", ";", "int", "contentLength", "=", "0", ";", "do", "{", "pos", "--", ";", "buf", ".", "put", "(", "pos", ",", "(", "byte", ")", "(", "value", "&", "0xff", ")", ")", ";", "value", ">>>=", "8", ";", "contentLength", "++", ";", "}", "while", "(", "value", "!=", "0", ")", ";", "buf", ".", "position", "(", "buf", ".", "position", "(", ")", "-", "contentLength", ")", ";", "int", "headerLen", "=", "DerUtils", ".", "encodeIdAndLength", "(", "DerId", ".", "TagClass", ".", "UNIVERSAL", ",", "DerId", ".", "EncodingType", ".", "PRIMITIVE", ",", "ASN1_INTEGER_TAG_NUM", ",", "contentLength", ",", "buf", ")", ";", "return", "headerLen", "+", "contentLength", ";", "}" ]
Encode an ASN.1 INTEGER. @param value the value to be encoded @param buf the buffer with space to the left of current position where the value will be encoded @return the length of the encoded data
[ "Encode", "an", "ASN", ".", "1", "INTEGER", "." ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/util/src/main/java/org/kaazing/gateway/util/asn1/Asn1Utils.java#L330-L343
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UTF16.java
UTF16.findOffsetFromCodePoint
public static int findOffsetFromCodePoint(StringBuffer source, int offset32) { """ Returns the UTF-16 offset that corresponds to a UTF-32 offset. Used for random access. See the {@link UTF16 class description} for notes on roundtripping. @param source The UTF-16 string buffer @param offset32 UTF-32 offset @return UTF-16 offset @exception IndexOutOfBoundsException If offset32 is out of bounds. """ char ch; int size = source.length(), result = 0, count = offset32; if (offset32 < 0 || offset32 > size) { throw new StringIndexOutOfBoundsException(offset32); } while (result < size && count > 0) { ch = source.charAt(result); if (isLeadSurrogate(ch) && ((result + 1) < size) && isTrailSurrogate(source.charAt(result + 1))) { result++; } count--; result++; } if (count != 0) { throw new StringIndexOutOfBoundsException(offset32); } return result; }
java
public static int findOffsetFromCodePoint(StringBuffer source, int offset32) { char ch; int size = source.length(), result = 0, count = offset32; if (offset32 < 0 || offset32 > size) { throw new StringIndexOutOfBoundsException(offset32); } while (result < size && count > 0) { ch = source.charAt(result); if (isLeadSurrogate(ch) && ((result + 1) < size) && isTrailSurrogate(source.charAt(result + 1))) { result++; } count--; result++; } if (count != 0) { throw new StringIndexOutOfBoundsException(offset32); } return result; }
[ "public", "static", "int", "findOffsetFromCodePoint", "(", "StringBuffer", "source", ",", "int", "offset32", ")", "{", "char", "ch", ";", "int", "size", "=", "source", ".", "length", "(", ")", ",", "result", "=", "0", ",", "count", "=", "offset32", ";", "if", "(", "offset32", "<", "0", "||", "offset32", ">", "size", ")", "{", "throw", "new", "StringIndexOutOfBoundsException", "(", "offset32", ")", ";", "}", "while", "(", "result", "<", "size", "&&", "count", ">", "0", ")", "{", "ch", "=", "source", ".", "charAt", "(", "result", ")", ";", "if", "(", "isLeadSurrogate", "(", "ch", ")", "&&", "(", "(", "result", "+", "1", ")", "<", "size", ")", "&&", "isTrailSurrogate", "(", "source", ".", "charAt", "(", "result", "+", "1", ")", ")", ")", "{", "result", "++", ";", "}", "count", "--", ";", "result", "++", ";", "}", "if", "(", "count", "!=", "0", ")", "{", "throw", "new", "StringIndexOutOfBoundsException", "(", "offset32", ")", ";", "}", "return", "result", ";", "}" ]
Returns the UTF-16 offset that corresponds to a UTF-32 offset. Used for random access. See the {@link UTF16 class description} for notes on roundtripping. @param source The UTF-16 string buffer @param offset32 UTF-32 offset @return UTF-16 offset @exception IndexOutOfBoundsException If offset32 is out of bounds.
[ "Returns", "the", "UTF", "-", "16", "offset", "that", "corresponds", "to", "a", "UTF", "-", "32", "offset", ".", "Used", "for", "random", "access", ".", "See", "the", "{", "@link", "UTF16", "class", "description", "}", "for", "notes", "on", "roundtripping", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UTF16.java#L760-L780
msteiger/jxmapviewer2
jxmapviewer2/src/main/java/org/jxmapviewer/util/ShapeUtils.java
ShapeUtils.mergeClip
public static Shape mergeClip(Graphics g, Shape clip) { """ Sets the clip on a graphics object by merging a supplied clip with the existing one. The new clip will be an intersection of the old clip and the supplied clip. The old clip shape will be returned. This is useful for resetting the old clip after an operation is performed. @param g the graphics object to update @param clip a new clipping region to add to the graphics clip. @return the current clipping region of the supplied graphics object. This may return {@code null} if the current clip is {@code null}. @throws NullPointerException if any parameter is {@code null} """ Shape oldClip = g.getClip(); if (oldClip == null) { g.setClip(clip); return null; } Area area = new Area(oldClip); area.intersect(new Area(clip));// new Rectangle(0,0,width,height))); g.setClip(area); return oldClip; }
java
public static Shape mergeClip(Graphics g, Shape clip) { Shape oldClip = g.getClip(); if (oldClip == null) { g.setClip(clip); return null; } Area area = new Area(oldClip); area.intersect(new Area(clip));// new Rectangle(0,0,width,height))); g.setClip(area); return oldClip; }
[ "public", "static", "Shape", "mergeClip", "(", "Graphics", "g", ",", "Shape", "clip", ")", "{", "Shape", "oldClip", "=", "g", ".", "getClip", "(", ")", ";", "if", "(", "oldClip", "==", "null", ")", "{", "g", ".", "setClip", "(", "clip", ")", ";", "return", "null", ";", "}", "Area", "area", "=", "new", "Area", "(", "oldClip", ")", ";", "area", ".", "intersect", "(", "new", "Area", "(", "clip", ")", ")", ";", "// new Rectangle(0,0,width,height)));", "g", ".", "setClip", "(", "area", ")", ";", "return", "oldClip", ";", "}" ]
Sets the clip on a graphics object by merging a supplied clip with the existing one. The new clip will be an intersection of the old clip and the supplied clip. The old clip shape will be returned. This is useful for resetting the old clip after an operation is performed. @param g the graphics object to update @param clip a new clipping region to add to the graphics clip. @return the current clipping region of the supplied graphics object. This may return {@code null} if the current clip is {@code null}. @throws NullPointerException if any parameter is {@code null}
[ "Sets", "the", "clip", "on", "a", "graphics", "object", "by", "merging", "a", "supplied", "clip", "with", "the", "existing", "one", ".", "The", "new", "clip", "will", "be", "an", "intersection", "of", "the", "old", "clip", "and", "the", "supplied", "clip", ".", "The", "old", "clip", "shape", "will", "be", "returned", ".", "This", "is", "useful", "for", "resetting", "the", "old", "clip", "after", "an", "operation", "is", "performed", "." ]
train
https://github.com/msteiger/jxmapviewer2/blob/82639273b0aac983b6026fb90aa925c0cf596410/jxmapviewer2/src/main/java/org/jxmapviewer/util/ShapeUtils.java#L148-L158
jboss-integration/fuse-bxms-integ
switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/Manifest.java
Manifest.removeFromEnvironment
protected static <T extends Manifest> T removeFromEnvironment(Environment environment, Class<T> type) { """ Removes and returns the Manifest from the Environment. @param environment the Environment @param type the type of Manifest @return the Manifest """ String identifier = type.getName(); Object manifest = environment.get(identifier); if (manifest != null) { environment.set(identifier, null); } return type.cast(manifest); }
java
protected static <T extends Manifest> T removeFromEnvironment(Environment environment, Class<T> type) { String identifier = type.getName(); Object manifest = environment.get(identifier); if (manifest != null) { environment.set(identifier, null); } return type.cast(manifest); }
[ "protected", "static", "<", "T", "extends", "Manifest", ">", "T", "removeFromEnvironment", "(", "Environment", "environment", ",", "Class", "<", "T", ">", "type", ")", "{", "String", "identifier", "=", "type", ".", "getName", "(", ")", ";", "Object", "manifest", "=", "environment", ".", "get", "(", "identifier", ")", ";", "if", "(", "manifest", "!=", "null", ")", "{", "environment", ".", "set", "(", "identifier", ",", "null", ")", ";", "}", "return", "type", ".", "cast", "(", "manifest", ")", ";", "}" ]
Removes and returns the Manifest from the Environment. @param environment the Environment @param type the type of Manifest @return the Manifest
[ "Removes", "and", "returns", "the", "Manifest", "from", "the", "Environment", "." ]
train
https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/Manifest.java#L44-L51
litsec/swedish-eid-shibboleth-base
shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/controller/AbstractExternalAuthenticationController.java
AbstractExternalAuthenticationController.processExternalAuthentication
@RequestMapping(method = RequestMethod.GET) public final ModelAndView processExternalAuthentication(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ExternalAuthenticationException, IOException { """ Main entry point for the external authentication controller. The implementation starts a Shibboleth external authentication process and hands over the control to {@link #doExternalAuthentication(HttpServletRequest, HttpServletResponse, String, ProfileRequestContext)}. @param httpRequest the HTTP request @param httpResponse the HTTP response @return a model and view object @throws ExternalAuthenticationException for Shibboleth session errors @throws IOException for IO errors """ // Start the external authentication process ... // final String key = ExternalAuthentication.startExternalAuthentication(httpRequest); logger.debug("External authentication started. [key='{}',client-ip-address='{}']", key, httpRequest.getRemoteAddr()); final ProfileRequestContext<?, ?> profileRequestContext = ExternalAuthentication.getProfileRequestContext(key, httpRequest); // Store the authentication key in the HTTP session. // HttpSession session = httpRequest.getSession(); session.setAttribute(EXTAUTHN_KEY_ATTRIBUTE_NAME, key); // Initialize services and process the request try { this.processIsPassive(profileRequestContext); this.initializeServices(profileRequestContext); this.servicesProcessRequest(profileRequestContext); } catch (ExternalAutenticationErrorCodeException e) { this.error(httpRequest, httpResponse, e); return null; } // Hand over to implementation ... // return this.doExternalAuthentication(httpRequest, httpResponse, key, profileRequestContext); }
java
@RequestMapping(method = RequestMethod.GET) public final ModelAndView processExternalAuthentication(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ExternalAuthenticationException, IOException { // Start the external authentication process ... // final String key = ExternalAuthentication.startExternalAuthentication(httpRequest); logger.debug("External authentication started. [key='{}',client-ip-address='{}']", key, httpRequest.getRemoteAddr()); final ProfileRequestContext<?, ?> profileRequestContext = ExternalAuthentication.getProfileRequestContext(key, httpRequest); // Store the authentication key in the HTTP session. // HttpSession session = httpRequest.getSession(); session.setAttribute(EXTAUTHN_KEY_ATTRIBUTE_NAME, key); // Initialize services and process the request try { this.processIsPassive(profileRequestContext); this.initializeServices(profileRequestContext); this.servicesProcessRequest(profileRequestContext); } catch (ExternalAutenticationErrorCodeException e) { this.error(httpRequest, httpResponse, e); return null; } // Hand over to implementation ... // return this.doExternalAuthentication(httpRequest, httpResponse, key, profileRequestContext); }
[ "@", "RequestMapping", "(", "method", "=", "RequestMethod", ".", "GET", ")", "public", "final", "ModelAndView", "processExternalAuthentication", "(", "HttpServletRequest", "httpRequest", ",", "HttpServletResponse", "httpResponse", ")", "throws", "ExternalAuthenticationException", ",", "IOException", "{", "// Start the external authentication process ...", "//", "final", "String", "key", "=", "ExternalAuthentication", ".", "startExternalAuthentication", "(", "httpRequest", ")", ";", "logger", ".", "debug", "(", "\"External authentication started. [key='{}',client-ip-address='{}']\"", ",", "key", ",", "httpRequest", ".", "getRemoteAddr", "(", ")", ")", ";", "final", "ProfileRequestContext", "<", "?", ",", "?", ">", "profileRequestContext", "=", "ExternalAuthentication", ".", "getProfileRequestContext", "(", "key", ",", "httpRequest", ")", ";", "// Store the authentication key in the HTTP session.", "//", "HttpSession", "session", "=", "httpRequest", ".", "getSession", "(", ")", ";", "session", ".", "setAttribute", "(", "EXTAUTHN_KEY_ATTRIBUTE_NAME", ",", "key", ")", ";", "// Initialize services and process the request", "try", "{", "this", ".", "processIsPassive", "(", "profileRequestContext", ")", ";", "this", ".", "initializeServices", "(", "profileRequestContext", ")", ";", "this", ".", "servicesProcessRequest", "(", "profileRequestContext", ")", ";", "}", "catch", "(", "ExternalAutenticationErrorCodeException", "e", ")", "{", "this", ".", "error", "(", "httpRequest", ",", "httpResponse", ",", "e", ")", ";", "return", "null", ";", "}", "// Hand over to implementation ...", "//", "return", "this", ".", "doExternalAuthentication", "(", "httpRequest", ",", "httpResponse", ",", "key", ",", "profileRequestContext", ")", ";", "}" ]
Main entry point for the external authentication controller. The implementation starts a Shibboleth external authentication process and hands over the control to {@link #doExternalAuthentication(HttpServletRequest, HttpServletResponse, String, ProfileRequestContext)}. @param httpRequest the HTTP request @param httpResponse the HTTP response @return a model and view object @throws ExternalAuthenticationException for Shibboleth session errors @throws IOException for IO errors
[ "Main", "entry", "point", "for", "the", "external", "authentication", "controller", ".", "The", "implementation", "starts", "a", "Shibboleth", "external", "authentication", "process", "and", "hands", "over", "the", "control", "to", "{", "@link", "#doExternalAuthentication", "(", "HttpServletRequest", "HttpServletResponse", "String", "ProfileRequestContext", ")", "}", "." ]
train
https://github.com/litsec/swedish-eid-shibboleth-base/blob/aaaa467ff61f07d7dfa31627fb36851a37da6804/shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/controller/AbstractExternalAuthenticationController.java#L147-L177
joniles/mpxj
src/main/java/net/sf/mpxj/Task.java
Task.setBaselineFixedCost
public void setBaselineFixedCost(int baselineNumber, Number value) { """ Set a baseline value. @param baselineNumber baseline index (1-10) @param value baseline value """ set(selectField(TaskFieldLists.BASELINE_FIXED_COSTS, baselineNumber), value); }
java
public void setBaselineFixedCost(int baselineNumber, Number value) { set(selectField(TaskFieldLists.BASELINE_FIXED_COSTS, baselineNumber), value); }
[ "public", "void", "setBaselineFixedCost", "(", "int", "baselineNumber", ",", "Number", "value", ")", "{", "set", "(", "selectField", "(", "TaskFieldLists", ".", "BASELINE_FIXED_COSTS", ",", "baselineNumber", ")", ",", "value", ")", ";", "}" ]
Set a baseline value. @param baselineNumber baseline index (1-10) @param value baseline value
[ "Set", "a", "baseline", "value", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Task.java#L4504-L4507
hellosign/hellosign-java-sdk
src/main/java/com/hellosign/sdk/HelloSignClient.java
HelloSignClient.getFilesUrl
public FileUrlResponse getFilesUrl(String requestId) throws HelloSignException { """ Retrieves a URL for a file associated with a signature request. @param requestId String signature request ID @return {@link FileUrlResponse} @throws HelloSignException thrown if there's a problem processing the HTTP request or the JSON response. @see <a href="https://app.hellosign.com/api/reference#get_files">https://app.hellosign.com/api/reference#get_files</a> """ String url = BASE_URI + SIGNATURE_REQUEST_FILES_URI + "/" + requestId; HttpClient httpClient = this.httpClient.withAuth(auth).withGetParam(PARAM_GET_URL, "1").get(url); if (httpClient.getLastResponseCode() == 404) { throw new HelloSignException(String.format("Could not find request with id=%s", requestId)); } return new FileUrlResponse(httpClient.asJson()); }
java
public FileUrlResponse getFilesUrl(String requestId) throws HelloSignException { String url = BASE_URI + SIGNATURE_REQUEST_FILES_URI + "/" + requestId; HttpClient httpClient = this.httpClient.withAuth(auth).withGetParam(PARAM_GET_URL, "1").get(url); if (httpClient.getLastResponseCode() == 404) { throw new HelloSignException(String.format("Could not find request with id=%s", requestId)); } return new FileUrlResponse(httpClient.asJson()); }
[ "public", "FileUrlResponse", "getFilesUrl", "(", "String", "requestId", ")", "throws", "HelloSignException", "{", "String", "url", "=", "BASE_URI", "+", "SIGNATURE_REQUEST_FILES_URI", "+", "\"/\"", "+", "requestId", ";", "HttpClient", "httpClient", "=", "this", ".", "httpClient", ".", "withAuth", "(", "auth", ")", ".", "withGetParam", "(", "PARAM_GET_URL", ",", "\"1\"", ")", ".", "get", "(", "url", ")", ";", "if", "(", "httpClient", ".", "getLastResponseCode", "(", ")", "==", "404", ")", "{", "throw", "new", "HelloSignException", "(", "String", ".", "format", "(", "\"Could not find request with id=%s\"", ",", "requestId", ")", ")", ";", "}", "return", "new", "FileUrlResponse", "(", "httpClient", ".", "asJson", "(", ")", ")", ";", "}" ]
Retrieves a URL for a file associated with a signature request. @param requestId String signature request ID @return {@link FileUrlResponse} @throws HelloSignException thrown if there's a problem processing the HTTP request or the JSON response. @see <a href="https://app.hellosign.com/api/reference#get_files">https://app.hellosign.com/api/reference#get_files</a>
[ "Retrieves", "a", "URL", "for", "a", "file", "associated", "with", "a", "signature", "request", "." ]
train
https://github.com/hellosign/hellosign-java-sdk/blob/08fa7aeb3b0c68ddb6c7ea797d114d55d36d36b1/src/main/java/com/hellosign/sdk/HelloSignClient.java#L789-L799
anotheria/moskito
moskito-aop/src/main/java/net/anotheria/moskito/aop/aspect/MonitoringAspect.java
MonitoringAspect.doProfilingMethod
@Around (value = "execution(@(@net.anotheria.moskito.aop.annotation.Monitor *) * *(..)) && !@annotation(net.anotheria.moskito.aop.annotation.DontMonitor)") public Object doProfilingMethod(final ProceedingJoinPoint pjp) throws Throwable { """ Special method profiling entry-point, which allow to fetch {@link Monitor} from one lvl up of method annotation. Pattern will pre-select 2-nd lvl annotation on method scope. @param pjp {@link ProceedingJoinPoint} @return call result @throws Throwable in case of error during {@link ProceedingJoinPoint#proceed()} """ return doProfilingMethod(pjp, resolveAnnotation(pjp)); }
java
@Around (value = "execution(@(@net.anotheria.moskito.aop.annotation.Monitor *) * *(..)) && !@annotation(net.anotheria.moskito.aop.annotation.DontMonitor)") public Object doProfilingMethod(final ProceedingJoinPoint pjp) throws Throwable { return doProfilingMethod(pjp, resolveAnnotation(pjp)); }
[ "@", "Around", "(", "value", "=", "\"execution(@(@net.anotheria.moskito.aop.annotation.Monitor *) * *(..)) && !@annotation(net.anotheria.moskito.aop.annotation.DontMonitor)\"", ")", "public", "Object", "doProfilingMethod", "(", "final", "ProceedingJoinPoint", "pjp", ")", "throws", "Throwable", "{", "return", "doProfilingMethod", "(", "pjp", ",", "resolveAnnotation", "(", "pjp", ")", ")", ";", "}" ]
Special method profiling entry-point, which allow to fetch {@link Monitor} from one lvl up of method annotation. Pattern will pre-select 2-nd lvl annotation on method scope. @param pjp {@link ProceedingJoinPoint} @return call result @throws Throwable in case of error during {@link ProceedingJoinPoint#proceed()}
[ "Special", "method", "profiling", "entry", "-", "point", "which", "allow", "to", "fetch", "{", "@link", "Monitor", "}", "from", "one", "lvl", "up", "of", "method", "annotation", ".", "Pattern", "will", "pre", "-", "select", "2", "-", "nd", "lvl", "annotation", "on", "method", "scope", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-aop/src/main/java/net/anotheria/moskito/aop/aspect/MonitoringAspect.java#L67-L70
code4everything/util
src/main/java/com/zhazhapan/util/Checker.java
Checker.isIn
public static <T> boolean isIn(T t, T... ts) { """ 检查对象是否在集合中 @param <T> 类型 @param t 对象 @param ts 集合 @return 是否存在 @since 1.0.8 """ if (isNotNull(t) && isNotNull(ts)) { for (Object object : ts) { if (t.equals(object)) { return true; } } } return false; }
java
public static <T> boolean isIn(T t, T... ts) { if (isNotNull(t) && isNotNull(ts)) { for (Object object : ts) { if (t.equals(object)) { return true; } } } return false; }
[ "public", "static", "<", "T", ">", "boolean", "isIn", "(", "T", "t", ",", "T", "...", "ts", ")", "{", "if", "(", "isNotNull", "(", "t", ")", "&&", "isNotNull", "(", "ts", ")", ")", "{", "for", "(", "Object", "object", ":", "ts", ")", "{", "if", "(", "t", ".", "equals", "(", "object", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
检查对象是否在集合中 @param <T> 类型 @param t 对象 @param ts 集合 @return 是否存在 @since 1.0.8
[ "检查对象是否在集合中" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/Checker.java#L656-L665
square/okhttp
okhttp/src/main/java/okhttp3/internal/Util.java
Util.skipTrailingAsciiWhitespace
public static int skipTrailingAsciiWhitespace(String input, int pos, int limit) { """ Decrements {@code limit} until {@code input[limit - 1]} is not ASCII whitespace. Stops at {@code pos}. """ for (int i = limit - 1; i >= pos; i--) { switch (input.charAt(i)) { case '\t': case '\n': case '\f': case '\r': case ' ': continue; default: return i + 1; } } return pos; }
java
public static int skipTrailingAsciiWhitespace(String input, int pos, int limit) { for (int i = limit - 1; i >= pos; i--) { switch (input.charAt(i)) { case '\t': case '\n': case '\f': case '\r': case ' ': continue; default: return i + 1; } } return pos; }
[ "public", "static", "int", "skipTrailingAsciiWhitespace", "(", "String", "input", ",", "int", "pos", ",", "int", "limit", ")", "{", "for", "(", "int", "i", "=", "limit", "-", "1", ";", "i", ">=", "pos", ";", "i", "--", ")", "{", "switch", "(", "input", ".", "charAt", "(", "i", ")", ")", "{", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "continue", ";", "default", ":", "return", "i", "+", "1", ";", "}", "}", "return", "pos", ";", "}" ]
Decrements {@code limit} until {@code input[limit - 1]} is not ASCII whitespace. Stops at {@code pos}.
[ "Decrements", "{" ]
train
https://github.com/square/okhttp/blob/a8c65a822dd6cadd2de7d115bf94adf312e67868/okhttp/src/main/java/okhttp3/internal/Util.java#L316-L330
alkacon/opencms-core
src/org/opencms/ade/containerpage/CmsDetailOnlyContainerPageBuilder.java
CmsDetailOnlyContainerPageBuilder.buildContainerElementBean
private CmsContainerElementBean buildContainerElementBean(ContainerInfo cnt, CmsResource resource) { """ Builds the container element bean for a resource.<p> @param cnt the container for the element resource @param resource the resource @return the container element bean """ I_CmsFormatterBean formatter = m_config.getFormatters(m_cms, resource).getDefaultFormatter( cnt.getEffectiveType(), cnt.getEffectiveWidth()); CmsUUID formatterId = formatter.getJspStructureId(); CmsContainerElementBean elementBean = new CmsContainerElementBean( resource.getStructureId(), formatterId, new HashMap<String, String>(), false); return elementBean; }
java
private CmsContainerElementBean buildContainerElementBean(ContainerInfo cnt, CmsResource resource) { I_CmsFormatterBean formatter = m_config.getFormatters(m_cms, resource).getDefaultFormatter( cnt.getEffectiveType(), cnt.getEffectiveWidth()); CmsUUID formatterId = formatter.getJspStructureId(); CmsContainerElementBean elementBean = new CmsContainerElementBean( resource.getStructureId(), formatterId, new HashMap<String, String>(), false); return elementBean; }
[ "private", "CmsContainerElementBean", "buildContainerElementBean", "(", "ContainerInfo", "cnt", ",", "CmsResource", "resource", ")", "{", "I_CmsFormatterBean", "formatter", "=", "m_config", ".", "getFormatters", "(", "m_cms", ",", "resource", ")", ".", "getDefaultFormatter", "(", "cnt", ".", "getEffectiveType", "(", ")", ",", "cnt", ".", "getEffectiveWidth", "(", ")", ")", ";", "CmsUUID", "formatterId", "=", "formatter", ".", "getJspStructureId", "(", ")", ";", "CmsContainerElementBean", "elementBean", "=", "new", "CmsContainerElementBean", "(", "resource", ".", "getStructureId", "(", ")", ",", "formatterId", ",", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ",", "false", ")", ";", "return", "elementBean", ";", "}" ]
Builds the container element bean for a resource.<p> @param cnt the container for the element resource @param resource the resource @return the container element bean
[ "Builds", "the", "container", "element", "bean", "for", "a", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/containerpage/CmsDetailOnlyContainerPageBuilder.java#L282-L294
grpc/grpc-java
examples/src/main/java/io/grpc/examples/advanced/JsonMarshaller.java
JsonMarshaller.jsonMarshaller
public static <T extends Message> Marshaller<T> jsonMarshaller( final T defaultInstance, final Parser parser, final Printer printer) { """ Create a {@code Marshaller} for json protos of the same type as {@code defaultInstance}. <p>This is an unstable API and has not been optimized yet for performance. """ final Charset charset = Charset.forName("UTF-8"); return new Marshaller<T>() { @Override public InputStream stream(T value) { try { return new ByteArrayInputStream(printer.print(value).getBytes(charset)); } catch (InvalidProtocolBufferException e) { throw Status.INTERNAL .withCause(e) .withDescription("Unable to print json proto") .asRuntimeException(); } } @SuppressWarnings("unchecked") @Override public T parse(InputStream stream) { Builder builder = defaultInstance.newBuilderForType(); Reader reader = new InputStreamReader(stream, charset); T proto; try { parser.merge(reader, builder); proto = (T) builder.build(); reader.close(); } catch (InvalidProtocolBufferException e) { throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence") .withCause(e).asRuntimeException(); } catch (IOException e) { // Same for now, might be unavailable throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence") .withCause(e).asRuntimeException(); } return proto; } }; }
java
public static <T extends Message> Marshaller<T> jsonMarshaller( final T defaultInstance, final Parser parser, final Printer printer) { final Charset charset = Charset.forName("UTF-8"); return new Marshaller<T>() { @Override public InputStream stream(T value) { try { return new ByteArrayInputStream(printer.print(value).getBytes(charset)); } catch (InvalidProtocolBufferException e) { throw Status.INTERNAL .withCause(e) .withDescription("Unable to print json proto") .asRuntimeException(); } } @SuppressWarnings("unchecked") @Override public T parse(InputStream stream) { Builder builder = defaultInstance.newBuilderForType(); Reader reader = new InputStreamReader(stream, charset); T proto; try { parser.merge(reader, builder); proto = (T) builder.build(); reader.close(); } catch (InvalidProtocolBufferException e) { throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence") .withCause(e).asRuntimeException(); } catch (IOException e) { // Same for now, might be unavailable throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence") .withCause(e).asRuntimeException(); } return proto; } }; }
[ "public", "static", "<", "T", "extends", "Message", ">", "Marshaller", "<", "T", ">", "jsonMarshaller", "(", "final", "T", "defaultInstance", ",", "final", "Parser", "parser", ",", "final", "Printer", "printer", ")", "{", "final", "Charset", "charset", "=", "Charset", ".", "forName", "(", "\"UTF-8\"", ")", ";", "return", "new", "Marshaller", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "InputStream", "stream", "(", "T", "value", ")", "{", "try", "{", "return", "new", "ByteArrayInputStream", "(", "printer", ".", "print", "(", "value", ")", ".", "getBytes", "(", "charset", ")", ")", ";", "}", "catch", "(", "InvalidProtocolBufferException", "e", ")", "{", "throw", "Status", ".", "INTERNAL", ".", "withCause", "(", "e", ")", ".", "withDescription", "(", "\"Unable to print json proto\"", ")", ".", "asRuntimeException", "(", ")", ";", "}", "}", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Override", "public", "T", "parse", "(", "InputStream", "stream", ")", "{", "Builder", "builder", "=", "defaultInstance", ".", "newBuilderForType", "(", ")", ";", "Reader", "reader", "=", "new", "InputStreamReader", "(", "stream", ",", "charset", ")", ";", "T", "proto", ";", "try", "{", "parser", ".", "merge", "(", "reader", ",", "builder", ")", ";", "proto", "=", "(", "T", ")", "builder", ".", "build", "(", ")", ";", "reader", ".", "close", "(", ")", ";", "}", "catch", "(", "InvalidProtocolBufferException", "e", ")", "{", "throw", "Status", ".", "INTERNAL", ".", "withDescription", "(", "\"Invalid protobuf byte sequence\"", ")", ".", "withCause", "(", "e", ")", ".", "asRuntimeException", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// Same for now, might be unavailable", "throw", "Status", ".", "INTERNAL", ".", "withDescription", "(", "\"Invalid protobuf byte sequence\"", ")", ".", "withCause", "(", "e", ")", ".", "asRuntimeException", "(", ")", ";", "}", "return", "proto", ";", "}", "}", ";", "}" ]
Create a {@code Marshaller} for json protos of the same type as {@code defaultInstance}. <p>This is an unstable API and has not been optimized yet for performance.
[ "Create", "a", "{", "@code", "Marshaller", "}", "for", "json", "protos", "of", "the", "same", "type", "as", "{", "@code", "defaultInstance", "}", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/examples/src/main/java/io/grpc/examples/advanced/JsonMarshaller.java#L58-L97
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java
KeyVaultClientCustomImpl.listCertificatesAsync
public ServiceFuture<List<CertificateItem>> listCertificatesAsync(final String vaultBaseUrl, final ListOperationCallback<CertificateItem> serviceCallback) { """ List certificates in the specified vault. @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net @param serviceCallback the async ServiceCallback to handle successful and failed responses. @return the {@link ServiceFuture} object """ return getCertificatesAsync(vaultBaseUrl, serviceCallback); }
java
public ServiceFuture<List<CertificateItem>> listCertificatesAsync(final String vaultBaseUrl, final ListOperationCallback<CertificateItem> serviceCallback) { return getCertificatesAsync(vaultBaseUrl, serviceCallback); }
[ "public", "ServiceFuture", "<", "List", "<", "CertificateItem", ">", ">", "listCertificatesAsync", "(", "final", "String", "vaultBaseUrl", ",", "final", "ListOperationCallback", "<", "CertificateItem", ">", "serviceCallback", ")", "{", "return", "getCertificatesAsync", "(", "vaultBaseUrl", ",", "serviceCallback", ")", ";", "}" ]
List certificates in the specified vault. @param vaultBaseUrl The vault name, e.g. https://myvault.vault.azure.net @param serviceCallback the async ServiceCallback to handle successful and failed responses. @return the {@link ServiceFuture} object
[ "List", "certificates", "in", "the", "specified", "vault", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java#L1308-L1311
ngageoint/geopackage-java
src/main/java/mil/nga/geopackage/property/GeoPackageJavaProperties.java
GeoPackageJavaProperties.getFloatProperty
public static Float getFloatProperty(String key, boolean required) { """ Get a float by key @param key key @param required required flag @return property value """ Float value = null; String stringValue = getProperty(key, required); if (stringValue != null) { value = Float.valueOf(stringValue); } return value; }
java
public static Float getFloatProperty(String key, boolean required) { Float value = null; String stringValue = getProperty(key, required); if (stringValue != null) { value = Float.valueOf(stringValue); } return value; }
[ "public", "static", "Float", "getFloatProperty", "(", "String", "key", ",", "boolean", "required", ")", "{", "Float", "value", "=", "null", ";", "String", "stringValue", "=", "getProperty", "(", "key", ",", "required", ")", ";", "if", "(", "stringValue", "!=", "null", ")", "{", "value", "=", "Float", ".", "valueOf", "(", "stringValue", ")", ";", "}", "return", "value", ";", "}" ]
Get a float by key @param key key @param required required flag @return property value
[ "Get", "a", "float", "by", "key" ]
train
https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/property/GeoPackageJavaProperties.java#L169-L176
GCRC/nunaliit
nunaliit2-dbSec/src/main/java/ca/carleton/gcrc/dbSec/impl/ColumnDataUtils.java
ColumnDataUtils.obtainNextIncrementInteger
static public int obtainNextIncrementInteger(Connection connection, ColumnData autoIncrementIntegerColumn) throws Exception { """ Performs a database query to find the next integer in the sequence reserved for the given column. @param autoIncrementIntegerColumn Column data where a new integer is required @return The next integer in sequence @throws Exception """ try { String sqlQuery = "SELECT nextval(?);"; // Create SQL command PreparedStatement pstmt = null; { pstmt = connection.prepareStatement(sqlQuery); // Populate prepared statement pstmt.setString(1, autoIncrementIntegerColumn.getAutoIncrementSequence()); } if( pstmt.execute() ) { ResultSet rs = pstmt.getResultSet(); if( rs.next() ) { int nextValue = rs.getInt(1); return nextValue; } else { throw new Exception("Empty result returned by SQL: "+sqlQuery); } } else { throw new Exception("No result returned by SQL: "+sqlQuery); } } catch( Exception e ) { throw new Exception("Error while attempting to get a auto increment integer value for: "+ autoIncrementIntegerColumn.getColumnName()+ " ("+autoIncrementIntegerColumn.getAutoIncrementSequence()+")",e); } }
java
static public int obtainNextIncrementInteger(Connection connection, ColumnData autoIncrementIntegerColumn) throws Exception { try { String sqlQuery = "SELECT nextval(?);"; // Create SQL command PreparedStatement pstmt = null; { pstmt = connection.prepareStatement(sqlQuery); // Populate prepared statement pstmt.setString(1, autoIncrementIntegerColumn.getAutoIncrementSequence()); } if( pstmt.execute() ) { ResultSet rs = pstmt.getResultSet(); if( rs.next() ) { int nextValue = rs.getInt(1); return nextValue; } else { throw new Exception("Empty result returned by SQL: "+sqlQuery); } } else { throw new Exception("No result returned by SQL: "+sqlQuery); } } catch( Exception e ) { throw new Exception("Error while attempting to get a auto increment integer value for: "+ autoIncrementIntegerColumn.getColumnName()+ " ("+autoIncrementIntegerColumn.getAutoIncrementSequence()+")",e); } }
[ "static", "public", "int", "obtainNextIncrementInteger", "(", "Connection", "connection", ",", "ColumnData", "autoIncrementIntegerColumn", ")", "throws", "Exception", "{", "try", "{", "String", "sqlQuery", "=", "\"SELECT nextval(?);\"", ";", "// Create SQL command", "PreparedStatement", "pstmt", "=", "null", ";", "{", "pstmt", "=", "connection", ".", "prepareStatement", "(", "sqlQuery", ")", ";", "// Populate prepared statement", "pstmt", ".", "setString", "(", "1", ",", "autoIncrementIntegerColumn", ".", "getAutoIncrementSequence", "(", ")", ")", ";", "}", "if", "(", "pstmt", ".", "execute", "(", ")", ")", "{", "ResultSet", "rs", "=", "pstmt", ".", "getResultSet", "(", ")", ";", "if", "(", "rs", ".", "next", "(", ")", ")", "{", "int", "nextValue", "=", "rs", ".", "getInt", "(", "1", ")", ";", "return", "nextValue", ";", "}", "else", "{", "throw", "new", "Exception", "(", "\"Empty result returned by SQL: \"", "+", "sqlQuery", ")", ";", "}", "}", "else", "{", "throw", "new", "Exception", "(", "\"No result returned by SQL: \"", "+", "sqlQuery", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "Exception", "(", "\"Error while attempting to get a auto increment integer value for: \"", "+", "autoIncrementIntegerColumn", ".", "getColumnName", "(", ")", "+", "\" (\"", "+", "autoIncrementIntegerColumn", ".", "getAutoIncrementSequence", "(", ")", "+", "\")\"", ",", "e", ")", ";", "}", "}" ]
Performs a database query to find the next integer in the sequence reserved for the given column. @param autoIncrementIntegerColumn Column data where a new integer is required @return The next integer in sequence @throws Exception
[ "Performs", "a", "database", "query", "to", "find", "the", "next", "integer", "in", "the", "sequence", "reserved", "for", "the", "given", "column", "." ]
train
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-dbSec/src/main/java/ca/carleton/gcrc/dbSec/impl/ColumnDataUtils.java#L355-L386