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
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/system_settings.java
system_settings.update
public static system_settings update(nitro_service client, system_settings resource) throws Exception { """ <pre> Use this operation to modify SDX system settings. </pre> """ resource.validate("modify"); return ((system_settings[]) resource.update_resource(client))[0]; }
java
public static system_settings update(nitro_service client, system_settings resource) throws Exception { resource.validate("modify"); return ((system_settings[]) resource.update_resource(client))[0]; }
[ "public", "static", "system_settings", "update", "(", "nitro_service", "client", ",", "system_settings", "resource", ")", "throws", "Exception", "{", "resource", ".", "validate", "(", "\"modify\"", ")", ";", "return", "(", "(", "system_settings", "[", "]", ")", "resource", ".", "update_resource", "(", "client", ")", ")", "[", "0", "]", ";", "}" ]
<pre> Use this operation to modify SDX system settings. </pre>
[ "<pre", ">", "Use", "this", "operation", "to", "modify", "SDX", "system", "settings", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/system_settings.java#L221-L225
Mozu/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/urls/platform/ReferenceDataUrl.java
ReferenceDataUrl.getUnitsOfMeasureUrl
public static MozuUrl getUnitsOfMeasureUrl(String filter, String responseFields) { """ Get Resource Url for GetUnitsOfMeasure @param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @return String Resource Url """ UrlFormatter formatter = new UrlFormatter("/api/platform/reference/unitsofmeasure?filter={filter}&responseFields={responseFields}"); formatter.formatUrl("filter", filter); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.HOME_POD) ; }
java
public static MozuUrl getUnitsOfMeasureUrl(String filter, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/platform/reference/unitsofmeasure?filter={filter}&responseFields={responseFields}"); formatter.formatUrl("filter", filter); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.HOME_POD) ; }
[ "public", "static", "MozuUrl", "getUnitsOfMeasureUrl", "(", "String", "filter", ",", "String", "responseFields", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/platform/reference/unitsofmeasure?filter={filter}&responseFields={responseFields}\"", ")", ";", "formatter", ".", "formatUrl", "(", "\"filter\"", ",", "filter", ")", ";", "formatter", ".", "formatUrl", "(", "\"responseFields\"", ",", "responseFields", ")", ";", "return", "new", "MozuUrl", "(", "formatter", ".", "getResourceUrl", "(", ")", ",", "MozuUrl", ".", "UrlLocation", ".", "HOME_POD", ")", ";", "}" ]
Get Resource Url for GetUnitsOfMeasure @param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetUnitsOfMeasure" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/platform/ReferenceDataUrl.java#L174-L180
baratine/baratine
kraken/src/main/java/com/caucho/v5/kraken/table/KrakenImpl.java
KrakenImpl.findStream
private void findStream(QueryKraken query, Object []args, ResultStream<Cursor> result) { """ Query implementation for multiple result with the parsed query. """ try { TableKraken table = query.table(); TableKelp tableKelp = table.getTableKelp(); TablePod tablePod = table.getTablePod(); if (query.isStaticNode()) { RowCursor cursor = tableKelp.cursor(); query.fillKey(cursor, args); int hash = query.calculateHash(cursor); //ShardPod node = tablePod.getPodNode(hash); if (tablePod.getNode(hash).isSelfCopy() || true) { query.findStream(result, args); return; } else { //tablePod.get(cursor.getKey(), new FindGetResult(result, query, args)); result.ok(); return; } } query.findStream(result, args); } catch (Exception e) { result.fail(e); } }
java
private void findStream(QueryKraken query, Object []args, ResultStream<Cursor> result) { try { TableKraken table = query.table(); TableKelp tableKelp = table.getTableKelp(); TablePod tablePod = table.getTablePod(); if (query.isStaticNode()) { RowCursor cursor = tableKelp.cursor(); query.fillKey(cursor, args); int hash = query.calculateHash(cursor); //ShardPod node = tablePod.getPodNode(hash); if (tablePod.getNode(hash).isSelfCopy() || true) { query.findStream(result, args); return; } else { //tablePod.get(cursor.getKey(), new FindGetResult(result, query, args)); result.ok(); return; } } query.findStream(result, args); } catch (Exception e) { result.fail(e); } }
[ "private", "void", "findStream", "(", "QueryKraken", "query", ",", "Object", "[", "]", "args", ",", "ResultStream", "<", "Cursor", ">", "result", ")", "{", "try", "{", "TableKraken", "table", "=", "query", ".", "table", "(", ")", ";", "TableKelp", "tableKelp", "=", "table", ".", "getTableKelp", "(", ")", ";", "TablePod", "tablePod", "=", "table", ".", "getTablePod", "(", ")", ";", "if", "(", "query", ".", "isStaticNode", "(", ")", ")", "{", "RowCursor", "cursor", "=", "tableKelp", ".", "cursor", "(", ")", ";", "query", ".", "fillKey", "(", "cursor", ",", "args", ")", ";", "int", "hash", "=", "query", ".", "calculateHash", "(", "cursor", ")", ";", "//ShardPod node = tablePod.getPodNode(hash);", "if", "(", "tablePod", ".", "getNode", "(", "hash", ")", ".", "isSelfCopy", "(", ")", "||", "true", ")", "{", "query", ".", "findStream", "(", "result", ",", "args", ")", ";", "return", ";", "}", "else", "{", "//tablePod.get(cursor.getKey(), new FindGetResult(result, query, args));", "result", ".", "ok", "(", ")", ";", "return", ";", "}", "}", "query", ".", "findStream", "(", "result", ",", "args", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "result", ".", "fail", "(", "e", ")", ";", "}", "}" ]
Query implementation for multiple result with the parsed query.
[ "Query", "implementation", "for", "multiple", "result", "with", "the", "parsed", "query", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/kraken/src/main/java/com/caucho/v5/kraken/table/KrakenImpl.java#L542-L575
Azure/azure-sdk-for-java
postgresql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/postgresql/v2017_12_01/implementation/VirtualNetworkRulesInner.java
VirtualNetworkRulesInner.createOrUpdate
public VirtualNetworkRuleInner createOrUpdate(String resourceGroupName, String serverName, String virtualNetworkRuleName, VirtualNetworkRuleInner parameters) { """ Creates or updates an existing virtual network rule. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param virtualNetworkRuleName The name of the virtual network rule. @param parameters The requested virtual Network Rule Resource state. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VirtualNetworkRuleInner object if successful. """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, virtualNetworkRuleName, parameters).toBlocking().last().body(); }
java
public VirtualNetworkRuleInner createOrUpdate(String resourceGroupName, String serverName, String virtualNetworkRuleName, VirtualNetworkRuleInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, virtualNetworkRuleName, parameters).toBlocking().last().body(); }
[ "public", "VirtualNetworkRuleInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "virtualNetworkRuleName", ",", "VirtualNetworkRuleInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "virtualNetworkRuleName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates an existing virtual network rule. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param virtualNetworkRuleName The name of the virtual network rule. @param parameters The requested virtual Network Rule Resource state. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VirtualNetworkRuleInner object if successful.
[ "Creates", "or", "updates", "an", "existing", "virtual", "network", "rule", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/postgresql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/postgresql/v2017_12_01/implementation/VirtualNetworkRulesInner.java#L199-L201
geomajas/geomajas-project-client-gwt2
common-gwt/command/src/main/java/org/geomajas/gwt/server/mvc/GeomajasController.java
GeomajasController.handleRequest
@RequestMapping("/geomajasService") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { """ Implements Spring Controller interface method. <p/> Call {@link RemoteServiceServlet#doPost(HttpServletRequest, HttpServletResponse)} method and return null. @param request current HTTP request @param response current HTTP response @return a ModelAndView to render, or null if handled directly @throws Exception in case of errors """ doPost(request, response); return null; }
java
@RequestMapping("/geomajasService") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { doPost(request, response); return null; }
[ "@", "RequestMapping", "(", "\"/geomajasService\"", ")", "public", "ModelAndView", "handleRequest", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "Exception", "{", "doPost", "(", "request", ",", "response", ")", ";", "return", "null", ";", "}" ]
Implements Spring Controller interface method. <p/> Call {@link RemoteServiceServlet#doPost(HttpServletRequest, HttpServletResponse)} method and return null. @param request current HTTP request @param response current HTTP response @return a ModelAndView to render, or null if handled directly @throws Exception in case of errors
[ "Implements", "Spring", "Controller", "interface", "method", ".", "<p", "/", ">", "Call", "{", "@link", "RemoteServiceServlet#doPost", "(", "HttpServletRequest", "HttpServletResponse", ")", "}", "method", "and", "return", "null", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/common-gwt/command/src/main/java/org/geomajas/gwt/server/mvc/GeomajasController.java#L67-L71
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/PropsBlock.java
PropsBlock.populateMap
private void populateMap(byte[] data, Integer previousItemOffset, Integer previousItemKey, Integer itemOffset) { """ Method used to extract data from the block of properties and insert the key value pair into a map. @param data block of property data @param previousItemOffset previous offset @param previousItemKey item key @param itemOffset current item offset """ if (previousItemOffset != null) { int itemSize = itemOffset.intValue() - previousItemOffset.intValue(); byte[] itemData = new byte[itemSize]; System.arraycopy(data, previousItemOffset.intValue(), itemData, 0, itemSize); m_map.put(previousItemKey, itemData); } }
java
private void populateMap(byte[] data, Integer previousItemOffset, Integer previousItemKey, Integer itemOffset) { if (previousItemOffset != null) { int itemSize = itemOffset.intValue() - previousItemOffset.intValue(); byte[] itemData = new byte[itemSize]; System.arraycopy(data, previousItemOffset.intValue(), itemData, 0, itemSize); m_map.put(previousItemKey, itemData); } }
[ "private", "void", "populateMap", "(", "byte", "[", "]", "data", ",", "Integer", "previousItemOffset", ",", "Integer", "previousItemKey", ",", "Integer", "itemOffset", ")", "{", "if", "(", "previousItemOffset", "!=", "null", ")", "{", "int", "itemSize", "=", "itemOffset", ".", "intValue", "(", ")", "-", "previousItemOffset", ".", "intValue", "(", ")", ";", "byte", "[", "]", "itemData", "=", "new", "byte", "[", "itemSize", "]", ";", "System", ".", "arraycopy", "(", "data", ",", "previousItemOffset", ".", "intValue", "(", ")", ",", "itemData", ",", "0", ",", "itemSize", ")", ";", "m_map", ".", "put", "(", "previousItemKey", ",", "itemData", ")", ";", "}", "}" ]
Method used to extract data from the block of properties and insert the key value pair into a map. @param data block of property data @param previousItemOffset previous offset @param previousItemKey item key @param itemOffset current item offset
[ "Method", "used", "to", "extract", "data", "from", "the", "block", "of", "properties", "and", "insert", "the", "key", "value", "pair", "into", "a", "map", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/PropsBlock.java#L83-L92
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalBigDecimal
public BigDecimal getInternalBigDecimal(ColumnInformation columnInfo) { """ Get BigDecimal from raw text format. @param columnInfo column information @return BigDecimal value """ if (lastValueWasNull()) { return null; } if (columnInfo.getColumnType() == ColumnType.BIT) { return BigDecimal.valueOf(parseBit()); } return new BigDecimal(new String(buf, pos, length, StandardCharsets.UTF_8)); }
java
public BigDecimal getInternalBigDecimal(ColumnInformation columnInfo) { if (lastValueWasNull()) { return null; } if (columnInfo.getColumnType() == ColumnType.BIT) { return BigDecimal.valueOf(parseBit()); } return new BigDecimal(new String(buf, pos, length, StandardCharsets.UTF_8)); }
[ "public", "BigDecimal", "getInternalBigDecimal", "(", "ColumnInformation", "columnInfo", ")", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "columnInfo", ".", "getColumnType", "(", ")", "==", "ColumnType", ".", "BIT", ")", "{", "return", "BigDecimal", ".", "valueOf", "(", "parseBit", "(", ")", ")", ";", "}", "return", "new", "BigDecimal", "(", "new", "String", "(", "buf", ",", "pos", ",", "length", ",", "StandardCharsets", ".", "UTF_8", ")", ")", ";", "}" ]
Get BigDecimal from raw text format. @param columnInfo column information @return BigDecimal value
[ "Get", "BigDecimal", "from", "raw", "text", "format", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L442-L451
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/stats/StatsInterface.java
StatsInterface.getCollectionReferrers
public ReferrerList getCollectionReferrers(Date date, String domain, String collectionId, int perPage, int page) throws FlickrException { """ Get a list of referrers from a given domain to a collection. @param date (Required) Stats will be returned for this date. A day according to Flickr Stats starts at midnight GMT for all users, and timestamps will automatically be rounded down to the start of the day. @param domain (Required) The domain to return referrers for. This should be a hostname (eg: "flickr.com") with no protocol or pathname. @param collectionId (Optional) The id of the collection to get stats for. If not provided, stats for all collections will be returned. @param perPage (Optional) Number of domains to return per page. If this argument is omitted, it defaults to 25. The maximum allowed value is 100. @param page (Optional) The page of results to return. If this argument is omitted, it defaults to 1. @see "http://www.flickr.com/services/api/flickr.stats.getCollectionReferrers.html" """ return getReferrers(METHOD_GET_COLLECTION_REFERRERS, domain, "collection_id", collectionId, date, perPage, page); }
java
public ReferrerList getCollectionReferrers(Date date, String domain, String collectionId, int perPage, int page) throws FlickrException { return getReferrers(METHOD_GET_COLLECTION_REFERRERS, domain, "collection_id", collectionId, date, perPage, page); }
[ "public", "ReferrerList", "getCollectionReferrers", "(", "Date", "date", ",", "String", "domain", ",", "String", "collectionId", ",", "int", "perPage", ",", "int", "page", ")", "throws", "FlickrException", "{", "return", "getReferrers", "(", "METHOD_GET_COLLECTION_REFERRERS", ",", "domain", ",", "\"collection_id\"", ",", "collectionId", ",", "date", ",", "perPage", ",", "page", ")", ";", "}" ]
Get a list of referrers from a given domain to a collection. @param date (Required) Stats will be returned for this date. A day according to Flickr Stats starts at midnight GMT for all users, and timestamps will automatically be rounded down to the start of the day. @param domain (Required) The domain to return referrers for. This should be a hostname (eg: "flickr.com") with no protocol or pathname. @param collectionId (Optional) The id of the collection to get stats for. If not provided, stats for all collections will be returned. @param perPage (Optional) Number of domains to return per page. If this argument is omitted, it defaults to 25. The maximum allowed value is 100. @param page (Optional) The page of results to return. If this argument is omitted, it defaults to 1. @see "http://www.flickr.com/services/api/flickr.stats.getCollectionReferrers.html"
[ "Get", "a", "list", "of", "referrers", "from", "a", "given", "domain", "to", "a", "collection", "." ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/stats/StatsInterface.java#L115-L117
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/MPP9Reader.java
MPP9Reader.processViewData
private void processViewData() throws IOException { """ This method extracts view data from the MPP file. @throws IOException """ DirectoryEntry dir = (DirectoryEntry) m_viewDir.getEntry("CV_iew"); VarMeta viewVarMeta = new VarMeta9(new DocumentInputStream(((DocumentEntry) dir.getEntry("VarMeta")))); Var2Data viewVarData = new Var2Data(viewVarMeta, new DocumentInputStream(((DocumentEntry) dir.getEntry("Var2Data")))); FixedMeta fixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) dir.getEntry("FixedMeta"))), 10); FixedData fixedData = new FixedData(122, m_inputStreamFactory.getInstance(dir, "FixedData")); int items = fixedMeta.getAdjustedItemCount(); View view; ViewFactory factory = new ViewFactory9(); int lastOffset = -1; for (int loop = 0; loop < items; loop++) { byte[] fm = fixedMeta.getByteArrayValue(loop); int offset = MPPUtility.getShort(fm, 4); if (offset > lastOffset) { byte[] fd = fixedData.getByteArrayValue(fixedData.getIndexFromOffset(offset)); if (fd != null) { view = factory.createView(m_file, fm, fd, viewVarData, m_fontBases); m_file.getViews().add(view); //System.out.print(view); } lastOffset = offset; } } }
java
private void processViewData() throws IOException { DirectoryEntry dir = (DirectoryEntry) m_viewDir.getEntry("CV_iew"); VarMeta viewVarMeta = new VarMeta9(new DocumentInputStream(((DocumentEntry) dir.getEntry("VarMeta")))); Var2Data viewVarData = new Var2Data(viewVarMeta, new DocumentInputStream(((DocumentEntry) dir.getEntry("Var2Data")))); FixedMeta fixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) dir.getEntry("FixedMeta"))), 10); FixedData fixedData = new FixedData(122, m_inputStreamFactory.getInstance(dir, "FixedData")); int items = fixedMeta.getAdjustedItemCount(); View view; ViewFactory factory = new ViewFactory9(); int lastOffset = -1; for (int loop = 0; loop < items; loop++) { byte[] fm = fixedMeta.getByteArrayValue(loop); int offset = MPPUtility.getShort(fm, 4); if (offset > lastOffset) { byte[] fd = fixedData.getByteArrayValue(fixedData.getIndexFromOffset(offset)); if (fd != null) { view = factory.createView(m_file, fm, fd, viewVarData, m_fontBases); m_file.getViews().add(view); //System.out.print(view); } lastOffset = offset; } } }
[ "private", "void", "processViewData", "(", ")", "throws", "IOException", "{", "DirectoryEntry", "dir", "=", "(", "DirectoryEntry", ")", "m_viewDir", ".", "getEntry", "(", "\"CV_iew\"", ")", ";", "VarMeta", "viewVarMeta", "=", "new", "VarMeta9", "(", "new", "DocumentInputStream", "(", "(", "(", "DocumentEntry", ")", "dir", ".", "getEntry", "(", "\"VarMeta\"", ")", ")", ")", ")", ";", "Var2Data", "viewVarData", "=", "new", "Var2Data", "(", "viewVarMeta", ",", "new", "DocumentInputStream", "(", "(", "(", "DocumentEntry", ")", "dir", ".", "getEntry", "(", "\"Var2Data\"", ")", ")", ")", ")", ";", "FixedMeta", "fixedMeta", "=", "new", "FixedMeta", "(", "new", "DocumentInputStream", "(", "(", "(", "DocumentEntry", ")", "dir", ".", "getEntry", "(", "\"FixedMeta\"", ")", ")", ")", ",", "10", ")", ";", "FixedData", "fixedData", "=", "new", "FixedData", "(", "122", ",", "m_inputStreamFactory", ".", "getInstance", "(", "dir", ",", "\"FixedData\"", ")", ")", ";", "int", "items", "=", "fixedMeta", ".", "getAdjustedItemCount", "(", ")", ";", "View", "view", ";", "ViewFactory", "factory", "=", "new", "ViewFactory9", "(", ")", ";", "int", "lastOffset", "=", "-", "1", ";", "for", "(", "int", "loop", "=", "0", ";", "loop", "<", "items", ";", "loop", "++", ")", "{", "byte", "[", "]", "fm", "=", "fixedMeta", ".", "getByteArrayValue", "(", "loop", ")", ";", "int", "offset", "=", "MPPUtility", ".", "getShort", "(", "fm", ",", "4", ")", ";", "if", "(", "offset", ">", "lastOffset", ")", "{", "byte", "[", "]", "fd", "=", "fixedData", ".", "getByteArrayValue", "(", "fixedData", ".", "getIndexFromOffset", "(", "offset", ")", ")", ";", "if", "(", "fd", "!=", "null", ")", "{", "view", "=", "factory", ".", "createView", "(", "m_file", ",", "fm", ",", "fd", ",", "viewVarData", ",", "m_fontBases", ")", ";", "m_file", ".", "getViews", "(", ")", ".", "add", "(", "view", ")", ";", "//System.out.print(view);", "}", "lastOffset", "=", "offset", ";", "}", "}", "}" ]
This method extracts view data from the MPP file. @throws IOException
[ "This", "method", "extracts", "view", "data", "from", "the", "MPP", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPP9Reader.java#L1914-L1943
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.parseRebasePaths
private void parseRebasePaths(String rebaseDefinitions) { """ Process a set of rebase definitions of the form 'a=b,c=d,e=f'. """ StringTokenizer tokenizer = new StringTokenizer(rebaseDefinitions, ","); while (tokenizer.hasMoreTokens()) { String rebasePair = tokenizer.nextToken(); int equals = rebasePair.indexOf('='); String fromPrefix = rebasePair.substring(0, equals); String toPrefix = rebasePair.substring(equals + 1); if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("processPropertiesConfiguration: adding rebase rule from '" + fromPrefix + "' to '" + toPrefix + "'"); } rebasePaths.put(fromPrefix, toPrefix); } }
java
private void parseRebasePaths(String rebaseDefinitions) { StringTokenizer tokenizer = new StringTokenizer(rebaseDefinitions, ","); while (tokenizer.hasMoreTokens()) { String rebasePair = tokenizer.nextToken(); int equals = rebasePair.indexOf('='); String fromPrefix = rebasePair.substring(0, equals); String toPrefix = rebasePair.substring(equals + 1); if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("processPropertiesConfiguration: adding rebase rule from '" + fromPrefix + "' to '" + toPrefix + "'"); } rebasePaths.put(fromPrefix, toPrefix); } }
[ "private", "void", "parseRebasePaths", "(", "String", "rebaseDefinitions", ")", "{", "StringTokenizer", "tokenizer", "=", "new", "StringTokenizer", "(", "rebaseDefinitions", ",", "\",\"", ")", ";", "while", "(", "tokenizer", ".", "hasMoreTokens", "(", ")", ")", "{", "String", "rebasePair", "=", "tokenizer", ".", "nextToken", "(", ")", ";", "int", "equals", "=", "rebasePair", ".", "indexOf", "(", "'", "'", ")", ";", "String", "fromPrefix", "=", "rebasePair", ".", "substring", "(", "0", ",", "equals", ")", ";", "String", "toPrefix", "=", "rebasePair", ".", "substring", "(", "equals", "+", "1", ")", ";", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "INFO", ")", ")", "{", "log", ".", "info", "(", "\"processPropertiesConfiguration: adding rebase rule from '\"", "+", "fromPrefix", "+", "\"' to '\"", "+", "toPrefix", "+", "\"'\"", ")", ";", "}", "rebasePaths", ".", "put", "(", "fromPrefix", ",", "toPrefix", ")", ";", "}", "}" ]
Process a set of rebase definitions of the form 'a=b,c=d,e=f'.
[ "Process", "a", "set", "of", "rebase", "definitions", "of", "the", "form", "a", "=", "b", "c", "=", "d", "e", "=", "f", "." ]
train
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L518-L531
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/entity/CmsEntityBackend.java
CmsEntityBackend.createFromNativeWrapper
public static CmsEntity createFromNativeWrapper(JavaScriptObject entityWrapper) { """ Method to create an entity object from a wrapped instance.<p> @param entityWrapper the wrappe entity @return the entity """ CmsEntity result = new CmsEntity(null, getEntityType(entityWrapper)); String[] simpleAttr = getSimpleAttributeNames(entityWrapper); for (int i = 0; i < simpleAttr.length; i++) { String[] simpleAttrValues = getSimpleAttributeValues(entityWrapper, simpleAttr[i]); for (int j = 0; j < simpleAttrValues.length; j++) { result.addAttributeValue(simpleAttr[i], simpleAttrValues[j]); } } String[] complexAttr = getComplexAttributeNames(entityWrapper); for (int i = 0; i < complexAttr.length; i++) { JavaScriptObject[] complexAttrValues = getComplexAttributeValues(entityWrapper, complexAttr[i]); for (int j = 0; j < complexAttrValues.length; j++) { result.addAttributeValue(complexAttr[i], createFromNativeWrapper(complexAttrValues[j])); } } return result; }
java
public static CmsEntity createFromNativeWrapper(JavaScriptObject entityWrapper) { CmsEntity result = new CmsEntity(null, getEntityType(entityWrapper)); String[] simpleAttr = getSimpleAttributeNames(entityWrapper); for (int i = 0; i < simpleAttr.length; i++) { String[] simpleAttrValues = getSimpleAttributeValues(entityWrapper, simpleAttr[i]); for (int j = 0; j < simpleAttrValues.length; j++) { result.addAttributeValue(simpleAttr[i], simpleAttrValues[j]); } } String[] complexAttr = getComplexAttributeNames(entityWrapper); for (int i = 0; i < complexAttr.length; i++) { JavaScriptObject[] complexAttrValues = getComplexAttributeValues(entityWrapper, complexAttr[i]); for (int j = 0; j < complexAttrValues.length; j++) { result.addAttributeValue(complexAttr[i], createFromNativeWrapper(complexAttrValues[j])); } } return result; }
[ "public", "static", "CmsEntity", "createFromNativeWrapper", "(", "JavaScriptObject", "entityWrapper", ")", "{", "CmsEntity", "result", "=", "new", "CmsEntity", "(", "null", ",", "getEntityType", "(", "entityWrapper", ")", ")", ";", "String", "[", "]", "simpleAttr", "=", "getSimpleAttributeNames", "(", "entityWrapper", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "simpleAttr", ".", "length", ";", "i", "++", ")", "{", "String", "[", "]", "simpleAttrValues", "=", "getSimpleAttributeValues", "(", "entityWrapper", ",", "simpleAttr", "[", "i", "]", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "simpleAttrValues", ".", "length", ";", "j", "++", ")", "{", "result", ".", "addAttributeValue", "(", "simpleAttr", "[", "i", "]", ",", "simpleAttrValues", "[", "j", "]", ")", ";", "}", "}", "String", "[", "]", "complexAttr", "=", "getComplexAttributeNames", "(", "entityWrapper", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "complexAttr", ".", "length", ";", "i", "++", ")", "{", "JavaScriptObject", "[", "]", "complexAttrValues", "=", "getComplexAttributeValues", "(", "entityWrapper", ",", "complexAttr", "[", "i", "]", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "complexAttrValues", ".", "length", ";", "j", "++", ")", "{", "result", ".", "addAttributeValue", "(", "complexAttr", "[", "i", "]", ",", "createFromNativeWrapper", "(", "complexAttrValues", "[", "j", "]", ")", ")", ";", "}", "}", "return", "result", ";", "}" ]
Method to create an entity object from a wrapped instance.<p> @param entityWrapper the wrappe entity @return the entity
[ "Method", "to", "create", "an", "entity", "object", "from", "a", "wrapped", "instance", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/entity/CmsEntityBackend.java#L79-L97
Azure/azure-sdk-for-java
common/azure-common/src/main/java/com/azure/common/implementation/RestProxy.java
RestProxy.createHttpRequest
@SuppressWarnings("unchecked") private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { """ Create a HttpRequest for the provided Swagger method using the provided arguments. @param methodParser the Swagger method parser to use @param args the arguments to use to populate the method's annotation values @return a HttpRequest @throws IOException thrown if the body contents cannot be serialized """ UrlBuilder urlBuilder; // Sometimes people pass in a full URL for the value of their PathParam annotated argument. // This definitely happens in paging scenarios. In that case, just use the full URL and // ignore the Host annotation. final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); // We add path to the UrlBuilder first because this is what is // provided to the HTTP Method annotation. Any path substitutions // from other substitution annotations will overwrite this. urlBuilder.withPath(path); final String scheme = methodParser.scheme(args); urlBuilder.withScheme(scheme); final String host = methodParser.host(args); urlBuilder.withHost(host); } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); // Headers from Swagger method arguments always take precedence over inferred headers from body types for (final HttpHeader header : methodParser.headers(args)) { request.withHeader(header.name(), header.value()); } return request; }
java
@SuppressWarnings("unchecked") private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; // Sometimes people pass in a full URL for the value of their PathParam annotated argument. // This definitely happens in paging scenarios. In that case, just use the full URL and // ignore the Host annotation. final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); // We add path to the UrlBuilder first because this is what is // provided to the HTTP Method annotation. Any path substitutions // from other substitution annotations will overwrite this. urlBuilder.withPath(path); final String scheme = methodParser.scheme(args); urlBuilder.withScheme(scheme); final String host = methodParser.host(args); urlBuilder.withHost(host); } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); // Headers from Swagger method arguments always take precedence over inferred headers from body types for (final HttpHeader header : methodParser.headers(args)) { request.withHeader(header.name(), header.value()); } return request; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "HttpRequest", "createHttpRequest", "(", "SwaggerMethodParser", "methodParser", ",", "Object", "[", "]", "args", ")", "throws", "IOException", "{", "UrlBuilder", "urlBuilder", ";", "// Sometimes people pass in a full URL for the value of their PathParam annotated argument.", "// This definitely happens in paging scenarios. In that case, just use the full URL and", "// ignore the Host annotation.", "final", "String", "path", "=", "methodParser", ".", "path", "(", "args", ")", ";", "final", "UrlBuilder", "pathUrlBuilder", "=", "UrlBuilder", ".", "parse", "(", "path", ")", ";", "if", "(", "pathUrlBuilder", ".", "scheme", "(", ")", "!=", "null", ")", "{", "urlBuilder", "=", "pathUrlBuilder", ";", "}", "else", "{", "urlBuilder", "=", "new", "UrlBuilder", "(", ")", ";", "// We add path to the UrlBuilder first because this is what is", "// provided to the HTTP Method annotation. Any path substitutions", "// from other substitution annotations will overwrite this.", "urlBuilder", ".", "withPath", "(", "path", ")", ";", "final", "String", "scheme", "=", "methodParser", ".", "scheme", "(", "args", ")", ";", "urlBuilder", ".", "withScheme", "(", "scheme", ")", ";", "final", "String", "host", "=", "methodParser", ".", "host", "(", "args", ")", ";", "urlBuilder", ".", "withHost", "(", "host", ")", ";", "}", "for", "(", "final", "EncodedParameter", "queryParameter", ":", "methodParser", ".", "encodedQueryParameters", "(", "args", ")", ")", "{", "urlBuilder", ".", "setQueryParameter", "(", "queryParameter", ".", "name", "(", ")", ",", "queryParameter", ".", "encodedValue", "(", ")", ")", ";", "}", "final", "URL", "url", "=", "urlBuilder", ".", "toURL", "(", ")", ";", "final", "HttpRequest", "request", "=", "configRequest", "(", "new", "HttpRequest", "(", "methodParser", ".", "httpMethod", "(", ")", ",", "url", ")", ",", "methodParser", ",", "args", ")", ";", "// Headers from Swagger method arguments always take precedence over inferred headers from body types", "for", "(", "final", "HttpHeader", "header", ":", "methodParser", ".", "headers", "(", "args", ")", ")", "{", "request", ".", "withHeader", "(", "header", ".", "name", "(", ")", ",", "header", ".", "value", "(", ")", ")", ";", "}", "return", "request", ";", "}" ]
Create a HttpRequest for the provided Swagger method using the provided arguments. @param methodParser the Swagger method parser to use @param args the arguments to use to populate the method's annotation values @return a HttpRequest @throws IOException thrown if the body contents cannot be serialized
[ "Create", "a", "HttpRequest", "for", "the", "provided", "Swagger", "method", "using", "the", "provided", "arguments", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/common/azure-common/src/main/java/com/azure/common/implementation/RestProxy.java#L161-L200
phax/ph-css
ph-css/src/main/java/com/helger/css/parser/CSSParseHelper.java
CSSParseHelper.extractStringValue
@Nullable public static String extractStringValue (@Nullable final String sStr) { """ Remove surrounding quotes (single or double) of a string (if present). If the start and the end quote are not equal, nothing happens. @param sStr The string where the quotes should be removed @return The string without quotes. """ if (StringHelper.hasNoText (sStr) || sStr.length () < 2) return sStr; final char cFirst = sStr.charAt (0); if ((cFirst == '"' || cFirst == '\'') && StringHelper.getLastChar (sStr) == cFirst) { // Remove quotes around the string return _trimBy (sStr, 1, 1); } return sStr; }
java
@Nullable public static String extractStringValue (@Nullable final String sStr) { if (StringHelper.hasNoText (sStr) || sStr.length () < 2) return sStr; final char cFirst = sStr.charAt (0); if ((cFirst == '"' || cFirst == '\'') && StringHelper.getLastChar (sStr) == cFirst) { // Remove quotes around the string return _trimBy (sStr, 1, 1); } return sStr; }
[ "@", "Nullable", "public", "static", "String", "extractStringValue", "(", "@", "Nullable", "final", "String", "sStr", ")", "{", "if", "(", "StringHelper", ".", "hasNoText", "(", "sStr", ")", "||", "sStr", ".", "length", "(", ")", "<", "2", ")", "return", "sStr", ";", "final", "char", "cFirst", "=", "sStr", ".", "charAt", "(", "0", ")", ";", "if", "(", "(", "cFirst", "==", "'", "'", "||", "cFirst", "==", "'", "'", ")", "&&", "StringHelper", ".", "getLastChar", "(", "sStr", ")", "==", "cFirst", ")", "{", "// Remove quotes around the string", "return", "_trimBy", "(", "sStr", ",", "1", ",", "1", ")", ";", "}", "return", "sStr", ";", "}" ]
Remove surrounding quotes (single or double) of a string (if present). If the start and the end quote are not equal, nothing happens. @param sStr The string where the quotes should be removed @return The string without quotes.
[ "Remove", "surrounding", "quotes", "(", "single", "or", "double", ")", "of", "a", "string", "(", "if", "present", ")", ".", "If", "the", "start", "and", "the", "end", "quote", "are", "not", "equal", "nothing", "happens", "." ]
train
https://github.com/phax/ph-css/blob/c9da5bb4decc681de6e27ce31712aad4c00adafa/ph-css/src/main/java/com/helger/css/parser/CSSParseHelper.java#L66-L79
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/sjavac/Util.java
Util.cleanSubOptions
public static String cleanSubOptions(String optionPrefix, Set<String> allowedSubOptions, String s) { """ Clean out unwanted sub options supplied inside a primary option. For example to only had portfile remaining from: settings="--server:id=foo,portfile=bar" do settings = cleanOptions("--server:",Util.set("-portfile"),settings); now settings equals "--server:portfile=bar" @param optionPrefix The option name, including colon, eg --server: @param allowsSubOptions A set of the allowed sub options, id portfile etc. @param s The option settings string. """ StringBuilder sb = new StringBuilder(); if (!s.startsWith(optionPrefix)) return ""; StringTokenizer st = new StringTokenizer(s.substring(optionPrefix.length()), ","); while (st.hasMoreTokens()) { String o = st.nextToken(); int p = o.indexOf('='); if (p>0) { String key = o.substring(0,p); String val = o.substring(p+1); if (allowedSubOptions.contains(key)) { if (sb.length() > 0) sb.append(','); sb.append(key+"="+val); } } } return sb.toString(); }
java
public static String cleanSubOptions(String optionPrefix, Set<String> allowedSubOptions, String s) { StringBuilder sb = new StringBuilder(); if (!s.startsWith(optionPrefix)) return ""; StringTokenizer st = new StringTokenizer(s.substring(optionPrefix.length()), ","); while (st.hasMoreTokens()) { String o = st.nextToken(); int p = o.indexOf('='); if (p>0) { String key = o.substring(0,p); String val = o.substring(p+1); if (allowedSubOptions.contains(key)) { if (sb.length() > 0) sb.append(','); sb.append(key+"="+val); } } } return sb.toString(); }
[ "public", "static", "String", "cleanSubOptions", "(", "String", "optionPrefix", ",", "Set", "<", "String", ">", "allowedSubOptions", ",", "String", "s", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "!", "s", ".", "startsWith", "(", "optionPrefix", ")", ")", "return", "\"\"", ";", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "s", ".", "substring", "(", "optionPrefix", ".", "length", "(", ")", ")", ",", "\",\"", ")", ";", "while", "(", "st", ".", "hasMoreTokens", "(", ")", ")", "{", "String", "o", "=", "st", ".", "nextToken", "(", ")", ";", "int", "p", "=", "o", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "p", ">", "0", ")", "{", "String", "key", "=", "o", ".", "substring", "(", "0", ",", "p", ")", ";", "String", "val", "=", "o", ".", "substring", "(", "p", "+", "1", ")", ";", "if", "(", "allowedSubOptions", ".", "contains", "(", "key", ")", ")", "{", "if", "(", "sb", ".", "length", "(", ")", ">", "0", ")", "sb", ".", "append", "(", "'", "'", ")", ";", "sb", ".", "append", "(", "key", "+", "\"=\"", "+", "val", ")", ";", "}", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Clean out unwanted sub options supplied inside a primary option. For example to only had portfile remaining from: settings="--server:id=foo,portfile=bar" do settings = cleanOptions("--server:",Util.set("-portfile"),settings); now settings equals "--server:portfile=bar" @param optionPrefix The option name, including colon, eg --server: @param allowsSubOptions A set of the allowed sub options, id portfile etc. @param s The option settings string.
[ "Clean", "out", "unwanted", "sub", "options", "supplied", "inside", "a", "primary", "option", ".", "For", "example", "to", "only", "had", "portfile", "remaining", "from", ":", "settings", "=", "--", "server", ":", "id", "=", "foo", "portfile", "=", "bar", "do", "settings", "=", "cleanOptions", "(", "--", "server", ":", "Util", ".", "set", "(", "-", "portfile", ")", "settings", ")", ";", "now", "settings", "equals", "--", "server", ":", "portfile", "=", "bar" ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/sjavac/Util.java#L101-L118
BigBadaboom/androidsvg
androidsvg/src/main/java/com/caverock/androidsvg/SVG.java
SVG.renderToPicture
@SuppressWarnings( { """ Renders this SVG document to a {@link Picture}. @param renderOptions options that describe how to render this SVG on the Canvas. @return a Picture object suitable for later rendering using {@link Canvas#drawPicture(Picture)} @since 1.3 """"WeakerAccess", "unused"}) public Picture renderToPicture(RenderOptions renderOptions) { Box viewBox = (renderOptions != null && renderOptions.hasViewBox()) ? renderOptions.viewBox : rootElement.viewBox; // If a viewPort was supplied in the renderOptions, then use its maxX and maxY as the Picture size if (renderOptions != null && renderOptions.hasViewPort()) { float w = renderOptions.viewPort.maxX(); float h = renderOptions.viewPort.maxY(); return renderToPicture( (int) Math.ceil(w), (int) Math.ceil(h), renderOptions ); } else if (rootElement.width != null && rootElement.width.unit != Unit.percent && rootElement.height != null && rootElement.height.unit != Unit.percent) { float w = rootElement.width.floatValue(this.renderDPI); float h = rootElement.height.floatValue(this.renderDPI); return renderToPicture( (int) Math.ceil(w), (int) Math.ceil(h), renderOptions ); } else if (rootElement.width != null && viewBox != null) { // Width and viewBox supplied, but no height // Determine the Picture size and initial viewport. See SVG spec section 7.12. float w = rootElement.width.floatValue(this.renderDPI); float h = w * viewBox.height / viewBox.width; return renderToPicture( (int) Math.ceil(w), (int) Math.ceil(h), renderOptions ); } else if (rootElement.height != null && viewBox != null) { // Height and viewBox supplied, but no width float h = rootElement.height.floatValue(this.renderDPI); float w = h * viewBox.width / viewBox.height; return renderToPicture( (int) Math.ceil(w), (int) Math.ceil(h), renderOptions ); } else { return renderToPicture(DEFAULT_PICTURE_WIDTH, DEFAULT_PICTURE_HEIGHT, renderOptions); } }
java
@SuppressWarnings({"WeakerAccess", "unused"}) public Picture renderToPicture(RenderOptions renderOptions) { Box viewBox = (renderOptions != null && renderOptions.hasViewBox()) ? renderOptions.viewBox : rootElement.viewBox; // If a viewPort was supplied in the renderOptions, then use its maxX and maxY as the Picture size if (renderOptions != null && renderOptions.hasViewPort()) { float w = renderOptions.viewPort.maxX(); float h = renderOptions.viewPort.maxY(); return renderToPicture( (int) Math.ceil(w), (int) Math.ceil(h), renderOptions ); } else if (rootElement.width != null && rootElement.width.unit != Unit.percent && rootElement.height != null && rootElement.height.unit != Unit.percent) { float w = rootElement.width.floatValue(this.renderDPI); float h = rootElement.height.floatValue(this.renderDPI); return renderToPicture( (int) Math.ceil(w), (int) Math.ceil(h), renderOptions ); } else if (rootElement.width != null && viewBox != null) { // Width and viewBox supplied, but no height // Determine the Picture size and initial viewport. See SVG spec section 7.12. float w = rootElement.width.floatValue(this.renderDPI); float h = w * viewBox.height / viewBox.width; return renderToPicture( (int) Math.ceil(w), (int) Math.ceil(h), renderOptions ); } else if (rootElement.height != null && viewBox != null) { // Height and viewBox supplied, but no width float h = rootElement.height.floatValue(this.renderDPI); float w = h * viewBox.width / viewBox.height; return renderToPicture( (int) Math.ceil(w), (int) Math.ceil(h), renderOptions ); } else { return renderToPicture(DEFAULT_PICTURE_WIDTH, DEFAULT_PICTURE_HEIGHT, renderOptions); } }
[ "@", "SuppressWarnings", "(", "{", "\"WeakerAccess\"", ",", "\"unused\"", "}", ")", "public", "Picture", "renderToPicture", "(", "RenderOptions", "renderOptions", ")", "{", "Box", "viewBox", "=", "(", "renderOptions", "!=", "null", "&&", "renderOptions", ".", "hasViewBox", "(", ")", ")", "?", "renderOptions", ".", "viewBox", ":", "rootElement", ".", "viewBox", ";", "// If a viewPort was supplied in the renderOptions, then use its maxX and maxY as the Picture size\r", "if", "(", "renderOptions", "!=", "null", "&&", "renderOptions", ".", "hasViewPort", "(", ")", ")", "{", "float", "w", "=", "renderOptions", ".", "viewPort", ".", "maxX", "(", ")", ";", "float", "h", "=", "renderOptions", ".", "viewPort", ".", "maxY", "(", ")", ";", "return", "renderToPicture", "(", "(", "int", ")", "Math", ".", "ceil", "(", "w", ")", ",", "(", "int", ")", "Math", ".", "ceil", "(", "h", ")", ",", "renderOptions", ")", ";", "}", "else", "if", "(", "rootElement", ".", "width", "!=", "null", "&&", "rootElement", ".", "width", ".", "unit", "!=", "Unit", ".", "percent", "&&", "rootElement", ".", "height", "!=", "null", "&&", "rootElement", ".", "height", ".", "unit", "!=", "Unit", ".", "percent", ")", "{", "float", "w", "=", "rootElement", ".", "width", ".", "floatValue", "(", "this", ".", "renderDPI", ")", ";", "float", "h", "=", "rootElement", ".", "height", ".", "floatValue", "(", "this", ".", "renderDPI", ")", ";", "return", "renderToPicture", "(", "(", "int", ")", "Math", ".", "ceil", "(", "w", ")", ",", "(", "int", ")", "Math", ".", "ceil", "(", "h", ")", ",", "renderOptions", ")", ";", "}", "else", "if", "(", "rootElement", ".", "width", "!=", "null", "&&", "viewBox", "!=", "null", ")", "{", "// Width and viewBox supplied, but no height\r", "// Determine the Picture size and initial viewport. See SVG spec section 7.12.\r", "float", "w", "=", "rootElement", ".", "width", ".", "floatValue", "(", "this", ".", "renderDPI", ")", ";", "float", "h", "=", "w", "*", "viewBox", ".", "height", "/", "viewBox", ".", "width", ";", "return", "renderToPicture", "(", "(", "int", ")", "Math", ".", "ceil", "(", "w", ")", ",", "(", "int", ")", "Math", ".", "ceil", "(", "h", ")", ",", "renderOptions", ")", ";", "}", "else", "if", "(", "rootElement", ".", "height", "!=", "null", "&&", "viewBox", "!=", "null", ")", "{", "// Height and viewBox supplied, but no width\r", "float", "h", "=", "rootElement", ".", "height", ".", "floatValue", "(", "this", ".", "renderDPI", ")", ";", "float", "w", "=", "h", "*", "viewBox", ".", "width", "/", "viewBox", ".", "height", ";", "return", "renderToPicture", "(", "(", "int", ")", "Math", ".", "ceil", "(", "w", ")", ",", "(", "int", ")", "Math", ".", "ceil", "(", "h", ")", ",", "renderOptions", ")", ";", "}", "else", "{", "return", "renderToPicture", "(", "DEFAULT_PICTURE_WIDTH", ",", "DEFAULT_PICTURE_HEIGHT", ",", "renderOptions", ")", ";", "}", "}" ]
Renders this SVG document to a {@link Picture}. @param renderOptions options that describe how to render this SVG on the Canvas. @return a Picture object suitable for later rendering using {@link Canvas#drawPicture(Picture)} @since 1.3
[ "Renders", "this", "SVG", "document", "to", "a", "{", "@link", "Picture", "}", "." ]
train
https://github.com/BigBadaboom/androidsvg/blob/0d1614dd1a4da10ea4afe3b0cea1361a4ac6b45a/androidsvg/src/main/java/com/caverock/androidsvg/SVG.java#L376-L415
riversun/d6
src/main/java/org/riversun/d6/core/D6Crud.java
D6Crud.execInsert
public boolean execInsert(D6Model[] modelObjects, D6Inex includeExcludeColumnNames) { """ Insert the specified model object into the DB @param modelObjects @param includeExcludeColumnNames You can select either 'the column name you want to reflected in the database' AND 'the column name you don't want to reflect in the database'. When omitted (null specified) ,reflects all properties in the model class has to be reflected to the database. @return true:DB operation success false:failure """ boolean ignoreDuplicate = false; return execInsert(modelObjects, includeExcludeColumnNames, ignoreDuplicate); }
java
public boolean execInsert(D6Model[] modelObjects, D6Inex includeExcludeColumnNames) { boolean ignoreDuplicate = false; return execInsert(modelObjects, includeExcludeColumnNames, ignoreDuplicate); }
[ "public", "boolean", "execInsert", "(", "D6Model", "[", "]", "modelObjects", ",", "D6Inex", "includeExcludeColumnNames", ")", "{", "boolean", "ignoreDuplicate", "=", "false", ";", "return", "execInsert", "(", "modelObjects", ",", "includeExcludeColumnNames", ",", "ignoreDuplicate", ")", ";", "}" ]
Insert the specified model object into the DB @param modelObjects @param includeExcludeColumnNames You can select either 'the column name you want to reflected in the database' AND 'the column name you don't want to reflect in the database'. When omitted (null specified) ,reflects all properties in the model class has to be reflected to the database. @return true:DB operation success false:failure
[ "Insert", "the", "specified", "model", "object", "into", "the", "DB" ]
train
https://github.com/riversun/d6/blob/2798bd876b9380dbfea8182d11ad306cb1b0e114/src/main/java/org/riversun/d6/core/D6Crud.java#L507-L510
jamesagnew/hapi-fhir
hapi-fhir-utilities/src/main/java/org/hl7/fhir/utilities/IniFile.java
IniFile.utilDateToStr
private String utilDateToStr(Date pdt, String pstrFmt) { """ Converts a java.util.date into String @param pd Date that need to be converted to String @param pstrFmt The date format pattern. @return String """ String strRet = null; SimpleDateFormat dtFmt = null; try { dtFmt = new SimpleDateFormat(pstrFmt); strRet = dtFmt.format(pdt); } catch (Exception e) { strRet = null; } finally { if (dtFmt != null) dtFmt = null; } return strRet; }
java
private String utilDateToStr(Date pdt, String pstrFmt) { String strRet = null; SimpleDateFormat dtFmt = null; try { dtFmt = new SimpleDateFormat(pstrFmt); strRet = dtFmt.format(pdt); } catch (Exception e) { strRet = null; } finally { if (dtFmt != null) dtFmt = null; } return strRet; }
[ "private", "String", "utilDateToStr", "(", "Date", "pdt", ",", "String", "pstrFmt", ")", "{", "String", "strRet", "=", "null", ";", "SimpleDateFormat", "dtFmt", "=", "null", ";", "try", "{", "dtFmt", "=", "new", "SimpleDateFormat", "(", "pstrFmt", ")", ";", "strRet", "=", "dtFmt", ".", "format", "(", "pdt", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "strRet", "=", "null", ";", "}", "finally", "{", "if", "(", "dtFmt", "!=", "null", ")", "dtFmt", "=", "null", ";", "}", "return", "strRet", ";", "}" ]
Converts a java.util.date into String @param pd Date that need to be converted to String @param pstrFmt The date format pattern. @return String
[ "Converts", "a", "java", ".", "util", ".", "date", "into", "String" ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-utilities/src/main/java/org/hl7/fhir/utilities/IniFile.java#L1099-L1118
couchbase/couchbase-lite-java
src/main/java/com/couchbase/lite/MutableArray.java
MutableArray.insertNumber
@NonNull @Override public MutableArray insertNumber(int index, Number value) { """ Inserts a Number object at the given index. @param index the index. This value must not exceed the bounds of the array. @param value the Number object @return The self object """ return insertValue(index, value); }
java
@NonNull @Override public MutableArray insertNumber(int index, Number value) { return insertValue(index, value); }
[ "@", "NonNull", "@", "Override", "public", "MutableArray", "insertNumber", "(", "int", "index", ",", "Number", "value", ")", "{", "return", "insertValue", "(", "index", ",", "value", ")", ";", "}" ]
Inserts a Number object at the given index. @param index the index. This value must not exceed the bounds of the array. @param value the Number object @return The self object
[ "Inserts", "a", "Number", "object", "at", "the", "given", "index", "." ]
train
https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/MutableArray.java#L436-L440
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.getKeyVersionsAsync
public Observable<Page<KeyItem>> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName) { """ Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param keyName The name of the key. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;KeyItem&gt; object """ return getKeyVersionsWithServiceResponseAsync(vaultBaseUrl, keyName) .map(new Func1<ServiceResponse<Page<KeyItem>>, Page<KeyItem>>() { @Override public Page<KeyItem> call(ServiceResponse<Page<KeyItem>> response) { return response.body(); } }); }
java
public Observable<Page<KeyItem>> getKeyVersionsAsync(final String vaultBaseUrl, final String keyName) { return getKeyVersionsWithServiceResponseAsync(vaultBaseUrl, keyName) .map(new Func1<ServiceResponse<Page<KeyItem>>, Page<KeyItem>>() { @Override public Page<KeyItem> call(ServiceResponse<Page<KeyItem>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "KeyItem", ">", ">", "getKeyVersionsAsync", "(", "final", "String", "vaultBaseUrl", ",", "final", "String", "keyName", ")", "{", "return", "getKeyVersionsWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "keyName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "KeyItem", ">", ">", ",", "Page", "<", "KeyItem", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "KeyItem", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "KeyItem", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Retrieves a list of individual key versions with the same key name. The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param keyName The name of the key. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;KeyItem&gt; object
[ "Retrieves", "a", "list", "of", "individual", "key", "versions", "with", "the", "same", "key", "name", ".", "The", "full", "key", "identifier", "attributes", "and", "tags", "are", "provided", "in", "the", "response", ".", "This", "operation", "requires", "the", "keys", "/", "list", "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#L1520-L1528
pippo-java/pippo
pippo-core/src/main/java/ro/pippo/core/Languages.java
Languages.generateLanguageCookie
private Cookie generateLanguageCookie(String language) { """ Generates a language cookie with a very long max age (ten years). @param language @return The cookie """ Cookie cookie = new Cookie(applicationCookiePrefix + "_LANG", language); cookie.setSecure(true); cookie.setMaxAge(TEN_YEARS); return cookie; }
java
private Cookie generateLanguageCookie(String language) { Cookie cookie = new Cookie(applicationCookiePrefix + "_LANG", language); cookie.setSecure(true); cookie.setMaxAge(TEN_YEARS); return cookie; }
[ "private", "Cookie", "generateLanguageCookie", "(", "String", "language", ")", "{", "Cookie", "cookie", "=", "new", "Cookie", "(", "applicationCookiePrefix", "+", "\"_LANG\"", ",", "language", ")", ";", "cookie", ".", "setSecure", "(", "true", ")", ";", "cookie", ".", "setMaxAge", "(", "TEN_YEARS", ")", ";", "return", "cookie", ";", "}" ]
Generates a language cookie with a very long max age (ten years). @param language @return The cookie
[ "Generates", "a", "language", "cookie", "with", "a", "very", "long", "max", "age", "(", "ten", "years", ")", "." ]
train
https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/Languages.java#L267-L272
j-a-w-r/jawr-main-repo
jawr-tools/jawr-bundle-processor/src/main/java/net/jawr/web/bundle/processor/BundleProcessor.java
BundleProcessor.getImageFinalPath
public String getImageFinalPath(String path, JawrConfig jawrConfig) { """ Retrieves the image final path, where the servlet mapping and the cache prefix have been removed @param path the path @param jawrConfig the jawr config @return the final path """ String finalPath = path; // Remove servlet mapping if it exists. finalPath = removeServletMappingFromPath(finalPath, jawrConfig.getServletMapping()); if (finalPath.startsWith("/")) { finalPath = finalPath.substring(1); } // remove cache prefix int idx = finalPath.indexOf("/"); finalPath = finalPath.substring(idx + 1); return finalPath; }
java
public String getImageFinalPath(String path, JawrConfig jawrConfig) { String finalPath = path; // Remove servlet mapping if it exists. finalPath = removeServletMappingFromPath(finalPath, jawrConfig.getServletMapping()); if (finalPath.startsWith("/")) { finalPath = finalPath.substring(1); } // remove cache prefix int idx = finalPath.indexOf("/"); finalPath = finalPath.substring(idx + 1); return finalPath; }
[ "public", "String", "getImageFinalPath", "(", "String", "path", ",", "JawrConfig", "jawrConfig", ")", "{", "String", "finalPath", "=", "path", ";", "// Remove servlet mapping if it exists.", "finalPath", "=", "removeServletMappingFromPath", "(", "finalPath", ",", "jawrConfig", ".", "getServletMapping", "(", ")", ")", ";", "if", "(", "finalPath", ".", "startsWith", "(", "\"/\"", ")", ")", "{", "finalPath", "=", "finalPath", ".", "substring", "(", "1", ")", ";", "}", "// remove cache prefix", "int", "idx", "=", "finalPath", ".", "indexOf", "(", "\"/\"", ")", ";", "finalPath", "=", "finalPath", ".", "substring", "(", "idx", "+", "1", ")", ";", "return", "finalPath", ";", "}" ]
Retrieves the image final path, where the servlet mapping and the cache prefix have been removed @param path the path @param jawrConfig the jawr config @return the final path
[ "Retrieves", "the", "image", "final", "path", "where", "the", "servlet", "mapping", "and", "the", "cache", "prefix", "have", "been", "removed" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr-tools/jawr-bundle-processor/src/main/java/net/jawr/web/bundle/processor/BundleProcessor.java#L956-L972
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeAlignmentPatternLocator.java
QrCodeAlignmentPatternLocator.centerOnSquare
boolean centerOnSquare(QrCode.Alignment pattern, float guessY, float guessX) { """ If the initial guess is within the inner white circle or black dot this will ensure that it is centered on the black dot """ float step = 1; float bestMag = Float.MAX_VALUE; float bestX = guessX; float bestY = guessY; for (int i = 0; i < 10; i++) { for (int row = 0; row < 3; row++) { float gridy = guessY - 1f + row; for (int col = 0; col < 3; col++) { float gridx = guessX - 1f + col; samples[row*3+col] = reader.read(gridy,gridx); } } float dx = (samples[2]+samples[5]+samples[8])-(samples[0]+samples[3]+samples[6]); float dy = (samples[6]+samples[7]+samples[8])-(samples[0]+samples[1]+samples[2]); float r = (float)Math.sqrt(dx*dx + dy*dy); if( bestMag > r ) { // System.out.println("good step at "+i); bestMag = r; bestX = guessX; bestY = guessY; } else { // System.out.println("bad step at "+i); step *= 0.75f; } if( r > 0 ) { guessX = bestX + step * dx / r; guessY = bestY + step * dy / r; } else { break; } } pattern.moduleFound.x = bestX; pattern.moduleFound.y = bestY; reader.gridToImage((float)pattern.moduleFound.y,(float)pattern.moduleFound.x,pattern.pixel); return true; }
java
boolean centerOnSquare(QrCode.Alignment pattern, float guessY, float guessX) { float step = 1; float bestMag = Float.MAX_VALUE; float bestX = guessX; float bestY = guessY; for (int i = 0; i < 10; i++) { for (int row = 0; row < 3; row++) { float gridy = guessY - 1f + row; for (int col = 0; col < 3; col++) { float gridx = guessX - 1f + col; samples[row*3+col] = reader.read(gridy,gridx); } } float dx = (samples[2]+samples[5]+samples[8])-(samples[0]+samples[3]+samples[6]); float dy = (samples[6]+samples[7]+samples[8])-(samples[0]+samples[1]+samples[2]); float r = (float)Math.sqrt(dx*dx + dy*dy); if( bestMag > r ) { // System.out.println("good step at "+i); bestMag = r; bestX = guessX; bestY = guessY; } else { // System.out.println("bad step at "+i); step *= 0.75f; } if( r > 0 ) { guessX = bestX + step * dx / r; guessY = bestY + step * dy / r; } else { break; } } pattern.moduleFound.x = bestX; pattern.moduleFound.y = bestY; reader.gridToImage((float)pattern.moduleFound.y,(float)pattern.moduleFound.x,pattern.pixel); return true; }
[ "boolean", "centerOnSquare", "(", "QrCode", ".", "Alignment", "pattern", ",", "float", "guessY", ",", "float", "guessX", ")", "{", "float", "step", "=", "1", ";", "float", "bestMag", "=", "Float", ".", "MAX_VALUE", ";", "float", "bestX", "=", "guessX", ";", "float", "bestY", "=", "guessY", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "10", ";", "i", "++", ")", "{", "for", "(", "int", "row", "=", "0", ";", "row", "<", "3", ";", "row", "++", ")", "{", "float", "gridy", "=", "guessY", "-", "1f", "+", "row", ";", "for", "(", "int", "col", "=", "0", ";", "col", "<", "3", ";", "col", "++", ")", "{", "float", "gridx", "=", "guessX", "-", "1f", "+", "col", ";", "samples", "[", "row", "*", "3", "+", "col", "]", "=", "reader", ".", "read", "(", "gridy", ",", "gridx", ")", ";", "}", "}", "float", "dx", "=", "(", "samples", "[", "2", "]", "+", "samples", "[", "5", "]", "+", "samples", "[", "8", "]", ")", "-", "(", "samples", "[", "0", "]", "+", "samples", "[", "3", "]", "+", "samples", "[", "6", "]", ")", ";", "float", "dy", "=", "(", "samples", "[", "6", "]", "+", "samples", "[", "7", "]", "+", "samples", "[", "8", "]", ")", "-", "(", "samples", "[", "0", "]", "+", "samples", "[", "1", "]", "+", "samples", "[", "2", "]", ")", ";", "float", "r", "=", "(", "float", ")", "Math", ".", "sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", ";", "if", "(", "bestMag", ">", "r", ")", "{", "//\t\t\t\tSystem.out.println(\"good step at \"+i);", "bestMag", "=", "r", ";", "bestX", "=", "guessX", ";", "bestY", "=", "guessY", ";", "}", "else", "{", "//\t\t\t\tSystem.out.println(\"bad step at \"+i);", "step", "*=", "0.75f", ";", "}", "if", "(", "r", ">", "0", ")", "{", "guessX", "=", "bestX", "+", "step", "*", "dx", "/", "r", ";", "guessY", "=", "bestY", "+", "step", "*", "dy", "/", "r", ";", "}", "else", "{", "break", ";", "}", "}", "pattern", ".", "moduleFound", ".", "x", "=", "bestX", ";", "pattern", ".", "moduleFound", ".", "y", "=", "bestY", ";", "reader", ".", "gridToImage", "(", "(", "float", ")", "pattern", ".", "moduleFound", ".", "y", ",", "(", "float", ")", "pattern", ".", "moduleFound", ".", "x", ",", "pattern", ".", "pixel", ")", ";", "return", "true", ";", "}" ]
If the initial guess is within the inner white circle or black dot this will ensure that it is centered on the black dot
[ "If", "the", "initial", "guess", "is", "within", "the", "inner", "white", "circle", "or", "black", "dot", "this", "will", "ensure", "that", "it", "is", "centered", "on", "the", "black", "dot" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodeAlignmentPatternLocator.java#L153-L198
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/trace/TraceId.java
TraceId.copyLowerBase16To
public void copyLowerBase16To(char[] dest, int destOffset) { """ Copies the lowercase base16 representations of the {@code TraceId} into the {@code dest} beginning at the {@code destOffset} offset. @param dest the destination buffer. @param destOffset the starting offset in the destination buffer. @throws IndexOutOfBoundsException if {@code destOffset + 2 * TraceId.SIZE} is greater than {@code dest.length}. @since 0.18 """ BigendianEncoding.longToBase16String(idHi, dest, destOffset); BigendianEncoding.longToBase16String(idLo, dest, destOffset + BASE16_SIZE / 2); }
java
public void copyLowerBase16To(char[] dest, int destOffset) { BigendianEncoding.longToBase16String(idHi, dest, destOffset); BigendianEncoding.longToBase16String(idLo, dest, destOffset + BASE16_SIZE / 2); }
[ "public", "void", "copyLowerBase16To", "(", "char", "[", "]", "dest", ",", "int", "destOffset", ")", "{", "BigendianEncoding", ".", "longToBase16String", "(", "idHi", ",", "dest", ",", "destOffset", ")", ";", "BigendianEncoding", ".", "longToBase16String", "(", "idLo", ",", "dest", ",", "destOffset", "+", "BASE16_SIZE", "/", "2", ")", ";", "}" ]
Copies the lowercase base16 representations of the {@code TraceId} into the {@code dest} beginning at the {@code destOffset} offset. @param dest the destination buffer. @param destOffset the starting offset in the destination buffer. @throws IndexOutOfBoundsException if {@code destOffset + 2 * TraceId.SIZE} is greater than {@code dest.length}. @since 0.18
[ "Copies", "the", "lowercase", "base16", "representations", "of", "the", "{", "@code", "TraceId", "}", "into", "the", "{", "@code", "dest", "}", "beginning", "at", "the", "{", "@code", "destOffset", "}", "offset", "." ]
train
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/trace/TraceId.java#L189-L192
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/net/SSLUtils.java
SSLUtils.createSSLServerSocketFactory
public static ServerSocketFactory createSSLServerSocketFactory(Configuration config) throws Exception { """ Creates a factory for SSL Server Sockets from the given configuration. SSL Server Sockets are always part of internal communication. """ SSLContext sslContext = createInternalSSLContext(config); if (sslContext == null) { throw new IllegalConfigurationException("SSL is not enabled"); } String[] protocols = getEnabledProtocols(config); String[] cipherSuites = getEnabledCipherSuites(config); SSLServerSocketFactory factory = sslContext.getServerSocketFactory(); return new ConfiguringSSLServerSocketFactory(factory, protocols, cipherSuites); }
java
public static ServerSocketFactory createSSLServerSocketFactory(Configuration config) throws Exception { SSLContext sslContext = createInternalSSLContext(config); if (sslContext == null) { throw new IllegalConfigurationException("SSL is not enabled"); } String[] protocols = getEnabledProtocols(config); String[] cipherSuites = getEnabledCipherSuites(config); SSLServerSocketFactory factory = sslContext.getServerSocketFactory(); return new ConfiguringSSLServerSocketFactory(factory, protocols, cipherSuites); }
[ "public", "static", "ServerSocketFactory", "createSSLServerSocketFactory", "(", "Configuration", "config", ")", "throws", "Exception", "{", "SSLContext", "sslContext", "=", "createInternalSSLContext", "(", "config", ")", ";", "if", "(", "sslContext", "==", "null", ")", "{", "throw", "new", "IllegalConfigurationException", "(", "\"SSL is not enabled\"", ")", ";", "}", "String", "[", "]", "protocols", "=", "getEnabledProtocols", "(", "config", ")", ";", "String", "[", "]", "cipherSuites", "=", "getEnabledCipherSuites", "(", "config", ")", ";", "SSLServerSocketFactory", "factory", "=", "sslContext", ".", "getServerSocketFactory", "(", ")", ";", "return", "new", "ConfiguringSSLServerSocketFactory", "(", "factory", ",", "protocols", ",", "cipherSuites", ")", ";", "}" ]
Creates a factory for SSL Server Sockets from the given configuration. SSL Server Sockets are always part of internal communication.
[ "Creates", "a", "factory", "for", "SSL", "Server", "Sockets", "from", "the", "given", "configuration", ".", "SSL", "Server", "Sockets", "are", "always", "part", "of", "internal", "communication", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/net/SSLUtils.java#L84-L95
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/util/ShapeGenerator.java
ShapeGenerator.createTabCloseIcon
public Shape createTabCloseIcon(int x, int y, int w, int h) { """ Return a path for a "cancel" icon. This is a circle with a punched out "x" in it. @param x the X coordinate of the upper-left corner of the icon @param y the Y coordinate of the upper-left corner of the icon @param w the width of the icon @param h the height of the icon @return a path representing the shape. """ final double xMid = x + w / 2.0; final double yMid = y + h / 2.0; path.reset(); final double xOffsetL = w / 2.0; final double xOffsetS = w / 2.0 - 1; final double yOffsetL = h / 2.0; final double yOffsetS = h / 2.0 - 1; final double offsetC = 1; path.moveTo(xMid, yMid - offsetC); path.lineTo(xMid + xOffsetS, yMid - yOffsetL); path.lineTo(yMid + xOffsetL, yMid - yOffsetS); path.lineTo(xMid + offsetC, yMid); path.lineTo(xMid + xOffsetL, yMid + yOffsetS); path.lineTo(xMid + xOffsetS, yMid + yOffsetL); path.lineTo(xMid, yMid + offsetC); path.lineTo(xMid - xOffsetS, yMid + yOffsetL); path.lineTo(xMid - xOffsetL, yMid + yOffsetS); path.lineTo(xMid - offsetC, yMid); path.lineTo(xMid - xOffsetL, yMid - yOffsetS); path.lineTo(xMid - xOffsetS, yMid - yOffsetL); path.closePath(); return path; }
java
public Shape createTabCloseIcon(int x, int y, int w, int h) { final double xMid = x + w / 2.0; final double yMid = y + h / 2.0; path.reset(); final double xOffsetL = w / 2.0; final double xOffsetS = w / 2.0 - 1; final double yOffsetL = h / 2.0; final double yOffsetS = h / 2.0 - 1; final double offsetC = 1; path.moveTo(xMid, yMid - offsetC); path.lineTo(xMid + xOffsetS, yMid - yOffsetL); path.lineTo(yMid + xOffsetL, yMid - yOffsetS); path.lineTo(xMid + offsetC, yMid); path.lineTo(xMid + xOffsetL, yMid + yOffsetS); path.lineTo(xMid + xOffsetS, yMid + yOffsetL); path.lineTo(xMid, yMid + offsetC); path.lineTo(xMid - xOffsetS, yMid + yOffsetL); path.lineTo(xMid - xOffsetL, yMid + yOffsetS); path.lineTo(xMid - offsetC, yMid); path.lineTo(xMid - xOffsetL, yMid - yOffsetS); path.lineTo(xMid - xOffsetS, yMid - yOffsetL); path.closePath(); return path; }
[ "public", "Shape", "createTabCloseIcon", "(", "int", "x", ",", "int", "y", ",", "int", "w", ",", "int", "h", ")", "{", "final", "double", "xMid", "=", "x", "+", "w", "/", "2.0", ";", "final", "double", "yMid", "=", "y", "+", "h", "/", "2.0", ";", "path", ".", "reset", "(", ")", ";", "final", "double", "xOffsetL", "=", "w", "/", "2.0", ";", "final", "double", "xOffsetS", "=", "w", "/", "2.0", "-", "1", ";", "final", "double", "yOffsetL", "=", "h", "/", "2.0", ";", "final", "double", "yOffsetS", "=", "h", "/", "2.0", "-", "1", ";", "final", "double", "offsetC", "=", "1", ";", "path", ".", "moveTo", "(", "xMid", ",", "yMid", "-", "offsetC", ")", ";", "path", ".", "lineTo", "(", "xMid", "+", "xOffsetS", ",", "yMid", "-", "yOffsetL", ")", ";", "path", ".", "lineTo", "(", "yMid", "+", "xOffsetL", ",", "yMid", "-", "yOffsetS", ")", ";", "path", ".", "lineTo", "(", "xMid", "+", "offsetC", ",", "yMid", ")", ";", "path", ".", "lineTo", "(", "xMid", "+", "xOffsetL", ",", "yMid", "+", "yOffsetS", ")", ";", "path", ".", "lineTo", "(", "xMid", "+", "xOffsetS", ",", "yMid", "+", "yOffsetL", ")", ";", "path", ".", "lineTo", "(", "xMid", ",", "yMid", "+", "offsetC", ")", ";", "path", ".", "lineTo", "(", "xMid", "-", "xOffsetS", ",", "yMid", "+", "yOffsetL", ")", ";", "path", ".", "lineTo", "(", "xMid", "-", "xOffsetL", ",", "yMid", "+", "yOffsetS", ")", ";", "path", ".", "lineTo", "(", "xMid", "-", "offsetC", ",", "yMid", ")", ";", "path", ".", "lineTo", "(", "xMid", "-", "xOffsetL", ",", "yMid", "-", "yOffsetS", ")", ";", "path", ".", "lineTo", "(", "xMid", "-", "xOffsetS", ",", "yMid", "-", "yOffsetL", ")", ";", "path", ".", "closePath", "(", ")", ";", "return", "path", ";", "}" ]
Return a path for a "cancel" icon. This is a circle with a punched out "x" in it. @param x the X coordinate of the upper-left corner of the icon @param y the Y coordinate of the upper-left corner of the icon @param w the width of the icon @param h the height of the icon @return a path representing the shape.
[ "Return", "a", "path", "for", "a", "cancel", "icon", ".", "This", "is", "a", "circle", "with", "a", "punched", "out", "x", "in", "it", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/util/ShapeGenerator.java#L605-L632
Stratio/deep-spark
deep-mongodb/src/main/java/com/stratio/deep/mongodb/extractor/MongoNativeExtractor.java
MongoNativeExtractor.isShardedCollection
private boolean isShardedCollection(DBCollection collection) { """ Is sharded collection. @param collection the collection @return the boolean """ DB config = collection.getDB().getMongo().getDB("config"); DBCollection configCollections = config.getCollection("collections"); DBObject dbObject = configCollections.findOne(new BasicDBObject(MONGO_DEFAULT_ID, collection.getFullName())); return dbObject != null; }
java
private boolean isShardedCollection(DBCollection collection) { DB config = collection.getDB().getMongo().getDB("config"); DBCollection configCollections = config.getCollection("collections"); DBObject dbObject = configCollections.findOne(new BasicDBObject(MONGO_DEFAULT_ID, collection.getFullName())); return dbObject != null; }
[ "private", "boolean", "isShardedCollection", "(", "DBCollection", "collection", ")", "{", "DB", "config", "=", "collection", ".", "getDB", "(", ")", ".", "getMongo", "(", ")", ".", "getDB", "(", "\"config\"", ")", ";", "DBCollection", "configCollections", "=", "config", ".", "getCollection", "(", "\"collections\"", ")", ";", "DBObject", "dbObject", "=", "configCollections", ".", "findOne", "(", "new", "BasicDBObject", "(", "MONGO_DEFAULT_ID", ",", "collection", ".", "getFullName", "(", ")", ")", ")", ";", "return", "dbObject", "!=", "null", ";", "}" ]
Is sharded collection. @param collection the collection @return the boolean
[ "Is", "sharded", "collection", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-mongodb/src/main/java/com/stratio/deep/mongodb/extractor/MongoNativeExtractor.java#L137-L144
xwiki/xwiki-rendering
xwiki-rendering-transformations/xwiki-rendering-transformation-icon/src/main/java/org/xwiki/rendering/internal/transformation/icon/IconTransformation.java
IconTransformation.indexOf
private int indexOf(List<Block> targetBlocks, Block block) { """ Shallow indexOf implementation that only compares nodes based on their data and not their children data. @param targetBlocks the list of blocks to look into @param block the block to look for in the list of passed blocks @return the position of the block in the list of target blocks and -1 if not found """ int pos = 0; for (Block targetBlock : targetBlocks) { // Test a non deep equality if (blockEquals(targetBlock, block)) { return pos; } pos++; } return -1; }
java
private int indexOf(List<Block> targetBlocks, Block block) { int pos = 0; for (Block targetBlock : targetBlocks) { // Test a non deep equality if (blockEquals(targetBlock, block)) { return pos; } pos++; } return -1; }
[ "private", "int", "indexOf", "(", "List", "<", "Block", ">", "targetBlocks", ",", "Block", "block", ")", "{", "int", "pos", "=", "0", ";", "for", "(", "Block", "targetBlock", ":", "targetBlocks", ")", "{", "// Test a non deep equality", "if", "(", "blockEquals", "(", "targetBlock", ",", "block", ")", ")", "{", "return", "pos", ";", "}", "pos", "++", ";", "}", "return", "-", "1", ";", "}" ]
Shallow indexOf implementation that only compares nodes based on their data and not their children data. @param targetBlocks the list of blocks to look into @param block the block to look for in the list of passed blocks @return the position of the block in the list of target blocks and -1 if not found
[ "Shallow", "indexOf", "implementation", "that", "only", "compares", "nodes", "based", "on", "their", "data", "and", "not", "their", "children", "data", "." ]
train
https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-transformations/xwiki-rendering-transformation-icon/src/main/java/org/xwiki/rendering/internal/transformation/icon/IconTransformation.java#L176-L187
centic9/commons-dost
src/main/java/org/dstadler/commons/date/DateParser.java
DateParser.timeToReadable
public static String timeToReadable(long millis, String suffix) { """ Format the given number of milliseconds as readable string, optionally appending a suffix. @param millis The number of milliseconds to print. @param suffix A suffix that is appended if the millis is &gt; 0, specify "" if not needed. @return The readable string """ StringBuilder builder = new StringBuilder(); boolean haveDays = false; if(millis > ONE_DAY) { millis = handleTime(builder, millis, ONE_DAY, "day", "s"); haveDays = true; } boolean haveHours = false; if(millis >= ONE_HOUR) { millis = handleTime(builder, millis, ONE_HOUR, "h", ""); haveHours = true; } if((!haveDays || !haveHours) && millis >= ONE_MINUTE) { millis = handleTime(builder, millis, ONE_MINUTE, "min", ""); } if(!haveDays && !haveHours && millis >= ONE_SECOND) { /*millis =*/ handleTime(builder, millis, ONE_SECOND, "s", ""); } if(builder.length() > 0) { // cut off trailing ", " builder.setLength(builder.length() - 2); builder.append(suffix); } return builder.toString(); }
java
public static String timeToReadable(long millis, String suffix) { StringBuilder builder = new StringBuilder(); boolean haveDays = false; if(millis > ONE_DAY) { millis = handleTime(builder, millis, ONE_DAY, "day", "s"); haveDays = true; } boolean haveHours = false; if(millis >= ONE_HOUR) { millis = handleTime(builder, millis, ONE_HOUR, "h", ""); haveHours = true; } if((!haveDays || !haveHours) && millis >= ONE_MINUTE) { millis = handleTime(builder, millis, ONE_MINUTE, "min", ""); } if(!haveDays && !haveHours && millis >= ONE_SECOND) { /*millis =*/ handleTime(builder, millis, ONE_SECOND, "s", ""); } if(builder.length() > 0) { // cut off trailing ", " builder.setLength(builder.length() - 2); builder.append(suffix); } return builder.toString(); }
[ "public", "static", "String", "timeToReadable", "(", "long", "millis", ",", "String", "suffix", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "haveDays", "=", "false", ";", "if", "(", "millis", ">", "ONE_DAY", ")", "{", "millis", "=", "handleTime", "(", "builder", ",", "millis", ",", "ONE_DAY", ",", "\"day\"", ",", "\"s\"", ")", ";", "haveDays", "=", "true", ";", "}", "boolean", "haveHours", "=", "false", ";", "if", "(", "millis", ">=", "ONE_HOUR", ")", "{", "millis", "=", "handleTime", "(", "builder", ",", "millis", ",", "ONE_HOUR", ",", "\"h\"", ",", "\"\"", ")", ";", "haveHours", "=", "true", ";", "}", "if", "(", "(", "!", "haveDays", "||", "!", "haveHours", ")", "&&", "millis", ">=", "ONE_MINUTE", ")", "{", "millis", "=", "handleTime", "(", "builder", ",", "millis", ",", "ONE_MINUTE", ",", "\"min\"", ",", "\"\"", ")", ";", "}", "if", "(", "!", "haveDays", "&&", "!", "haveHours", "&&", "millis", ">=", "ONE_SECOND", ")", "{", "/*millis =*/", "handleTime", "(", "builder", ",", "millis", ",", "ONE_SECOND", ",", "\"s\"", ",", "\"\"", ")", ";", "}", "if", "(", "builder", ".", "length", "(", ")", ">", "0", ")", "{", "// cut off trailing \", \"", "builder", ".", "setLength", "(", "builder", ".", "length", "(", ")", "-", "2", ")", ";", "builder", ".", "append", "(", "suffix", ")", ";", "}", "return", "builder", ".", "toString", "(", ")", ";", "}" ]
Format the given number of milliseconds as readable string, optionally appending a suffix. @param millis The number of milliseconds to print. @param suffix A suffix that is appended if the millis is &gt; 0, specify "" if not needed. @return The readable string
[ "Format", "the", "given", "number", "of", "milliseconds", "as", "readable", "string", "optionally", "appending", "a", "suffix", "." ]
train
https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/date/DateParser.java#L199-L228
jbundle/jcalendarbutton
src/main/java/org/jbundle/util/jcalendarbutton/JCalendarPopup.java
JCalendarPopup.getDateString
public String getDateString(Date dateTarget, int iDateFormat) { """ Convert this data to a string (using the supplied format). @param dateTarget The date to convert to a string. @param iDateFormat The format for the date. @return The date as a string. """ stringBuffer.setLength(0); FieldPosition fieldPosition = new FieldPosition(iDateFormat); String string = null; string = dateFormat.format(dateTarget, stringBuffer, fieldPosition).toString(); int iBegin = fieldPosition.getBeginIndex(); int iEnd = fieldPosition.getEndIndex(); string = string.substring(iBegin, iEnd); return string; }
java
public String getDateString(Date dateTarget, int iDateFormat) { stringBuffer.setLength(0); FieldPosition fieldPosition = new FieldPosition(iDateFormat); String string = null; string = dateFormat.format(dateTarget, stringBuffer, fieldPosition).toString(); int iBegin = fieldPosition.getBeginIndex(); int iEnd = fieldPosition.getEndIndex(); string = string.substring(iBegin, iEnd); return string; }
[ "public", "String", "getDateString", "(", "Date", "dateTarget", ",", "int", "iDateFormat", ")", "{", "stringBuffer", ".", "setLength", "(", "0", ")", ";", "FieldPosition", "fieldPosition", "=", "new", "FieldPosition", "(", "iDateFormat", ")", ";", "String", "string", "=", "null", ";", "string", "=", "dateFormat", ".", "format", "(", "dateTarget", ",", "stringBuffer", ",", "fieldPosition", ")", ".", "toString", "(", ")", ";", "int", "iBegin", "=", "fieldPosition", ".", "getBeginIndex", "(", ")", ";", "int", "iEnd", "=", "fieldPosition", ".", "getEndIndex", "(", ")", ";", "string", "=", "string", ".", "substring", "(", "iBegin", ",", "iEnd", ")", ";", "return", "string", ";", "}" ]
Convert this data to a string (using the supplied format). @param dateTarget The date to convert to a string. @param iDateFormat The format for the date. @return The date as a string.
[ "Convert", "this", "data", "to", "a", "string", "(", "using", "the", "supplied", "format", ")", "." ]
train
https://github.com/jbundle/jcalendarbutton/blob/2944e6a0b634b83768d5c0b7b4a2898176421403/src/main/java/org/jbundle/util/jcalendarbutton/JCalendarPopup.java#L468-L478
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java
AbstractBeanDefinition.preDestroy
@UsedByGeneratedCode protected Object preDestroy(BeanResolutionContext resolutionContext, BeanContext context, Object bean) { """ Default preDestroy hook that only invokes methods that require reflection. Generated subclasses should override to call methods that don't require reflection. @param resolutionContext The resolution hook @param context The context @param bean The bean @return The bean """ DefaultBeanContext defaultContext = (DefaultBeanContext) context; for (int i = 0; i < methodInjectionPoints.size(); i++) { MethodInjectionPoint methodInjectionPoint = methodInjectionPoints.get(i); if (methodInjectionPoint.isPreDestroyMethod() && methodInjectionPoint.requiresReflection()) { injectBeanMethod(resolutionContext, defaultContext, i, bean); } } if (bean instanceof LifeCycle) { bean = ((LifeCycle) bean).stop(); } return bean; }
java
@UsedByGeneratedCode protected Object preDestroy(BeanResolutionContext resolutionContext, BeanContext context, Object bean) { DefaultBeanContext defaultContext = (DefaultBeanContext) context; for (int i = 0; i < methodInjectionPoints.size(); i++) { MethodInjectionPoint methodInjectionPoint = methodInjectionPoints.get(i); if (methodInjectionPoint.isPreDestroyMethod() && methodInjectionPoint.requiresReflection()) { injectBeanMethod(resolutionContext, defaultContext, i, bean); } } if (bean instanceof LifeCycle) { bean = ((LifeCycle) bean).stop(); } return bean; }
[ "@", "UsedByGeneratedCode", "protected", "Object", "preDestroy", "(", "BeanResolutionContext", "resolutionContext", ",", "BeanContext", "context", ",", "Object", "bean", ")", "{", "DefaultBeanContext", "defaultContext", "=", "(", "DefaultBeanContext", ")", "context", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "methodInjectionPoints", ".", "size", "(", ")", ";", "i", "++", ")", "{", "MethodInjectionPoint", "methodInjectionPoint", "=", "methodInjectionPoints", ".", "get", "(", "i", ")", ";", "if", "(", "methodInjectionPoint", ".", "isPreDestroyMethod", "(", ")", "&&", "methodInjectionPoint", ".", "requiresReflection", "(", ")", ")", "{", "injectBeanMethod", "(", "resolutionContext", ",", "defaultContext", ",", "i", ",", "bean", ")", ";", "}", "}", "if", "(", "bean", "instanceof", "LifeCycle", ")", "{", "bean", "=", "(", "(", "LifeCycle", ")", "bean", ")", ".", "stop", "(", ")", ";", "}", "return", "bean", ";", "}" ]
Default preDestroy hook that only invokes methods that require reflection. Generated subclasses should override to call methods that don't require reflection. @param resolutionContext The resolution hook @param context The context @param bean The bean @return The bean
[ "Default", "preDestroy", "hook", "that", "only", "invokes", "methods", "that", "require", "reflection", ".", "Generated", "subclasses", "should", "override", "to", "call", "methods", "that", "don", "t", "require", "reflection", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java#L658-L672
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/common/utilities/PHPMethods.java
PHPMethods.preg_match
public static int preg_match(Pattern pattern, String subject) { """ Matches a string with a pattern. @param pattern @param subject @return """ int matches=0; Matcher m = pattern.matcher(subject); while(m.find()){ ++matches; } return matches; }
java
public static int preg_match(Pattern pattern, String subject) { int matches=0; Matcher m = pattern.matcher(subject); while(m.find()){ ++matches; } return matches; }
[ "public", "static", "int", "preg_match", "(", "Pattern", "pattern", ",", "String", "subject", ")", "{", "int", "matches", "=", "0", ";", "Matcher", "m", "=", "pattern", ".", "matcher", "(", "subject", ")", ";", "while", "(", "m", ".", "find", "(", ")", ")", "{", "++", "matches", ";", "}", "return", "matches", ";", "}" ]
Matches a string with a pattern. @param pattern @param subject @return
[ "Matches", "a", "string", "with", "a", "pattern", "." ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/common/utilities/PHPMethods.java#L149-L156
line/armeria
core/src/main/java/com/linecorp/armeria/common/metric/PrometheusMeterRegistries.java
PrometheusMeterRegistries.newRegistry
public static PrometheusMeterRegistry newRegistry(CollectorRegistry registry, Clock clock) { """ Returns a newly-created {@link PrometheusMeterRegistry} instance with the specified {@link CollectorRegistry} and {@link Clock}. """ final PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry( PrometheusConfig.DEFAULT, requireNonNull(registry, "registry"), requireNonNull(clock, "clock")); meterRegistry.config().namingConvention(MoreNamingConventions.prometheus()); meterRegistry.config().pauseDetector(new NoPauseDetector()); return meterRegistry; }
java
public static PrometheusMeterRegistry newRegistry(CollectorRegistry registry, Clock clock) { final PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry( PrometheusConfig.DEFAULT, requireNonNull(registry, "registry"), requireNonNull(clock, "clock")); meterRegistry.config().namingConvention(MoreNamingConventions.prometheus()); meterRegistry.config().pauseDetector(new NoPauseDetector()); return meterRegistry; }
[ "public", "static", "PrometheusMeterRegistry", "newRegistry", "(", "CollectorRegistry", "registry", ",", "Clock", "clock", ")", "{", "final", "PrometheusMeterRegistry", "meterRegistry", "=", "new", "PrometheusMeterRegistry", "(", "PrometheusConfig", ".", "DEFAULT", ",", "requireNonNull", "(", "registry", ",", "\"registry\"", ")", ",", "requireNonNull", "(", "clock", ",", "\"clock\"", ")", ")", ";", "meterRegistry", ".", "config", "(", ")", ".", "namingConvention", "(", "MoreNamingConventions", ".", "prometheus", "(", ")", ")", ";", "meterRegistry", ".", "config", "(", ")", ".", "pauseDetector", "(", "new", "NoPauseDetector", "(", ")", ")", ";", "return", "meterRegistry", ";", "}" ]
Returns a newly-created {@link PrometheusMeterRegistry} instance with the specified {@link CollectorRegistry} and {@link Clock}.
[ "Returns", "a", "newly", "-", "created", "{" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/common/metric/PrometheusMeterRegistries.java#L59-L65
m-m-m/util
reflect/src/main/java/net/sf/mmm/util/reflect/base/ReflectionUtilImpl.java
ReflectionUtilImpl.visitResourceNames
public void visitResourceNames(String packageName, boolean includeSubPackages, ClassLoader classLoader, ResourceVisitor visitor) { """ This method does the actual magic to locate resources on the classpath. @param packageName is the name of the {@link Package} to scan. Both "." and "/" are accepted as separator (e.g. "net.sf.mmm.util.reflect). @param includeSubPackages - if {@code true} all sub-packages of the specified {@link Package} will be included in the search. @param classLoader is the explicit {@link ClassLoader} to use. @param visitor is the {@link ResourceVisitor}. @if the operation failed with an I/O error. """ try { String path = packageName.replace('.', '/'); if (path.isEmpty()) { LOG.debug("Scanning entire classpath..."); } else { LOG.trace("Scanning for resources on classpath for {}", path); } StringBuilder qualifiedNameBuilder = new StringBuilder(path); if (qualifiedNameBuilder.length() > 0) { qualifiedNameBuilder.append('/'); } String pathWithPrefix = qualifiedNameBuilder.toString(); int qualifiedNamePrefixLength = qualifiedNameBuilder.length(); Enumeration<URL> urls = classLoader.getResources(path); Set<String> urlSet = new HashSet<>(); while (urls.hasMoreElements()) { URL url = urls.nextElement(); visitResourceUrl(includeSubPackages, visitor, pathWithPrefix, qualifiedNameBuilder, qualifiedNamePrefixLength, url, urlSet); } if (path.isEmpty()) { visitResourceClassloader(includeSubPackages, classLoader, visitor, pathWithPrefix, qualifiedNameBuilder, qualifiedNamePrefixLength, urlSet); visitResourceClasspath(includeSubPackages, visitor, qualifiedNameBuilder, pathWithPrefix, qualifiedNamePrefixLength, urlSet); } } catch (IOException e) { throw new IllegalStateException("Error reading resources.", e); } }
java
public void visitResourceNames(String packageName, boolean includeSubPackages, ClassLoader classLoader, ResourceVisitor visitor) { try { String path = packageName.replace('.', '/'); if (path.isEmpty()) { LOG.debug("Scanning entire classpath..."); } else { LOG.trace("Scanning for resources on classpath for {}", path); } StringBuilder qualifiedNameBuilder = new StringBuilder(path); if (qualifiedNameBuilder.length() > 0) { qualifiedNameBuilder.append('/'); } String pathWithPrefix = qualifiedNameBuilder.toString(); int qualifiedNamePrefixLength = qualifiedNameBuilder.length(); Enumeration<URL> urls = classLoader.getResources(path); Set<String> urlSet = new HashSet<>(); while (urls.hasMoreElements()) { URL url = urls.nextElement(); visitResourceUrl(includeSubPackages, visitor, pathWithPrefix, qualifiedNameBuilder, qualifiedNamePrefixLength, url, urlSet); } if (path.isEmpty()) { visitResourceClassloader(includeSubPackages, classLoader, visitor, pathWithPrefix, qualifiedNameBuilder, qualifiedNamePrefixLength, urlSet); visitResourceClasspath(includeSubPackages, visitor, qualifiedNameBuilder, pathWithPrefix, qualifiedNamePrefixLength, urlSet); } } catch (IOException e) { throw new IllegalStateException("Error reading resources.", e); } }
[ "public", "void", "visitResourceNames", "(", "String", "packageName", ",", "boolean", "includeSubPackages", ",", "ClassLoader", "classLoader", ",", "ResourceVisitor", "visitor", ")", "{", "try", "{", "String", "path", "=", "packageName", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "if", "(", "path", ".", "isEmpty", "(", ")", ")", "{", "LOG", ".", "debug", "(", "\"Scanning entire classpath...\"", ")", ";", "}", "else", "{", "LOG", ".", "trace", "(", "\"Scanning for resources on classpath for {}\"", ",", "path", ")", ";", "}", "StringBuilder", "qualifiedNameBuilder", "=", "new", "StringBuilder", "(", "path", ")", ";", "if", "(", "qualifiedNameBuilder", ".", "length", "(", ")", ">", "0", ")", "{", "qualifiedNameBuilder", ".", "append", "(", "'", "'", ")", ";", "}", "String", "pathWithPrefix", "=", "qualifiedNameBuilder", ".", "toString", "(", ")", ";", "int", "qualifiedNamePrefixLength", "=", "qualifiedNameBuilder", ".", "length", "(", ")", ";", "Enumeration", "<", "URL", ">", "urls", "=", "classLoader", ".", "getResources", "(", "path", ")", ";", "Set", "<", "String", ">", "urlSet", "=", "new", "HashSet", "<>", "(", ")", ";", "while", "(", "urls", ".", "hasMoreElements", "(", ")", ")", "{", "URL", "url", "=", "urls", ".", "nextElement", "(", ")", ";", "visitResourceUrl", "(", "includeSubPackages", ",", "visitor", ",", "pathWithPrefix", ",", "qualifiedNameBuilder", ",", "qualifiedNamePrefixLength", ",", "url", ",", "urlSet", ")", ";", "}", "if", "(", "path", ".", "isEmpty", "(", ")", ")", "{", "visitResourceClassloader", "(", "includeSubPackages", ",", "classLoader", ",", "visitor", ",", "pathWithPrefix", ",", "qualifiedNameBuilder", ",", "qualifiedNamePrefixLength", ",", "urlSet", ")", ";", "visitResourceClasspath", "(", "includeSubPackages", ",", "visitor", ",", "qualifiedNameBuilder", ",", "pathWithPrefix", ",", "qualifiedNamePrefixLength", ",", "urlSet", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Error reading resources.\"", ",", "e", ")", ";", "}", "}" ]
This method does the actual magic to locate resources on the classpath. @param packageName is the name of the {@link Package} to scan. Both "." and "/" are accepted as separator (e.g. "net.sf.mmm.util.reflect). @param includeSubPackages - if {@code true} all sub-packages of the specified {@link Package} will be included in the search. @param classLoader is the explicit {@link ClassLoader} to use. @param visitor is the {@link ResourceVisitor}. @if the operation failed with an I/O error.
[ "This", "method", "does", "the", "actual", "magic", "to", "locate", "resources", "on", "the", "classpath", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/reflect/src/main/java/net/sf/mmm/util/reflect/base/ReflectionUtilImpl.java#L731-L759
lessthanoptimal/BoofCV
main/boofcv-types/src/main/java/boofcv/struct/image/GrayF32.java
GrayF32.get
public float get(int x, int y) { """ Returns the value of the specified pixel. @param x pixel coordinate. @param y pixel coordinate. @return Pixel intensity value. """ if (!isInBounds(x, y)) throw new ImageAccessException("Requested pixel is out of bounds: ( " + x + " , " + y + " )"); return unsafe_get(x,y); }
java
public float get(int x, int y) { if (!isInBounds(x, y)) throw new ImageAccessException("Requested pixel is out of bounds: ( " + x + " , " + y + " )"); return unsafe_get(x,y); }
[ "public", "float", "get", "(", "int", "x", ",", "int", "y", ")", "{", "if", "(", "!", "isInBounds", "(", "x", ",", "y", ")", ")", "throw", "new", "ImageAccessException", "(", "\"Requested pixel is out of bounds: ( \"", "+", "x", "+", "\" , \"", "+", "y", "+", "\" )\"", ")", ";", "return", "unsafe_get", "(", "x", ",", "y", ")", ";", "}" ]
Returns the value of the specified pixel. @param x pixel coordinate. @param y pixel coordinate. @return Pixel intensity value.
[ "Returns", "the", "value", "of", "the", "specified", "pixel", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-types/src/main/java/boofcv/struct/image/GrayF32.java#L55-L60
codescape/bitvunit
bitvunit-core/src/main/java/de/codescape/bitvunit/BitvUnit.java
BitvUnit.assertAccessibility
public static void assertAccessibility(URL url, Testable testable) { """ JUnit Assertion to verify a {@link URL} instance for accessibility. @param url {@link java.net.URL} instance @param testable rule(s) to apply """ assertThat(url, is(compliantTo(testable))); }
java
public static void assertAccessibility(URL url, Testable testable) { assertThat(url, is(compliantTo(testable))); }
[ "public", "static", "void", "assertAccessibility", "(", "URL", "url", ",", "Testable", "testable", ")", "{", "assertThat", "(", "url", ",", "is", "(", "compliantTo", "(", "testable", ")", ")", ")", ";", "}" ]
JUnit Assertion to verify a {@link URL} instance for accessibility. @param url {@link java.net.URL} instance @param testable rule(s) to apply
[ "JUnit", "Assertion", "to", "verify", "a", "{", "@link", "URL", "}", "instance", "for", "accessibility", "." ]
train
https://github.com/codescape/bitvunit/blob/cef6d9af60d684e41294981c10b6d92c8f063a4e/bitvunit-core/src/main/java/de/codescape/bitvunit/BitvUnit.java#L88-L90
lightblue-platform/lightblue-migrator
facade/src/main/java/com/redhat/lightblue/migrator/facade/ConsistencyChecker.java
ConsistencyChecker.logInconsistency
private void logInconsistency(String parentThreadName, String callToLogInCaseOfInconsistency, String legacyJson, String lightblueJson, String diff) { """ /* Log inconsistencies based on following rules: If logResponseDataEnabled=true: - Log message < MAX_INCONSISTENCY_LOG_LENGTH to server.log. - Log message > MAX_INCONSISTENCY_LOG_LENGTH and diff <= MAX_INCONSISTENCY_LOG_LENGTH, log diff to server.log. - Otherwise log method name and parameters to server.log and full message to inconsistency.log. If logResponseDataEnabled=false: - diff <= MAX_INCONSISTENCY_LOG_LENGTH, log diff to server.log. - Otherwise log method name and parameters to server.log - Always log full message to inconsistency.log Logging inconsistencies at debug level since everything >= info would also appear in server.log """ String logMessage = String.format("[%s] Inconsistency found in %s.%s - diff: %s - legacyJson: %s, lightblueJson: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff, legacyJson, lightblueJson); if (logResponseDataEnabled) { if (logMessage.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(logMessage); } else if (diff != null && diff.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff)); hugeInconsistencyLog.debug(logMessage); } else { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - payload and diff is greater than %d bytes!", parentThreadName, implementationName, callToLogInCaseOfInconsistency, maxInconsistencyLogLength)); hugeInconsistencyLog.debug(logMessage); } } else { if (diff != null && diff.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff)); } else { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff is greater than %d bytes!", parentThreadName, implementationName, callToLogInCaseOfInconsistency, maxInconsistencyLogLength)); } // logData is turned off, log in inconsistency.log for debugging hugeInconsistencyLog.debug(logMessage); } }
java
private void logInconsistency(String parentThreadName, String callToLogInCaseOfInconsistency, String legacyJson, String lightblueJson, String diff) { String logMessage = String.format("[%s] Inconsistency found in %s.%s - diff: %s - legacyJson: %s, lightblueJson: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff, legacyJson, lightblueJson); if (logResponseDataEnabled) { if (logMessage.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(logMessage); } else if (diff != null && diff.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff)); hugeInconsistencyLog.debug(logMessage); } else { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - payload and diff is greater than %d bytes!", parentThreadName, implementationName, callToLogInCaseOfInconsistency, maxInconsistencyLogLength)); hugeInconsistencyLog.debug(logMessage); } } else { if (diff != null && diff.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff)); } else { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff is greater than %d bytes!", parentThreadName, implementationName, callToLogInCaseOfInconsistency, maxInconsistencyLogLength)); } // logData is turned off, log in inconsistency.log for debugging hugeInconsistencyLog.debug(logMessage); } }
[ "private", "void", "logInconsistency", "(", "String", "parentThreadName", ",", "String", "callToLogInCaseOfInconsistency", ",", "String", "legacyJson", ",", "String", "lightblueJson", ",", "String", "diff", ")", "{", "String", "logMessage", "=", "String", ".", "format", "(", "\"[%s] Inconsistency found in %s.%s - diff: %s - legacyJson: %s, lightblueJson: %s\"", ",", "parentThreadName", ",", "implementationName", ",", "callToLogInCaseOfInconsistency", ",", "diff", ",", "legacyJson", ",", "lightblueJson", ")", ";", "if", "(", "logResponseDataEnabled", ")", "{", "if", "(", "logMessage", ".", "length", "(", ")", "<=", "maxInconsistencyLogLength", ")", "{", "inconsistencyLog", ".", "warn", "(", "logMessage", ")", ";", "}", "else", "if", "(", "diff", "!=", "null", "&&", "diff", ".", "length", "(", ")", "<=", "maxInconsistencyLogLength", ")", "{", "inconsistencyLog", ".", "warn", "(", "String", ".", "format", "(", "\"[%s] Inconsistency found in %s.%s - diff: %s\"", ",", "parentThreadName", ",", "implementationName", ",", "callToLogInCaseOfInconsistency", ",", "diff", ")", ")", ";", "hugeInconsistencyLog", ".", "debug", "(", "logMessage", ")", ";", "}", "else", "{", "inconsistencyLog", ".", "warn", "(", "String", ".", "format", "(", "\"[%s] Inconsistency found in %s.%s - payload and diff is greater than %d bytes!\"", ",", "parentThreadName", ",", "implementationName", ",", "callToLogInCaseOfInconsistency", ",", "maxInconsistencyLogLength", ")", ")", ";", "hugeInconsistencyLog", ".", "debug", "(", "logMessage", ")", ";", "}", "}", "else", "{", "if", "(", "diff", "!=", "null", "&&", "diff", ".", "length", "(", ")", "<=", "maxInconsistencyLogLength", ")", "{", "inconsistencyLog", ".", "warn", "(", "String", ".", "format", "(", "\"[%s] Inconsistency found in %s.%s - diff: %s\"", ",", "parentThreadName", ",", "implementationName", ",", "callToLogInCaseOfInconsistency", ",", "diff", ")", ")", ";", "}", "else", "{", "inconsistencyLog", ".", "warn", "(", "String", ".", "format", "(", "\"[%s] Inconsistency found in %s.%s - diff is greater than %d bytes!\"", ",", "parentThreadName", ",", "implementationName", ",", "callToLogInCaseOfInconsistency", ",", "maxInconsistencyLogLength", ")", ")", ";", "}", "// logData is turned off, log in inconsistency.log for debugging", "hugeInconsistencyLog", ".", "debug", "(", "logMessage", ")", ";", "}", "}" ]
/* Log inconsistencies based on following rules: If logResponseDataEnabled=true: - Log message < MAX_INCONSISTENCY_LOG_LENGTH to server.log. - Log message > MAX_INCONSISTENCY_LOG_LENGTH and diff <= MAX_INCONSISTENCY_LOG_LENGTH, log diff to server.log. - Otherwise log method name and parameters to server.log and full message to inconsistency.log. If logResponseDataEnabled=false: - diff <= MAX_INCONSISTENCY_LOG_LENGTH, log diff to server.log. - Otherwise log method name and parameters to server.log - Always log full message to inconsistency.log Logging inconsistencies at debug level since everything >= info would also appear in server.log
[ "/", "*", "Log", "inconsistencies", "based", "on", "following", "rules", ":" ]
train
https://github.com/lightblue-platform/lightblue-migrator/blob/ec20748557b40d1f7851e1816d1b76dae48d2027/facade/src/main/java/com/redhat/lightblue/migrator/facade/ConsistencyChecker.java#L97-L118
onepf/OpenIAB
library/src/main/java/org/onepf/oms/SkuManager.java
SkuManager.mapSku
@NotNull public SkuManager mapSku(String sku, String storeName, @NotNull String storeSku) { """ Maps a store-specific SKU to an internal base SKU. The best approach is to use SKU like <code>com.companyname.application.item</code>. Such SKU fits most of stores, so it doesn't need to be mapped. If this approach is not applicable, use an internal application SKU in the code (usually it is a SKU for Google Play) and map SKU from other stores using this method. OpenIAB will map SKU in both directions, so you can use only your internal SKU @param sku - The internal SKU @param storeSku - The store-specific SKU. Shouldn't duplicate already mapped values @param storeName - @see {@link IOpenAppstore#getAppstoreName()} or {@link org.onepf.oms.OpenIabHelper#NAME_AMAZON} {@link org.onepf.oms.OpenIabHelper#NAME_GOOGLE} @return Instance of {@link org.onepf.oms.SkuManager}. @throws org.onepf.oms.SkuMappingException If mapping can't be done. @see #mapSku(String, java.util.Map) """ checkSkuMappingParams(sku, storeName, storeSku); Map<String, String> skuMap = sku2storeSkuMappings.get(storeName); if (skuMap == null) { skuMap = new HashMap<String, String>(); sku2storeSkuMappings.put(storeName, skuMap); } else if (skuMap.containsKey(sku)) { throw new SkuMappingException("Already specified SKU. sku: " + sku + " -> storeSku: " + skuMap.get(sku)); } Map<String, String> storeSkuMap = storeSku2skuMappings.get(storeName); if (storeSkuMap == null) { storeSkuMap = new HashMap<String, String>(); storeSku2skuMappings.put(storeName, storeSkuMap); } else if (storeSkuMap.get(storeSku) != null) { throw new SkuMappingException("Ambiguous SKU mapping. You try to map sku: " + sku + " -> storeSku: " + storeSku + ", that is already mapped to sku: " + storeSkuMap.get(storeSku)); } skuMap.put(sku, storeSku); storeSkuMap.put(storeSku, sku); return this; }
java
@NotNull public SkuManager mapSku(String sku, String storeName, @NotNull String storeSku) { checkSkuMappingParams(sku, storeName, storeSku); Map<String, String> skuMap = sku2storeSkuMappings.get(storeName); if (skuMap == null) { skuMap = new HashMap<String, String>(); sku2storeSkuMappings.put(storeName, skuMap); } else if (skuMap.containsKey(sku)) { throw new SkuMappingException("Already specified SKU. sku: " + sku + " -> storeSku: " + skuMap.get(sku)); } Map<String, String> storeSkuMap = storeSku2skuMappings.get(storeName); if (storeSkuMap == null) { storeSkuMap = new HashMap<String, String>(); storeSku2skuMappings.put(storeName, storeSkuMap); } else if (storeSkuMap.get(storeSku) != null) { throw new SkuMappingException("Ambiguous SKU mapping. You try to map sku: " + sku + " -> storeSku: " + storeSku + ", that is already mapped to sku: " + storeSkuMap.get(storeSku)); } skuMap.put(sku, storeSku); storeSkuMap.put(storeSku, sku); return this; }
[ "@", "NotNull", "public", "SkuManager", "mapSku", "(", "String", "sku", ",", "String", "storeName", ",", "@", "NotNull", "String", "storeSku", ")", "{", "checkSkuMappingParams", "(", "sku", ",", "storeName", ",", "storeSku", ")", ";", "Map", "<", "String", ",", "String", ">", "skuMap", "=", "sku2storeSkuMappings", ".", "get", "(", "storeName", ")", ";", "if", "(", "skuMap", "==", "null", ")", "{", "skuMap", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "sku2storeSkuMappings", ".", "put", "(", "storeName", ",", "skuMap", ")", ";", "}", "else", "if", "(", "skuMap", ".", "containsKey", "(", "sku", ")", ")", "{", "throw", "new", "SkuMappingException", "(", "\"Already specified SKU. sku: \"", "+", "sku", "+", "\" -> storeSku: \"", "+", "skuMap", ".", "get", "(", "sku", ")", ")", ";", "}", "Map", "<", "String", ",", "String", ">", "storeSkuMap", "=", "storeSku2skuMappings", ".", "get", "(", "storeName", ")", ";", "if", "(", "storeSkuMap", "==", "null", ")", "{", "storeSkuMap", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "storeSku2skuMappings", ".", "put", "(", "storeName", ",", "storeSkuMap", ")", ";", "}", "else", "if", "(", "storeSkuMap", ".", "get", "(", "storeSku", ")", "!=", "null", ")", "{", "throw", "new", "SkuMappingException", "(", "\"Ambiguous SKU mapping. You try to map sku: \"", "+", "sku", "+", "\" -> storeSku: \"", "+", "storeSku", "+", "\", that is already mapped to sku: \"", "+", "storeSkuMap", ".", "get", "(", "storeSku", ")", ")", ";", "}", "skuMap", ".", "put", "(", "sku", ",", "storeSku", ")", ";", "storeSkuMap", ".", "put", "(", "storeSku", ",", "sku", ")", ";", "return", "this", ";", "}" ]
Maps a store-specific SKU to an internal base SKU. The best approach is to use SKU like <code>com.companyname.application.item</code>. Such SKU fits most of stores, so it doesn't need to be mapped. If this approach is not applicable, use an internal application SKU in the code (usually it is a SKU for Google Play) and map SKU from other stores using this method. OpenIAB will map SKU in both directions, so you can use only your internal SKU @param sku - The internal SKU @param storeSku - The store-specific SKU. Shouldn't duplicate already mapped values @param storeName - @see {@link IOpenAppstore#getAppstoreName()} or {@link org.onepf.oms.OpenIabHelper#NAME_AMAZON} {@link org.onepf.oms.OpenIabHelper#NAME_GOOGLE} @return Instance of {@link org.onepf.oms.SkuManager}. @throws org.onepf.oms.SkuMappingException If mapping can't be done. @see #mapSku(String, java.util.Map)
[ "Maps", "a", "store", "-", "specific", "SKU", "to", "an", "internal", "base", "SKU", ".", "The", "best", "approach", "is", "to", "use", "SKU", "like", "<code", ">", "com", ".", "companyname", ".", "application", ".", "item<", "/", "code", ">", ".", "Such", "SKU", "fits", "most", "of", "stores", "so", "it", "doesn", "t", "need", "to", "be", "mapped", ".", "If", "this", "approach", "is", "not", "applicable", "use", "an", "internal", "application", "SKU", "in", "the", "code", "(", "usually", "it", "is", "a", "SKU", "for", "Google", "Play", ")", "and", "map", "SKU", "from", "other", "stores", "using", "this", "method", ".", "OpenIAB", "will", "map", "SKU", "in", "both", "directions", "so", "you", "can", "use", "only", "your", "internal", "SKU" ]
train
https://github.com/onepf/OpenIAB/blob/90552d53c5303b322940d96a0c4b7cb797d78760/library/src/main/java/org/onepf/oms/SkuManager.java#L72-L98
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ValueUtils.java
ValueUtils.convertDate
public static Date convertDate(JsonNode node, String dateTimeFormat) { """ Convert a {@link JsonNode} to {@link Date}. If the target node is a string, parse it as a {@link Date} using the specified date-time format. @param node @return @since 0.6.3.1 """ if (node instanceof POJONode) { return convertDate(DPathUtils.extractValue((POJONode) node), dateTimeFormat); } return node.isNumber() ? new Date(node.asLong()) : node.isTextual() ? DateFormatUtils.fromString(node.asText(), dateTimeFormat) : null; }
java
public static Date convertDate(JsonNode node, String dateTimeFormat) { if (node instanceof POJONode) { return convertDate(DPathUtils.extractValue((POJONode) node), dateTimeFormat); } return node.isNumber() ? new Date(node.asLong()) : node.isTextual() ? DateFormatUtils.fromString(node.asText(), dateTimeFormat) : null; }
[ "public", "static", "Date", "convertDate", "(", "JsonNode", "node", ",", "String", "dateTimeFormat", ")", "{", "if", "(", "node", "instanceof", "POJONode", ")", "{", "return", "convertDate", "(", "DPathUtils", ".", "extractValue", "(", "(", "POJONode", ")", "node", ")", ",", "dateTimeFormat", ")", ";", "}", "return", "node", ".", "isNumber", "(", ")", "?", "new", "Date", "(", "node", ".", "asLong", "(", ")", ")", ":", "node", ".", "isTextual", "(", ")", "?", "DateFormatUtils", ".", "fromString", "(", "node", ".", "asText", "(", ")", ",", "dateTimeFormat", ")", ":", "null", ";", "}" ]
Convert a {@link JsonNode} to {@link Date}. If the target node is a string, parse it as a {@link Date} using the specified date-time format. @param node @return @since 0.6.3.1
[ "Convert", "a", "{", "@link", "JsonNode", "}", "to", "{", "@link", "Date", "}", ".", "If", "the", "target", "node", "is", "a", "string", "parse", "it", "as", "a", "{", "@link", "Date", "}", "using", "the", "specified", "date", "-", "time", "format", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ValueUtils.java#L395-L402
akarnokd/ixjava
src/main/java/ix/Ix.java
Ix.nullCheck
protected static <U> U nullCheck(U value, String message) { """ Checks if the value is null and if so, throws a NullPointerException with the given message. @param <U> the value type @param value the value to check for null @param message the message to report in the exception @return the value """ if (value == null) { throw new NullPointerException(message); } return value; }
java
protected static <U> U nullCheck(U value, String message) { if (value == null) { throw new NullPointerException(message); } return value; }
[ "protected", "static", "<", "U", ">", "U", "nullCheck", "(", "U", "value", ",", "String", "message", ")", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "message", ")", ";", "}", "return", "value", ";", "}" ]
Checks if the value is null and if so, throws a NullPointerException with the given message. @param <U> the value type @param value the value to check for null @param message the message to report in the exception @return the value
[ "Checks", "if", "the", "value", "is", "null", "and", "if", "so", "throws", "a", "NullPointerException", "with", "the", "given", "message", "." ]
train
https://github.com/akarnokd/ixjava/blob/add721bba550c36541faa450e40a975bb65e78d7/src/main/java/ix/Ix.java#L2749-L2754
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/configuration/ArtifactHelpers.java
ArtifactHelpers.artifactsAreMatchingTypes
public static boolean artifactsAreMatchingTypes(Artifact first, Artifact second) { """ Checks to see if two artifacts are of the same type (but not necessarily the same version) @param first An Artifact @param second A comparison Artifact @return true if the Artifacts match, false if they don't """ return first.getGroupId().equals(second.getGroupId()) && first.getArtifactId().equals(second.getArtifactId()) && first.getExtension().equals(second.getExtension()) && first.getClassifier().equals(second.getClassifier()); }
java
public static boolean artifactsAreMatchingTypes(Artifact first, Artifact second) { return first.getGroupId().equals(second.getGroupId()) && first.getArtifactId().equals(second.getArtifactId()) && first.getExtension().equals(second.getExtension()) && first.getClassifier().equals(second.getClassifier()); }
[ "public", "static", "boolean", "artifactsAreMatchingTypes", "(", "Artifact", "first", ",", "Artifact", "second", ")", "{", "return", "first", ".", "getGroupId", "(", ")", ".", "equals", "(", "second", ".", "getGroupId", "(", ")", ")", "&&", "first", ".", "getArtifactId", "(", ")", ".", "equals", "(", "second", ".", "getArtifactId", "(", ")", ")", "&&", "first", ".", "getExtension", "(", ")", ".", "equals", "(", "second", ".", "getExtension", "(", ")", ")", "&&", "first", ".", "getClassifier", "(", ")", ".", "equals", "(", "second", ".", "getClassifier", "(", ")", ")", ";", "}" ]
Checks to see if two artifacts are of the same type (but not necessarily the same version) @param first An Artifact @param second A comparison Artifact @return true if the Artifacts match, false if they don't
[ "Checks", "to", "see", "if", "two", "artifacts", "are", "of", "the", "same", "type", "(", "but", "not", "necessarily", "the", "same", "version", ")" ]
train
https://github.com/jmeter-maven-plugin/jmeter-maven-plugin/blob/63dc8b49cc6b9542deb681e25a2ada6025ddbf6b/src/main/java/com/lazerycode/jmeter/configuration/ArtifactHelpers.java#L181-L186
Azure/azure-sdk-for-java
datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java
AccountsInner.beginUpdate
public DataLakeAnalyticsAccountInner beginUpdate(String resourceGroupName, String name, DataLakeAnalyticsAccountInner parameters) { """ Updates the Data Lake Analytics account object specified by the accountName with the contents of the account object. @param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account. @param name The name of the Data Lake Analytics account to update. @param parameters Parameters supplied to the update Data Lake Analytics account operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the DataLakeAnalyticsAccountInner object if successful. """ return beginUpdateWithServiceResponseAsync(resourceGroupName, name, parameters).toBlocking().single().body(); }
java
public DataLakeAnalyticsAccountInner beginUpdate(String resourceGroupName, String name, DataLakeAnalyticsAccountInner parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, name, parameters).toBlocking().single().body(); }
[ "public", "DataLakeAnalyticsAccountInner", "beginUpdate", "(", "String", "resourceGroupName", ",", "String", "name", ",", "DataLakeAnalyticsAccountInner", "parameters", ")", "{", "return", "beginUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Updates the Data Lake Analytics account object specified by the accountName with the contents of the account object. @param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account. @param name The name of the Data Lake Analytics account to update. @param parameters Parameters supplied to the update Data Lake Analytics account operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the DataLakeAnalyticsAccountInner object if successful.
[ "Updates", "the", "Data", "Lake", "Analytics", "account", "object", "specified", "by", "the", "accountName", "with", "the", "contents", "of", "the", "account", "object", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java#L2847-L2849
h2oai/h2o-2
src/main/java/water/Model.java
Model.getDomainMapping
public static int[][] getDomainMapping(String[] modelDom, String[] colDom, boolean exact) { """ Returns a mapping between values of model domains (<code>modelDom</code>) and given column domain. @see #getDomainMapping(String, String[], String[], boolean) """ return getDomainMapping(null, modelDom, colDom, exact); }
java
public static int[][] getDomainMapping(String[] modelDom, String[] colDom, boolean exact) { return getDomainMapping(null, modelDom, colDom, exact); }
[ "public", "static", "int", "[", "]", "[", "]", "getDomainMapping", "(", "String", "[", "]", "modelDom", ",", "String", "[", "]", "colDom", ",", "boolean", "exact", ")", "{", "return", "getDomainMapping", "(", "null", ",", "modelDom", ",", "colDom", ",", "exact", ")", ";", "}" ]
Returns a mapping between values of model domains (<code>modelDom</code>) and given column domain. @see #getDomainMapping(String, String[], String[], boolean)
[ "Returns", "a", "mapping", "between", "values", "of", "model", "domains", "(", "<code", ">", "modelDom<", "/", "code", ">", ")", "and", "given", "column", "domain", "." ]
train
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Model.java#L424-L426
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/handler/bundle/AbstractResourceBundleHandler.java
AbstractResourceBundleHandler.getResourceBundleChannel
public ReadableByteChannel getResourceBundleChannel(String bundleName, boolean gzipBundle) throws ResourceNotFoundException { """ Returns the readable byte channel from the bundle name @param bundleName the bundle name @param gzipBundle the flag indicating if we want to retrieve the gzip version or not @return the readable byte channel from the bundle name @throws ResourceNotFoundException if the resource is not found """ String tempFileName = getStoredBundlePath(bundleName, gzipBundle); InputStream is = getTemporaryResourceAsStream(tempFileName); return Channels.newChannel(is); }
java
public ReadableByteChannel getResourceBundleChannel(String bundleName, boolean gzipBundle) throws ResourceNotFoundException { String tempFileName = getStoredBundlePath(bundleName, gzipBundle); InputStream is = getTemporaryResourceAsStream(tempFileName); return Channels.newChannel(is); }
[ "public", "ReadableByteChannel", "getResourceBundleChannel", "(", "String", "bundleName", ",", "boolean", "gzipBundle", ")", "throws", "ResourceNotFoundException", "{", "String", "tempFileName", "=", "getStoredBundlePath", "(", "bundleName", ",", "gzipBundle", ")", ";", "InputStream", "is", "=", "getTemporaryResourceAsStream", "(", "tempFileName", ")", ";", "return", "Channels", ".", "newChannel", "(", "is", ")", ";", "}" ]
Returns the readable byte channel from the bundle name @param bundleName the bundle name @param gzipBundle the flag indicating if we want to retrieve the gzip version or not @return the readable byte channel from the bundle name @throws ResourceNotFoundException if the resource is not found
[ "Returns", "the", "readable", "byte", "channel", "from", "the", "bundle", "name" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/handler/bundle/AbstractResourceBundleHandler.java#L412-L418
lamydev/Android-Notification
core/src/zemin/notification/NotificationEntry.java
NotificationEntry.addAction
public void addAction(int icon, CharSequence title, Action.OnActionListener listener) { """ Add a action to this notification. Actions are typically displayed as a button adjacent to the notification content. @see android.app.Notification#addAction @param icon @param title @param listener """ addAction(icon, title, listener, null, null, null, null); }
java
public void addAction(int icon, CharSequence title, Action.OnActionListener listener) { addAction(icon, title, listener, null, null, null, null); }
[ "public", "void", "addAction", "(", "int", "icon", ",", "CharSequence", "title", ",", "Action", ".", "OnActionListener", "listener", ")", "{", "addAction", "(", "icon", ",", "title", ",", "listener", ",", "null", ",", "null", ",", "null", ",", "null", ")", ";", "}" ]
Add a action to this notification. Actions are typically displayed as a button adjacent to the notification content. @see android.app.Notification#addAction @param icon @param title @param listener
[ "Add", "a", "action", "to", "this", "notification", ".", "Actions", "are", "typically", "displayed", "as", "a", "button", "adjacent", "to", "the", "notification", "content", "." ]
train
https://github.com/lamydev/Android-Notification/blob/6d6571d2862cb6edbacf9a78125418f7d621c3f8/core/src/zemin/notification/NotificationEntry.java#L524-L526
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRoutePortsInner.java
ExpressRoutePortsInner.updateTags
public ExpressRoutePortInner updateTags(String resourceGroupName, String expressRoutePortName) { """ Update ExpressRoutePort tags. @param resourceGroupName The name of the resource group. @param expressRoutePortName The name of the ExpressRoutePort resource. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ExpressRoutePortInner object if successful. """ return updateTagsWithServiceResponseAsync(resourceGroupName, expressRoutePortName).toBlocking().last().body(); }
java
public ExpressRoutePortInner updateTags(String resourceGroupName, String expressRoutePortName) { return updateTagsWithServiceResponseAsync(resourceGroupName, expressRoutePortName).toBlocking().last().body(); }
[ "public", "ExpressRoutePortInner", "updateTags", "(", "String", "resourceGroupName", ",", "String", "expressRoutePortName", ")", "{", "return", "updateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "expressRoutePortName", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Update ExpressRoutePort tags. @param resourceGroupName The name of the resource group. @param expressRoutePortName The name of the ExpressRoutePort resource. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ExpressRoutePortInner object if successful.
[ "Update", "ExpressRoutePort", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRoutePortsInner.java#L529-L531
sagiegurari/fax4j
src/main/java/org/fax4j/spi/hylafax/HylaFaxClientSpi.java
HylaFaxClientSpi.resumeFaxJobImpl
@Override protected void resumeFaxJobImpl(FaxJob faxJob) { """ This function will resume an existing fax job. @param faxJob The fax job object containing the needed information """ //get fax job HylaFaxJob hylaFaxJob=(HylaFaxJob)faxJob; //get client HylaFAXClient client=this.getHylaFAXClient(); try { this.resumeFaxJob(hylaFaxJob,client); } catch(FaxException exception) { throw exception; } catch(Exception exception) { throw new FaxException("General error.",exception); } }
java
@Override protected void resumeFaxJobImpl(FaxJob faxJob) { //get fax job HylaFaxJob hylaFaxJob=(HylaFaxJob)faxJob; //get client HylaFAXClient client=this.getHylaFAXClient(); try { this.resumeFaxJob(hylaFaxJob,client); } catch(FaxException exception) { throw exception; } catch(Exception exception) { throw new FaxException("General error.",exception); } }
[ "@", "Override", "protected", "void", "resumeFaxJobImpl", "(", "FaxJob", "faxJob", ")", "{", "//get fax job", "HylaFaxJob", "hylaFaxJob", "=", "(", "HylaFaxJob", ")", "faxJob", ";", "//get client", "HylaFAXClient", "client", "=", "this", ".", "getHylaFAXClient", "(", ")", ";", "try", "{", "this", ".", "resumeFaxJob", "(", "hylaFaxJob", ",", "client", ")", ";", "}", "catch", "(", "FaxException", "exception", ")", "{", "throw", "exception", ";", "}", "catch", "(", "Exception", "exception", ")", "{", "throw", "new", "FaxException", "(", "\"General error.\"", ",", "exception", ")", ";", "}", "}" ]
This function will resume an existing fax job. @param faxJob The fax job object containing the needed information
[ "This", "function", "will", "resume", "an", "existing", "fax", "job", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/hylafax/HylaFaxClientSpi.java#L363-L384
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/StringUtils.java
StringUtils.propFileToProperties
public static Properties propFileToProperties(String filename) { """ This method reads in properties listed in a file in the format prop=value, one property per line. Although <code>Properties.load(InputStream)</code> exists, I implemented this method to trim the lines, something not implemented in the <code>load()</code> method. @param filename A properties file to read @return The corresponding Properties object """ Properties result = new Properties(); try { InputStream is = new BufferedInputStream(new FileInputStream(filename)); result.load(is); // trim all values for (Object propKey : result.keySet()){ String newVal = result.getProperty((String)propKey); result.setProperty((String)propKey,newVal.trim()); } is.close(); return result; } catch (IOException e) { throw new RuntimeIOException("propFileToProperties could not read properties file: " + filename, e); } }
java
public static Properties propFileToProperties(String filename) { Properties result = new Properties(); try { InputStream is = new BufferedInputStream(new FileInputStream(filename)); result.load(is); // trim all values for (Object propKey : result.keySet()){ String newVal = result.getProperty((String)propKey); result.setProperty((String)propKey,newVal.trim()); } is.close(); return result; } catch (IOException e) { throw new RuntimeIOException("propFileToProperties could not read properties file: " + filename, e); } }
[ "public", "static", "Properties", "propFileToProperties", "(", "String", "filename", ")", "{", "Properties", "result", "=", "new", "Properties", "(", ")", ";", "try", "{", "InputStream", "is", "=", "new", "BufferedInputStream", "(", "new", "FileInputStream", "(", "filename", ")", ")", ";", "result", ".", "load", "(", "is", ")", ";", "// trim all values\r", "for", "(", "Object", "propKey", ":", "result", ".", "keySet", "(", ")", ")", "{", "String", "newVal", "=", "result", ".", "getProperty", "(", "(", "String", ")", "propKey", ")", ";", "result", ".", "setProperty", "(", "(", "String", ")", "propKey", ",", "newVal", ".", "trim", "(", ")", ")", ";", "}", "is", ".", "close", "(", ")", ";", "return", "result", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeIOException", "(", "\"propFileToProperties could not read properties file: \"", "+", "filename", ",", "e", ")", ";", "}", "}" ]
This method reads in properties listed in a file in the format prop=value, one property per line. Although <code>Properties.load(InputStream)</code> exists, I implemented this method to trim the lines, something not implemented in the <code>load()</code> method. @param filename A properties file to read @return The corresponding Properties object
[ "This", "method", "reads", "in", "properties", "listed", "in", "a", "file", "in", "the", "format", "prop", "=", "value", "one", "property", "per", "line", ".", "Although", "<code", ">", "Properties", ".", "load", "(", "InputStream", ")", "<", "/", "code", ">", "exists", "I", "implemented", "this", "method", "to", "trim", "the", "lines", "something", "not", "implemented", "in", "the", "<code", ">", "load", "()", "<", "/", "code", ">", "method", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/StringUtils.java#L803-L818
alkacon/opencms-core
src/org/opencms/loader/CmsJspLoader.java
CmsJspLoader.showSource
protected void showSource(CmsObject cms, CmsResource file, HttpServletRequest req, HttpServletResponse res) throws CmsException, IOException { """ Delivers the plain uninterpreted resource with escaped XML.<p> This is intended for viewing historical versions.<p> @param cms the initialized CmsObject which provides user permissions @param file the requested OpenCms VFS resource @param req the servlet request @param res the servlet response @throws IOException might be thrown by the servlet environment @throws CmsException in case of errors accessing OpenCms functions """ CmsResource historyResource = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(req); if (historyResource == null) { historyResource = file; } CmsFile historyFile = cms.readFile(historyResource); String content = new String(historyFile.getContents()); // change the content-type header so that browsers show plain text res.setContentLength(content.length()); res.setContentType("text/plain"); Writer out = res.getWriter(); out.write(content); out.close(); }
java
protected void showSource(CmsObject cms, CmsResource file, HttpServletRequest req, HttpServletResponse res) throws CmsException, IOException { CmsResource historyResource = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(req); if (historyResource == null) { historyResource = file; } CmsFile historyFile = cms.readFile(historyResource); String content = new String(historyFile.getContents()); // change the content-type header so that browsers show plain text res.setContentLength(content.length()); res.setContentType("text/plain"); Writer out = res.getWriter(); out.write(content); out.close(); }
[ "protected", "void", "showSource", "(", "CmsObject", "cms", ",", "CmsResource", "file", ",", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "CmsException", ",", "IOException", "{", "CmsResource", "historyResource", "=", "(", "CmsResource", ")", "CmsHistoryResourceHandler", ".", "getHistoryResource", "(", "req", ")", ";", "if", "(", "historyResource", "==", "null", ")", "{", "historyResource", "=", "file", ";", "}", "CmsFile", "historyFile", "=", "cms", ".", "readFile", "(", "historyResource", ")", ";", "String", "content", "=", "new", "String", "(", "historyFile", ".", "getContents", "(", ")", ")", ";", "// change the content-type header so that browsers show plain text", "res", ".", "setContentLength", "(", "content", ".", "length", "(", ")", ")", ";", "res", ".", "setContentType", "(", "\"text/plain\"", ")", ";", "Writer", "out", "=", "res", ".", "getWriter", "(", ")", ";", "out", ".", "write", "(", "content", ")", ";", "out", ".", "close", "(", ")", ";", "}" ]
Delivers the plain uninterpreted resource with escaped XML.<p> This is intended for viewing historical versions.<p> @param cms the initialized CmsObject which provides user permissions @param file the requested OpenCms VFS resource @param req the servlet request @param res the servlet response @throws IOException might be thrown by the servlet environment @throws CmsException in case of errors accessing OpenCms functions
[ "Delivers", "the", "plain", "uninterpreted", "resource", "with", "escaped", "XML", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/loader/CmsJspLoader.java#L1625-L1641
saxsys/SynchronizeFX
synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/Listeners.java
Listeners.registerListenersOnEverything
public void registerListenersOnEverything(final Object object) { """ Registers listeners on all {@link Property} fields of all Objects contained in {@code model}. @param object The root of the object graph where to start registering listeners. """ try { // the removeListener() call ensures that the listener is not added more than once new PropertyVisitor(object) { @Override protected boolean visitSingleValueProperty(final Property<?> fieldValue) { fieldValue.removeListener(propertyListener); fieldValue.addListener(propertyListener); return true; } @Override protected boolean visitCollectionProperty(final ListProperty<?> fieldValue) { fieldValue.removeListener(listListener); fieldValue.addListener(listListener); return true; } @Override protected boolean visitCollectionProperty(final MapProperty<?, ?> fieldValue) { fieldValue.removeListener(mapListener); fieldValue.addListener(mapListener); return true; } @Override protected boolean visitCollectionProperty(final SetProperty<?> fieldValue) { fieldValue.removeListener(setListener); fieldValue.addListener(setListener); return false; } }; } catch (final IllegalAccessException e) { topology.onError(new SynchronizeFXException(e)); } catch (final SecurityException e) { topology.onError(new SynchronizeFXException( "Maybe you're JVM doesn't allow reflection for this application?", e)); } }
java
public void registerListenersOnEverything(final Object object) { try { // the removeListener() call ensures that the listener is not added more than once new PropertyVisitor(object) { @Override protected boolean visitSingleValueProperty(final Property<?> fieldValue) { fieldValue.removeListener(propertyListener); fieldValue.addListener(propertyListener); return true; } @Override protected boolean visitCollectionProperty(final ListProperty<?> fieldValue) { fieldValue.removeListener(listListener); fieldValue.addListener(listListener); return true; } @Override protected boolean visitCollectionProperty(final MapProperty<?, ?> fieldValue) { fieldValue.removeListener(mapListener); fieldValue.addListener(mapListener); return true; } @Override protected boolean visitCollectionProperty(final SetProperty<?> fieldValue) { fieldValue.removeListener(setListener); fieldValue.addListener(setListener); return false; } }; } catch (final IllegalAccessException e) { topology.onError(new SynchronizeFXException(e)); } catch (final SecurityException e) { topology.onError(new SynchronizeFXException( "Maybe you're JVM doesn't allow reflection for this application?", e)); } }
[ "public", "void", "registerListenersOnEverything", "(", "final", "Object", "object", ")", "{", "try", "{", "// the removeListener() call ensures that the listener is not added more than once", "new", "PropertyVisitor", "(", "object", ")", "{", "@", "Override", "protected", "boolean", "visitSingleValueProperty", "(", "final", "Property", "<", "?", ">", "fieldValue", ")", "{", "fieldValue", ".", "removeListener", "(", "propertyListener", ")", ";", "fieldValue", ".", "addListener", "(", "propertyListener", ")", ";", "return", "true", ";", "}", "@", "Override", "protected", "boolean", "visitCollectionProperty", "(", "final", "ListProperty", "<", "?", ">", "fieldValue", ")", "{", "fieldValue", ".", "removeListener", "(", "listListener", ")", ";", "fieldValue", ".", "addListener", "(", "listListener", ")", ";", "return", "true", ";", "}", "@", "Override", "protected", "boolean", "visitCollectionProperty", "(", "final", "MapProperty", "<", "?", ",", "?", ">", "fieldValue", ")", "{", "fieldValue", ".", "removeListener", "(", "mapListener", ")", ";", "fieldValue", ".", "addListener", "(", "mapListener", ")", ";", "return", "true", ";", "}", "@", "Override", "protected", "boolean", "visitCollectionProperty", "(", "final", "SetProperty", "<", "?", ">", "fieldValue", ")", "{", "fieldValue", ".", "removeListener", "(", "setListener", ")", ";", "fieldValue", ".", "addListener", "(", "setListener", ")", ";", "return", "false", ";", "}", "}", ";", "}", "catch", "(", "final", "IllegalAccessException", "e", ")", "{", "topology", ".", "onError", "(", "new", "SynchronizeFXException", "(", "e", ")", ")", ";", "}", "catch", "(", "final", "SecurityException", "e", ")", "{", "topology", ".", "onError", "(", "new", "SynchronizeFXException", "(", "\"Maybe you're JVM doesn't allow reflection for this application?\"", ",", "e", ")", ")", ";", "}", "}" ]
Registers listeners on all {@link Property} fields of all Objects contained in {@code model}. @param object The root of the object graph where to start registering listeners.
[ "Registers", "listeners", "on", "all", "{", "@link", "Property", "}", "fields", "of", "all", "Objects", "contained", "in", "{", "@code", "model", "}", "." ]
train
https://github.com/saxsys/SynchronizeFX/blob/f3683020e4749110b38514eb5bc73a247998b579/synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/Listeners.java#L106-L144
sagiegurari/fax4j
src/main/java/org/fax4j/spi/comm/RXTXCommPortAdapter.java
RXTXCommPortAdapter.getOutputStream
public OutputStream getOutputStream() { """ This function returns the output stream to the COMM port. @return The output stream """ OutputStream stream=null; try { stream=this.commPort.getOutputStream(); } catch(IOException exception) { throw new FaxException("Unable to extract output stream.",exception); } return stream; }
java
public OutputStream getOutputStream() { OutputStream stream=null; try { stream=this.commPort.getOutputStream(); } catch(IOException exception) { throw new FaxException("Unable to extract output stream.",exception); } return stream; }
[ "public", "OutputStream", "getOutputStream", "(", ")", "{", "OutputStream", "stream", "=", "null", ";", "try", "{", "stream", "=", "this", ".", "commPort", ".", "getOutputStream", "(", ")", ";", "}", "catch", "(", "IOException", "exception", ")", "{", "throw", "new", "FaxException", "(", "\"Unable to extract output stream.\"", ",", "exception", ")", ";", "}", "return", "stream", ";", "}" ]
This function returns the output stream to the COMM port. @return The output stream
[ "This", "function", "returns", "the", "output", "stream", "to", "the", "COMM", "port", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/comm/RXTXCommPortAdapter.java#L81-L94
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/measure/ws/ComponentAction.java
ComponentAction.addBestValuesToMeasures
private static void addBestValuesToMeasures(List<LiveMeasureDto> measures, ComponentDto component, Collection<MetricDto> metrics) { """ Conditions for best value measure: <ul> <li>component is a production file or test file</li> <li>metric is optimized for best value</li> </ul> """ if (!QUALIFIERS_ELIGIBLE_FOR_BEST_VALUE.contains(component.qualifier())) { return; } List<MetricDtoWithBestValue> metricWithBestValueList = metrics.stream() .filter(MetricDtoFunctions.isOptimizedForBestValue()) .map(MetricDtoWithBestValue::new) .collect(MoreCollectors.toList(metrics.size())); Map<Integer, LiveMeasureDto> measuresByMetricId = Maps.uniqueIndex(measures, LiveMeasureDto::getMetricId); for (MetricDtoWithBestValue metricWithBestValue : metricWithBestValueList) { if (measuresByMetricId.get(metricWithBestValue.getMetric().getId()) == null) { measures.add(metricWithBestValue.getBestValue()); } } }
java
private static void addBestValuesToMeasures(List<LiveMeasureDto> measures, ComponentDto component, Collection<MetricDto> metrics) { if (!QUALIFIERS_ELIGIBLE_FOR_BEST_VALUE.contains(component.qualifier())) { return; } List<MetricDtoWithBestValue> metricWithBestValueList = metrics.stream() .filter(MetricDtoFunctions.isOptimizedForBestValue()) .map(MetricDtoWithBestValue::new) .collect(MoreCollectors.toList(metrics.size())); Map<Integer, LiveMeasureDto> measuresByMetricId = Maps.uniqueIndex(measures, LiveMeasureDto::getMetricId); for (MetricDtoWithBestValue metricWithBestValue : metricWithBestValueList) { if (measuresByMetricId.get(metricWithBestValue.getMetric().getId()) == null) { measures.add(metricWithBestValue.getBestValue()); } } }
[ "private", "static", "void", "addBestValuesToMeasures", "(", "List", "<", "LiveMeasureDto", ">", "measures", ",", "ComponentDto", "component", ",", "Collection", "<", "MetricDto", ">", "metrics", ")", "{", "if", "(", "!", "QUALIFIERS_ELIGIBLE_FOR_BEST_VALUE", ".", "contains", "(", "component", ".", "qualifier", "(", ")", ")", ")", "{", "return", ";", "}", "List", "<", "MetricDtoWithBestValue", ">", "metricWithBestValueList", "=", "metrics", ".", "stream", "(", ")", ".", "filter", "(", "MetricDtoFunctions", ".", "isOptimizedForBestValue", "(", ")", ")", ".", "map", "(", "MetricDtoWithBestValue", "::", "new", ")", ".", "collect", "(", "MoreCollectors", ".", "toList", "(", "metrics", ".", "size", "(", ")", ")", ")", ";", "Map", "<", "Integer", ",", "LiveMeasureDto", ">", "measuresByMetricId", "=", "Maps", ".", "uniqueIndex", "(", "measures", ",", "LiveMeasureDto", "::", "getMetricId", ")", ";", "for", "(", "MetricDtoWithBestValue", "metricWithBestValue", ":", "metricWithBestValueList", ")", "{", "if", "(", "measuresByMetricId", ".", "get", "(", "metricWithBestValue", ".", "getMetric", "(", ")", ".", "getId", "(", ")", ")", "==", "null", ")", "{", "measures", ".", "add", "(", "metricWithBestValue", ".", "getBestValue", "(", ")", ")", ";", "}", "}", "}" ]
Conditions for best value measure: <ul> <li>component is a production file or test file</li> <li>metric is optimized for best value</li> </ul>
[ "Conditions", "for", "best", "value", "measure", ":", "<ul", ">", "<li", ">", "component", "is", "a", "production", "file", "or", "test", "file<", "/", "li", ">", "<li", ">", "metric", "is", "optimized", "for", "best", "value<", "/", "li", ">", "<", "/", "ul", ">" ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/measure/ws/ComponentAction.java#L218-L234
NordicSemiconductor/Android-DFU-Library
dfu/src/main/java/no/nordicsemi/android/dfu/ButtonlessDfuImpl.java
ButtonlessDfuImpl.getStatusCode
@SuppressWarnings("SameParameterValue") private int getStatusCode(final byte[] response, final int request) throws UnknownResponseException { """ Checks whether the response received is valid and returns the status code. @param response the response received from the DFU device. @param request the expected Op Code. @return The status code. @throws UnknownResponseException if response was not valid. """ if (response == null || response.length < 3 || response[0] != OP_CODE_RESPONSE_CODE_KEY || response[1] != request || (response[2] != DFU_STATUS_SUCCESS && response[2] != SecureDfuError.BUTTONLESS_ERROR_OP_CODE_NOT_SUPPORTED && response[2] != SecureDfuError.BUTTONLESS_ERROR_OPERATION_FAILED)) throw new UnknownResponseException("Invalid response received", response, OP_CODE_RESPONSE_CODE_KEY, request); return response[2]; }
java
@SuppressWarnings("SameParameterValue") private int getStatusCode(final byte[] response, final int request) throws UnknownResponseException { if (response == null || response.length < 3 || response[0] != OP_CODE_RESPONSE_CODE_KEY || response[1] != request || (response[2] != DFU_STATUS_SUCCESS && response[2] != SecureDfuError.BUTTONLESS_ERROR_OP_CODE_NOT_SUPPORTED && response[2] != SecureDfuError.BUTTONLESS_ERROR_OPERATION_FAILED)) throw new UnknownResponseException("Invalid response received", response, OP_CODE_RESPONSE_CODE_KEY, request); return response[2]; }
[ "@", "SuppressWarnings", "(", "\"SameParameterValue\"", ")", "private", "int", "getStatusCode", "(", "final", "byte", "[", "]", "response", ",", "final", "int", "request", ")", "throws", "UnknownResponseException", "{", "if", "(", "response", "==", "null", "||", "response", ".", "length", "<", "3", "||", "response", "[", "0", "]", "!=", "OP_CODE_RESPONSE_CODE_KEY", "||", "response", "[", "1", "]", "!=", "request", "||", "(", "response", "[", "2", "]", "!=", "DFU_STATUS_SUCCESS", "&&", "response", "[", "2", "]", "!=", "SecureDfuError", ".", "BUTTONLESS_ERROR_OP_CODE_NOT_SUPPORTED", "&&", "response", "[", "2", "]", "!=", "SecureDfuError", ".", "BUTTONLESS_ERROR_OPERATION_FAILED", ")", ")", "throw", "new", "UnknownResponseException", "(", "\"Invalid response received\"", ",", "response", ",", "OP_CODE_RESPONSE_CODE_KEY", ",", "request", ")", ";", "return", "response", "[", "2", "]", ";", "}" ]
Checks whether the response received is valid and returns the status code. @param response the response received from the DFU device. @param request the expected Op Code. @return The status code. @throws UnknownResponseException if response was not valid.
[ "Checks", "whether", "the", "response", "received", "is", "valid", "and", "returns", "the", "status", "code", "." ]
train
https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/ButtonlessDfuImpl.java#L178-L185
before/uadetector
modules/uadetector-core/src/main/java/net/sf/uadetector/datastore/CachingXmlDataStore.java
CachingXmlDataStore.createCachingXmlDataStore
@Nonnull @Deprecated public static CachingXmlDataStore createCachingXmlDataStore(@Nonnull final File cacheFile, @Nonnull final DataStore fallback) { """ Constructs a new instance of {@code CachingXmlDataStore} with the given arguments. The given {@code cacheFile} can be empty or filled with previously cached data in XML format. The file must be writable otherwise an exception will be thrown. @param cacheFile file with cached <em>UAS data</em> in XML format or empty file @param fallback <em>UAS data</em> as fallback in case the data on the specified resource can not be read correctly @return new instance of {@link CachingXmlDataStore} @throws net.sf.qualitycheck.exception.IllegalNullArgumentException if one of the given arguments is {@code null} @throws net.sf.qualitycheck.exception.IllegalStateOfArgumentException if the given cache file can not be read @throws net.sf.qualitycheck.exception.IllegalStateOfArgumentException if no URL can be resolved to the given given file """ return createCachingXmlDataStore(cacheFile, UrlUtil.build(DEFAULT_DATA_URL), UrlUtil.build(DEFAULT_VERSION_URL), DEFAULT_CHARSET, fallback); }
java
@Nonnull @Deprecated public static CachingXmlDataStore createCachingXmlDataStore(@Nonnull final File cacheFile, @Nonnull final DataStore fallback) { return createCachingXmlDataStore(cacheFile, UrlUtil.build(DEFAULT_DATA_URL), UrlUtil.build(DEFAULT_VERSION_URL), DEFAULT_CHARSET, fallback); }
[ "@", "Nonnull", "@", "Deprecated", "public", "static", "CachingXmlDataStore", "createCachingXmlDataStore", "(", "@", "Nonnull", "final", "File", "cacheFile", ",", "@", "Nonnull", "final", "DataStore", "fallback", ")", "{", "return", "createCachingXmlDataStore", "(", "cacheFile", ",", "UrlUtil", ".", "build", "(", "DEFAULT_DATA_URL", ")", ",", "UrlUtil", ".", "build", "(", "DEFAULT_VERSION_URL", ")", ",", "DEFAULT_CHARSET", ",", "fallback", ")", ";", "}" ]
Constructs a new instance of {@code CachingXmlDataStore} with the given arguments. The given {@code cacheFile} can be empty or filled with previously cached data in XML format. The file must be writable otherwise an exception will be thrown. @param cacheFile file with cached <em>UAS data</em> in XML format or empty file @param fallback <em>UAS data</em> as fallback in case the data on the specified resource can not be read correctly @return new instance of {@link CachingXmlDataStore} @throws net.sf.qualitycheck.exception.IllegalNullArgumentException if one of the given arguments is {@code null} @throws net.sf.qualitycheck.exception.IllegalStateOfArgumentException if the given cache file can not be read @throws net.sf.qualitycheck.exception.IllegalStateOfArgumentException if no URL can be resolved to the given given file
[ "Constructs", "a", "new", "instance", "of", "{", "@code", "CachingXmlDataStore", "}", "with", "the", "given", "arguments", ".", "The", "given", "{", "@code", "cacheFile", "}", "can", "be", "empty", "or", "filled", "with", "previously", "cached", "data", "in", "XML", "format", ".", "The", "file", "must", "be", "writable", "otherwise", "an", "exception", "will", "be", "thrown", "." ]
train
https://github.com/before/uadetector/blob/215fb652723c52866572cff885f52a3fe67b9db5/modules/uadetector-core/src/main/java/net/sf/uadetector/datastore/CachingXmlDataStore.java#L143-L148
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotStore.java
SnapshotStore.loadSnapshots
private Collection<Snapshot> loadSnapshots() { """ Loads all available snapshots from disk. @return A list of available snapshots. """ // Ensure log directories are created. storage.directory().mkdirs(); List<Snapshot> snapshots = new ArrayList<>(); // Iterate through all files in the log directory. for (File file : storage.directory().listFiles(File::isFile)) { // If the file looks like a segment file, attempt to load the segment. if (SnapshotFile.isSnapshotFile(file)) { SnapshotFile snapshotFile = new SnapshotFile(file); SnapshotDescriptor descriptor = new SnapshotDescriptor(FileBuffer.allocate(file, SnapshotDescriptor.BYTES)); // Valid segments will have been locked. Segments that resulting from failures during log cleaning will be // unlocked and should ultimately be deleted from disk. if (descriptor.isLocked()) { log.debug("Loaded disk snapshot: {} ({})", descriptor.index(), snapshotFile.file().getName()); snapshots.add(new FileSnapshot(snapshotFile, descriptor, this)); descriptor.close(); } // If the segment descriptor wasn't locked, close and delete the descriptor. else { log.debug("Deleting partial snapshot: {} ({})", descriptor.index(), snapshotFile.file().getName()); descriptor.close(); descriptor.delete(); } } } return snapshots; }
java
private Collection<Snapshot> loadSnapshots() { // Ensure log directories are created. storage.directory().mkdirs(); List<Snapshot> snapshots = new ArrayList<>(); // Iterate through all files in the log directory. for (File file : storage.directory().listFiles(File::isFile)) { // If the file looks like a segment file, attempt to load the segment. if (SnapshotFile.isSnapshotFile(file)) { SnapshotFile snapshotFile = new SnapshotFile(file); SnapshotDescriptor descriptor = new SnapshotDescriptor(FileBuffer.allocate(file, SnapshotDescriptor.BYTES)); // Valid segments will have been locked. Segments that resulting from failures during log cleaning will be // unlocked and should ultimately be deleted from disk. if (descriptor.isLocked()) { log.debug("Loaded disk snapshot: {} ({})", descriptor.index(), snapshotFile.file().getName()); snapshots.add(new FileSnapshot(snapshotFile, descriptor, this)); descriptor.close(); } // If the segment descriptor wasn't locked, close and delete the descriptor. else { log.debug("Deleting partial snapshot: {} ({})", descriptor.index(), snapshotFile.file().getName()); descriptor.close(); descriptor.delete(); } } } return snapshots; }
[ "private", "Collection", "<", "Snapshot", ">", "loadSnapshots", "(", ")", "{", "// Ensure log directories are created.", "storage", ".", "directory", "(", ")", ".", "mkdirs", "(", ")", ";", "List", "<", "Snapshot", ">", "snapshots", "=", "new", "ArrayList", "<>", "(", ")", ";", "// Iterate through all files in the log directory.", "for", "(", "File", "file", ":", "storage", ".", "directory", "(", ")", ".", "listFiles", "(", "File", "::", "isFile", ")", ")", "{", "// If the file looks like a segment file, attempt to load the segment.", "if", "(", "SnapshotFile", ".", "isSnapshotFile", "(", "file", ")", ")", "{", "SnapshotFile", "snapshotFile", "=", "new", "SnapshotFile", "(", "file", ")", ";", "SnapshotDescriptor", "descriptor", "=", "new", "SnapshotDescriptor", "(", "FileBuffer", ".", "allocate", "(", "file", ",", "SnapshotDescriptor", ".", "BYTES", ")", ")", ";", "// Valid segments will have been locked. Segments that resulting from failures during log cleaning will be", "// unlocked and should ultimately be deleted from disk.", "if", "(", "descriptor", ".", "isLocked", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Loaded disk snapshot: {} ({})\"", ",", "descriptor", ".", "index", "(", ")", ",", "snapshotFile", ".", "file", "(", ")", ".", "getName", "(", ")", ")", ";", "snapshots", ".", "add", "(", "new", "FileSnapshot", "(", "snapshotFile", ",", "descriptor", ",", "this", ")", ")", ";", "descriptor", ".", "close", "(", ")", ";", "}", "// If the segment descriptor wasn't locked, close and delete the descriptor.", "else", "{", "log", ".", "debug", "(", "\"Deleting partial snapshot: {} ({})\"", ",", "descriptor", ".", "index", "(", ")", ",", "snapshotFile", ".", "file", "(", ")", ".", "getName", "(", ")", ")", ";", "descriptor", ".", "close", "(", ")", ";", "descriptor", ".", "delete", "(", ")", ";", "}", "}", "}", "return", "snapshots", ";", "}" ]
Loads all available snapshots from disk. @return A list of available snapshots.
[ "Loads", "all", "available", "snapshots", "from", "disk", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotStore.java#L116-L147
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/grpc/AbstractWriteHandler.java
AbstractWriteHandler.writeDataMessage
public void writeDataMessage(WriteRequest request, DataBuffer buffer) { """ Handles write request with data message. @param request the request from the client @param buffer the data associated with the request """ if (buffer == null) { write(request); return; } Preconditions.checkState(!request.hasCommand(), "write request command should not come with data buffer"); Preconditions.checkState(buffer.readableBytes() > 0, "invalid data size from write request message"); if (!tryAcquireSemaphore()) { return; } mSerializingExecutor.execute(() -> { try { writeData(buffer); } finally { mSemaphore.release(); } }); }
java
public void writeDataMessage(WriteRequest request, DataBuffer buffer) { if (buffer == null) { write(request); return; } Preconditions.checkState(!request.hasCommand(), "write request command should not come with data buffer"); Preconditions.checkState(buffer.readableBytes() > 0, "invalid data size from write request message"); if (!tryAcquireSemaphore()) { return; } mSerializingExecutor.execute(() -> { try { writeData(buffer); } finally { mSemaphore.release(); } }); }
[ "public", "void", "writeDataMessage", "(", "WriteRequest", "request", ",", "DataBuffer", "buffer", ")", "{", "if", "(", "buffer", "==", "null", ")", "{", "write", "(", "request", ")", ";", "return", ";", "}", "Preconditions", ".", "checkState", "(", "!", "request", ".", "hasCommand", "(", ")", ",", "\"write request command should not come with data buffer\"", ")", ";", "Preconditions", ".", "checkState", "(", "buffer", ".", "readableBytes", "(", ")", ">", "0", ",", "\"invalid data size from write request message\"", ")", ";", "if", "(", "!", "tryAcquireSemaphore", "(", ")", ")", "{", "return", ";", "}", "mSerializingExecutor", ".", "execute", "(", "(", ")", "->", "{", "try", "{", "writeData", "(", "buffer", ")", ";", "}", "finally", "{", "mSemaphore", ".", "release", "(", ")", ";", "}", "}", ")", ";", "}" ]
Handles write request with data message. @param request the request from the client @param buffer the data associated with the request
[ "Handles", "write", "request", "with", "data", "message", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/grpc/AbstractWriteHandler.java#L149-L168
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/DefaultFontMapper.java
DefaultFontMapper.insertNames
public void insertNames(Object allNames[], String path) { """ Inserts the names in this map. @param allNames the returned value of calling {@link BaseFont#getAllFontNames(String, String, byte[])} @param path the full path to the font """ String names[][] = (String[][])allNames[2]; String main = null; for (int k = 0; k < names.length; ++k) { String name[] = names[k]; if (name[2].equals("1033")) { main = name[3]; break; } } if (main == null) main = names[0][3]; BaseFontParameters p = new BaseFontParameters(path); mapper.put(main, p); for (int k = 0; k < names.length; ++k) { aliases.put(names[k][3], main); } aliases.put(allNames[0], main); }
java
public void insertNames(Object allNames[], String path) { String names[][] = (String[][])allNames[2]; String main = null; for (int k = 0; k < names.length; ++k) { String name[] = names[k]; if (name[2].equals("1033")) { main = name[3]; break; } } if (main == null) main = names[0][3]; BaseFontParameters p = new BaseFontParameters(path); mapper.put(main, p); for (int k = 0; k < names.length; ++k) { aliases.put(names[k][3], main); } aliases.put(allNames[0], main); }
[ "public", "void", "insertNames", "(", "Object", "allNames", "[", "]", ",", "String", "path", ")", "{", "String", "names", "[", "]", "[", "]", "=", "(", "String", "[", "]", "[", "]", ")", "allNames", "[", "2", "]", ";", "String", "main", "=", "null", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "names", ".", "length", ";", "++", "k", ")", "{", "String", "name", "[", "]", "=", "names", "[", "k", "]", ";", "if", "(", "name", "[", "2", "]", ".", "equals", "(", "\"1033\"", ")", ")", "{", "main", "=", "name", "[", "3", "]", ";", "break", ";", "}", "}", "if", "(", "main", "==", "null", ")", "main", "=", "names", "[", "0", "]", "[", "3", "]", ";", "BaseFontParameters", "p", "=", "new", "BaseFontParameters", "(", "path", ")", ";", "mapper", ".", "put", "(", "main", ",", "p", ")", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "names", ".", "length", ";", "++", "k", ")", "{", "aliases", ".", "put", "(", "names", "[", "k", "]", "[", "3", "]", ",", "main", ")", ";", "}", "aliases", ".", "put", "(", "allNames", "[", "0", "]", ",", "main", ")", ";", "}" ]
Inserts the names in this map. @param allNames the returned value of calling {@link BaseFont#getAllFontNames(String, String, byte[])} @param path the full path to the font
[ "Inserts", "the", "names", "in", "this", "map", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/DefaultFontMapper.java#L244-L262
pippo-java/pippo
pippo-core/src/main/java/ro/pippo/core/PippoSettings.java
PippoSettings.overrideSetting
public void overrideSetting(String name, long value) { """ Override the setting at runtime with the specified value. This change does not persist. @param name @param value """ overrides.put(name, Long.toString(value)); }
java
public void overrideSetting(String name, long value) { overrides.put(name, Long.toString(value)); }
[ "public", "void", "overrideSetting", "(", "String", "name", ",", "long", "value", ")", "{", "overrides", ".", "put", "(", "name", ",", "Long", ".", "toString", "(", "value", ")", ")", ";", "}" ]
Override the setting at runtime with the specified value. This change does not persist. @param name @param value
[ "Override", "the", "setting", "at", "runtime", "with", "the", "specified", "value", ".", "This", "change", "does", "not", "persist", "." ]
train
https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/PippoSettings.java#L1056-L1058
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/DatabaseVulnerabilityAssessmentRuleBaselinesInner.java
DatabaseVulnerabilityAssessmentRuleBaselinesInner.getAsync
public Observable<DatabaseVulnerabilityAssessmentRuleBaselineInner> getAsync(String resourceGroupName, String serverName, String databaseName, String ruleId, VulnerabilityAssessmentPolicyBaselineName baselineName) { """ Gets a database's vulnerability assessment rule baseline. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database for which the vulnerability assessment rule baseline is defined. @param ruleId The vulnerability assessment rule ID. @param baselineName The name of the vulnerability assessment rule baseline (default implies a baseline on a database level rule and master for server level rule). Possible values include: 'master', 'default' @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DatabaseVulnerabilityAssessmentRuleBaselineInner object """ return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, ruleId, baselineName).map(new Func1<ServiceResponse<DatabaseVulnerabilityAssessmentRuleBaselineInner>, DatabaseVulnerabilityAssessmentRuleBaselineInner>() { @Override public DatabaseVulnerabilityAssessmentRuleBaselineInner call(ServiceResponse<DatabaseVulnerabilityAssessmentRuleBaselineInner> response) { return response.body(); } }); }
java
public Observable<DatabaseVulnerabilityAssessmentRuleBaselineInner> getAsync(String resourceGroupName, String serverName, String databaseName, String ruleId, VulnerabilityAssessmentPolicyBaselineName baselineName) { return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, ruleId, baselineName).map(new Func1<ServiceResponse<DatabaseVulnerabilityAssessmentRuleBaselineInner>, DatabaseVulnerabilityAssessmentRuleBaselineInner>() { @Override public DatabaseVulnerabilityAssessmentRuleBaselineInner call(ServiceResponse<DatabaseVulnerabilityAssessmentRuleBaselineInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DatabaseVulnerabilityAssessmentRuleBaselineInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "databaseName", ",", "String", "ruleId", ",", "VulnerabilityAssessmentPolicyBaselineName", "baselineName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "databaseName", ",", "ruleId", ",", "baselineName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "DatabaseVulnerabilityAssessmentRuleBaselineInner", ">", ",", "DatabaseVulnerabilityAssessmentRuleBaselineInner", ">", "(", ")", "{", "@", "Override", "public", "DatabaseVulnerabilityAssessmentRuleBaselineInner", "call", "(", "ServiceResponse", "<", "DatabaseVulnerabilityAssessmentRuleBaselineInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets a database's vulnerability assessment rule baseline. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database for which the vulnerability assessment rule baseline is defined. @param ruleId The vulnerability assessment rule ID. @param baselineName The name of the vulnerability assessment rule baseline (default implies a baseline on a database level rule and master for server level rule). Possible values include: 'master', 'default' @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DatabaseVulnerabilityAssessmentRuleBaselineInner object
[ "Gets", "a", "database", "s", "vulnerability", "assessment", "rule", "baseline", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/DatabaseVulnerabilityAssessmentRuleBaselinesInner.java#L119-L126
lecousin/java-framework-core
net.lecousin.core/src/main/java/net/lecousin/framework/memory/Cache.java
Cache.put
public synchronized void put(Key key, Value value, CloseableListenable firstUser) { """ Add the given data to this cache, and add the given first user to it. """ if (map.containsKey(key)) throw new IllegalStateException("Cannot put a value in Cache with an existing key: " + key); if (values.containsKey(value)) throw new IllegalStateException("Cannot put 2 times the same value in Cache: " + value); Data<Value> data = new Data<Value>(); data.value = value; data.lastUsage = System.currentTimeMillis(); data.users.add(firstUser); map.put(key, data); values.put(value, data); }
java
public synchronized void put(Key key, Value value, CloseableListenable firstUser) { if (map.containsKey(key)) throw new IllegalStateException("Cannot put a value in Cache with an existing key: " + key); if (values.containsKey(value)) throw new IllegalStateException("Cannot put 2 times the same value in Cache: " + value); Data<Value> data = new Data<Value>(); data.value = value; data.lastUsage = System.currentTimeMillis(); data.users.add(firstUser); map.put(key, data); values.put(value, data); }
[ "public", "synchronized", "void", "put", "(", "Key", "key", ",", "Value", "value", ",", "CloseableListenable", "firstUser", ")", "{", "if", "(", "map", ".", "containsKey", "(", "key", ")", ")", "throw", "new", "IllegalStateException", "(", "\"Cannot put a value in Cache with an existing key: \"", "+", "key", ")", ";", "if", "(", "values", ".", "containsKey", "(", "value", ")", ")", "throw", "new", "IllegalStateException", "(", "\"Cannot put 2 times the same value in Cache: \"", "+", "value", ")", ";", "Data", "<", "Value", ">", "data", "=", "new", "Data", "<", "Value", ">", "(", ")", ";", "data", ".", "value", "=", "value", ";", "data", ".", "lastUsage", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "data", ".", "users", ".", "add", "(", "firstUser", ")", ";", "map", ".", "put", "(", "key", ",", "data", ")", ";", "values", ".", "put", "(", "value", ",", "data", ")", ";", "}" ]
Add the given data to this cache, and add the given first user to it.
[ "Add", "the", "given", "data", "to", "this", "cache", "and", "add", "the", "given", "first", "user", "to", "it", "." ]
train
https://github.com/lecousin/java-framework-core/blob/b0c893b44bfde2c03f90ea846a49ef5749d598f3/net.lecousin.core/src/main/java/net/lecousin/framework/memory/Cache.java#L75-L86
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/earth/ST_SunPosition.java
ST_SunPosition.sunPosition
public static Geometry sunPosition(Geometry point, Date date) throws IllegalArgumentException { """ Return the sun position for a given date @param point @param date @return @throws IllegalArgumentException """ if(point == null){ return null; } if (point instanceof Point) { Coordinate coord = point.getCoordinate(); return point.getFactory().createPoint( SunCalc.getPosition(date, coord.y, coord.x)); } else { throw new IllegalArgumentException("The sun position is computed according a point location."); } }
java
public static Geometry sunPosition(Geometry point, Date date) throws IllegalArgumentException{ if(point == null){ return null; } if (point instanceof Point) { Coordinate coord = point.getCoordinate(); return point.getFactory().createPoint( SunCalc.getPosition(date, coord.y, coord.x)); } else { throw new IllegalArgumentException("The sun position is computed according a point location."); } }
[ "public", "static", "Geometry", "sunPosition", "(", "Geometry", "point", ",", "Date", "date", ")", "throws", "IllegalArgumentException", "{", "if", "(", "point", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "point", "instanceof", "Point", ")", "{", "Coordinate", "coord", "=", "point", ".", "getCoordinate", "(", ")", ";", "return", "point", ".", "getFactory", "(", ")", ".", "createPoint", "(", "SunCalc", ".", "getPosition", "(", "date", ",", "coord", ".", "y", ",", "coord", ".", "x", ")", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"The sun position is computed according a point location.\"", ")", ";", "}", "}" ]
Return the sun position for a given date @param point @param date @return @throws IllegalArgumentException
[ "Return", "the", "sun", "position", "for", "a", "given", "date" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/earth/ST_SunPosition.java#L68-L78
eldur/jwbf
src/main/java/net/sourceforge/jwbf/mediawiki/actions/editing/GetApiToken.java
GetApiToken.generateTokenRequest
private static Get generateTokenRequest(Intoken intoken, String title) { """ Generates the next MediaWiki API urlEncodedToken and adds it to <code>msgs</code>. @param intoken type to get the urlEncodedToken for @param title title of the article to generate the urlEncodedToken for """ return new ApiRequestBuilder() // .action("query") // .formatXml() // .param("prop", "info") // .param("intoken", intoken.toString().toLowerCase()) // .param("titles", MediaWiki.urlEncode(title)) // .buildGet(); }
java
private static Get generateTokenRequest(Intoken intoken, String title) { return new ApiRequestBuilder() // .action("query") // .formatXml() // .param("prop", "info") // .param("intoken", intoken.toString().toLowerCase()) // .param("titles", MediaWiki.urlEncode(title)) // .buildGet(); }
[ "private", "static", "Get", "generateTokenRequest", "(", "Intoken", "intoken", ",", "String", "title", ")", "{", "return", "new", "ApiRequestBuilder", "(", ")", "//", ".", "action", "(", "\"query\"", ")", "//", ".", "formatXml", "(", ")", "//", ".", "param", "(", "\"prop\"", ",", "\"info\"", ")", "//", ".", "param", "(", "\"intoken\"", ",", "intoken", ".", "toString", "(", ")", ".", "toLowerCase", "(", ")", ")", "//", ".", "param", "(", "\"titles\"", ",", "MediaWiki", ".", "urlEncode", "(", "title", ")", ")", "//", ".", "buildGet", "(", ")", ";", "}" ]
Generates the next MediaWiki API urlEncodedToken and adds it to <code>msgs</code>. @param intoken type to get the urlEncodedToken for @param title title of the article to generate the urlEncodedToken for
[ "Generates", "the", "next", "MediaWiki", "API", "urlEncodedToken", "and", "adds", "it", "to", "<code", ">", "msgs<", "/", "code", ">", "." ]
train
https://github.com/eldur/jwbf/blob/ee17ea2fa5a26f17c8332a094b2db86dd596d1ff/src/main/java/net/sourceforge/jwbf/mediawiki/actions/editing/GetApiToken.java#L123-L131
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ServerAutomaticTuningsInner.java
ServerAutomaticTuningsInner.updateAsync
public Observable<ServerAutomaticTuningInner> updateAsync(String resourceGroupName, String serverName, ServerAutomaticTuningInner parameters) { """ Update automatic tuning options on server. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param parameters The requested automatic tuning resource state. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ServerAutomaticTuningInner object """ return updateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ServerAutomaticTuningInner>, ServerAutomaticTuningInner>() { @Override public ServerAutomaticTuningInner call(ServiceResponse<ServerAutomaticTuningInner> response) { return response.body(); } }); }
java
public Observable<ServerAutomaticTuningInner> updateAsync(String resourceGroupName, String serverName, ServerAutomaticTuningInner parameters) { return updateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ServerAutomaticTuningInner>, ServerAutomaticTuningInner>() { @Override public ServerAutomaticTuningInner call(ServiceResponse<ServerAutomaticTuningInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ServerAutomaticTuningInner", ">", "updateAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "ServerAutomaticTuningInner", "parameters", ")", "{", "return", "updateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ServerAutomaticTuningInner", ">", ",", "ServerAutomaticTuningInner", ">", "(", ")", "{", "@", "Override", "public", "ServerAutomaticTuningInner", "call", "(", "ServiceResponse", "<", "ServerAutomaticTuningInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Update automatic tuning options on server. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param parameters The requested automatic tuning resource state. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ServerAutomaticTuningInner object
[ "Update", "automatic", "tuning", "options", "on", "server", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ServerAutomaticTuningsInner.java#L191-L198
kotcrab/vis-ui
ui/src/main/java/com/kotcrab/vis/ui/widget/VisWindow.java
VisWindow.closeOnEscape
public void closeOnEscape () { """ Will make this window close when escape key or back key was pressed. After pressing escape or back, {@link #close()} is called. Back key is Android and iOS only """ addListener(new InputListener() { @Override public boolean keyDown (InputEvent event, int keycode) { if (keycode == Keys.ESCAPE) { close(); return true; } return false; } @Override public boolean keyUp (InputEvent event, int keycode) { if (keycode == Keys.BACK) { close(); return true; } return false; } }); }
java
public void closeOnEscape () { addListener(new InputListener() { @Override public boolean keyDown (InputEvent event, int keycode) { if (keycode == Keys.ESCAPE) { close(); return true; } return false; } @Override public boolean keyUp (InputEvent event, int keycode) { if (keycode == Keys.BACK) { close(); return true; } return false; } }); }
[ "public", "void", "closeOnEscape", "(", ")", "{", "addListener", "(", "new", "InputListener", "(", ")", "{", "@", "Override", "public", "boolean", "keyDown", "(", "InputEvent", "event", ",", "int", "keycode", ")", "{", "if", "(", "keycode", "==", "Keys", ".", "ESCAPE", ")", "{", "close", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", "@", "Override", "public", "boolean", "keyUp", "(", "InputEvent", "event", ",", "int", "keycode", ")", "{", "if", "(", "keycode", "==", "Keys", ".", "BACK", ")", "{", "close", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", "}", ")", ";", "}" ]
Will make this window close when escape key or back key was pressed. After pressing escape or back, {@link #close()} is called. Back key is Android and iOS only
[ "Will", "make", "this", "window", "close", "when", "escape", "key", "or", "back", "key", "was", "pressed", ".", "After", "pressing", "escape", "or", "back", "{" ]
train
https://github.com/kotcrab/vis-ui/blob/3b68f82d94ae32bffa2a3399c63f432e0f4908e0/ui/src/main/java/com/kotcrab/vis/ui/widget/VisWindow.java#L197-L219
geomajas/geomajas-project-client-gwt
plugin/javascript-api/javascript-api-gwt/src/main/java/org/geomajas/plugin/jsapi/gwt/client/exporter/GeomajasServiceImpl.java
GeomajasServiceImpl.registerMap
public void registerMap(String applicationId, String mapId, Map map) { """ Register the given {@link Map} with applicationId and mapId. @param applicationId the application id. @param mapId the map id. @param map the map to register. """ HashMap<String, Map> mapMap; if (maps.containsKey(applicationId)) { mapMap = maps.get(applicationId); if (!mapMap.containsKey(mapId)) { mapMap.put(mapId, map); } } else { mapMap = new HashMap<String, Map>(); mapMap.put(mapId, map); maps.put(applicationId, mapMap); } }
java
public void registerMap(String applicationId, String mapId, Map map) { HashMap<String, Map> mapMap; if (maps.containsKey(applicationId)) { mapMap = maps.get(applicationId); if (!mapMap.containsKey(mapId)) { mapMap.put(mapId, map); } } else { mapMap = new HashMap<String, Map>(); mapMap.put(mapId, map); maps.put(applicationId, mapMap); } }
[ "public", "void", "registerMap", "(", "String", "applicationId", ",", "String", "mapId", ",", "Map", "map", ")", "{", "HashMap", "<", "String", ",", "Map", ">", "mapMap", ";", "if", "(", "maps", ".", "containsKey", "(", "applicationId", ")", ")", "{", "mapMap", "=", "maps", ".", "get", "(", "applicationId", ")", ";", "if", "(", "!", "mapMap", ".", "containsKey", "(", "mapId", ")", ")", "{", "mapMap", ".", "put", "(", "mapId", ",", "map", ")", ";", "}", "}", "else", "{", "mapMap", "=", "new", "HashMap", "<", "String", ",", "Map", ">", "(", ")", ";", "mapMap", ".", "put", "(", "mapId", ",", "map", ")", ";", "maps", ".", "put", "(", "applicationId", ",", "mapMap", ")", ";", "}", "}" ]
Register the given {@link Map} with applicationId and mapId. @param applicationId the application id. @param mapId the map id. @param map the map to register.
[ "Register", "the", "given", "{", "@link", "Map", "}", "with", "applicationId", "and", "mapId", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/plugin/javascript-api/javascript-api-gwt/src/main/java/org/geomajas/plugin/jsapi/gwt/client/exporter/GeomajasServiceImpl.java#L121-L133
OpenLiberty/open-liberty
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/filemgr/FileManagerImpl.java
FileManagerImpl.split_block
private long split_block(long block_addr, int request_size, int rem) throws IOException { """ /* Split a block on disk and return the appropriate address. We assume that this is only called to split a block on the misc list. """ allocated_words += request_size; allocated_blocks++; free_words -= request_size; ml_hits++; ml_splits++; seek_and_count(block_addr + request_size); writeInt(rem); seek_and_count(block_addr); writeInt(- request_size); return(block_addr + HDR_SIZE); }
java
private long split_block(long block_addr, int request_size, int rem) throws IOException { allocated_words += request_size; allocated_blocks++; free_words -= request_size; ml_hits++; ml_splits++; seek_and_count(block_addr + request_size); writeInt(rem); seek_and_count(block_addr); writeInt(- request_size); return(block_addr + HDR_SIZE); }
[ "private", "long", "split_block", "(", "long", "block_addr", ",", "int", "request_size", ",", "int", "rem", ")", "throws", "IOException", "{", "allocated_words", "+=", "request_size", ";", "allocated_blocks", "++", ";", "free_words", "-=", "request_size", ";", "ml_hits", "++", ";", "ml_splits", "++", ";", "seek_and_count", "(", "block_addr", "+", "request_size", ")", ";", "writeInt", "(", "rem", ")", ";", "seek_and_count", "(", "block_addr", ")", ";", "writeInt", "(", "-", "request_size", ")", ";", "return", "(", "block_addr", "+", "HDR_SIZE", ")", ";", "}" ]
/* Split a block on disk and return the appropriate address. We assume that this is only called to split a block on the misc list.
[ "/", "*", "Split", "a", "block", "on", "disk", "and", "return", "the", "appropriate", "address", ".", "We", "assume", "that", "this", "is", "only", "called", "to", "split", "a", "block", "on", "the", "misc", "list", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/filemgr/FileManagerImpl.java#L946-L959
cycorp/api-suite
core-api/src/main/java/com/cyc/kb/exception/CreateException.java
CreateException.fromThrowable
public static CreateException fromThrowable(String message, Throwable cause) { """ Converts a Throwable to a CreateException with the specified detail message. If the Throwable is a CreateException and if the Throwable's message is identical to the one supplied, the Throwable will be passed through unmodified; otherwise, it will be wrapped in a new CreateException with the detail message. @param cause the Throwable to convert @param message the specified detail message @return a CreateException """ return (cause instanceof CreateException && Objects.equals(message, cause.getMessage())) ? (CreateException) cause : new CreateException(message, cause); }
java
public static CreateException fromThrowable(String message, Throwable cause) { return (cause instanceof CreateException && Objects.equals(message, cause.getMessage())) ? (CreateException) cause : new CreateException(message, cause); }
[ "public", "static", "CreateException", "fromThrowable", "(", "String", "message", ",", "Throwable", "cause", ")", "{", "return", "(", "cause", "instanceof", "CreateException", "&&", "Objects", ".", "equals", "(", "message", ",", "cause", ".", "getMessage", "(", ")", ")", ")", "?", "(", "CreateException", ")", "cause", ":", "new", "CreateException", "(", "message", ",", "cause", ")", ";", "}" ]
Converts a Throwable to a CreateException with the specified detail message. If the Throwable is a CreateException and if the Throwable's message is identical to the one supplied, the Throwable will be passed through unmodified; otherwise, it will be wrapped in a new CreateException with the detail message. @param cause the Throwable to convert @param message the specified detail message @return a CreateException
[ "Converts", "a", "Throwable", "to", "a", "CreateException", "with", "the", "specified", "detail", "message", ".", "If", "the", "Throwable", "is", "a", "CreateException", "and", "if", "the", "Throwable", "s", "message", "is", "identical", "to", "the", "one", "supplied", "the", "Throwable", "will", "be", "passed", "through", "unmodified", ";", "otherwise", "it", "will", "be", "wrapped", "in", "a", "new", "CreateException", "with", "the", "detail", "message", "." ]
train
https://github.com/cycorp/api-suite/blob/1d52affabc4635e3715a059e38741712cbdbf2d5/core-api/src/main/java/com/cyc/kb/exception/CreateException.java#L64-L68
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/common/utils/NetUtils.java
NetUtils.connectToString
public static String connectToString(InetSocketAddress local, InetSocketAddress remote) { """ 连接转字符串 @param local 本地地址 @param remote 远程地址 @return 地址信息字符串 """ return toAddressString(local) + " <-> " + toAddressString(remote); }
java
public static String connectToString(InetSocketAddress local, InetSocketAddress remote) { return toAddressString(local) + " <-> " + toAddressString(remote); }
[ "public", "static", "String", "connectToString", "(", "InetSocketAddress", "local", ",", "InetSocketAddress", "remote", ")", "{", "return", "toAddressString", "(", "local", ")", "+", "\" <-> \"", "+", "toAddressString", "(", "remote", ")", ";", "}" ]
连接转字符串 @param local 本地地址 @param remote 远程地址 @return 地址信息字符串
[ "连接转字符串" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/common/utils/NetUtils.java#L457-L459
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/Channel.java
Channel.sendInstallProposal
Collection<ProposalResponse> sendInstallProposal(InstallProposalRequest installProposalRequest, Collection<Peer> peers) throws ProposalException, InvalidArgumentException { """ Send install chaincode request proposal to the channel. @param installProposalRequest @param peers @return @throws ProposalException @throws InvalidArgumentException """ checkChannelState(); checkPeers(peers); if (null == installProposalRequest) { throw new InvalidArgumentException("InstallProposalRequest is null"); } try { TransactionContext transactionContext = getTransactionContext(installProposalRequest.getUserContext()); transactionContext.verify(false); // Install will have no signing cause it's not really targeted to a channel. transactionContext.setProposalWaitTime(installProposalRequest.getProposalWaitTime()); InstallProposalBuilder installProposalbuilder = InstallProposalBuilder.newBuilder(); installProposalbuilder.context(transactionContext); installProposalbuilder.setChaincodeLanguage(installProposalRequest.getChaincodeLanguage()); installProposalbuilder.chaincodeName(installProposalRequest.getChaincodeName()); installProposalbuilder.chaincodePath(installProposalRequest.getChaincodePath()); installProposalbuilder.chaincodeVersion(installProposalRequest.getChaincodeVersion()); installProposalbuilder.setChaincodeSource(installProposalRequest.getChaincodeSourceLocation()); installProposalbuilder.setChaincodeInputStream(installProposalRequest.getChaincodeInputStream()); installProposalbuilder.setChaincodeMetaInfLocation(installProposalRequest.getChaincodeMetaInfLocation()); FabricProposal.Proposal deploymentProposal = installProposalbuilder.build(); SignedProposal signedProposal = getSignedProposal(transactionContext, deploymentProposal); return sendProposalToPeers(peers, signedProposal, transactionContext); } catch (Exception e) { throw new ProposalException(e); } }
java
Collection<ProposalResponse> sendInstallProposal(InstallProposalRequest installProposalRequest, Collection<Peer> peers) throws ProposalException, InvalidArgumentException { checkChannelState(); checkPeers(peers); if (null == installProposalRequest) { throw new InvalidArgumentException("InstallProposalRequest is null"); } try { TransactionContext transactionContext = getTransactionContext(installProposalRequest.getUserContext()); transactionContext.verify(false); // Install will have no signing cause it's not really targeted to a channel. transactionContext.setProposalWaitTime(installProposalRequest.getProposalWaitTime()); InstallProposalBuilder installProposalbuilder = InstallProposalBuilder.newBuilder(); installProposalbuilder.context(transactionContext); installProposalbuilder.setChaincodeLanguage(installProposalRequest.getChaincodeLanguage()); installProposalbuilder.chaincodeName(installProposalRequest.getChaincodeName()); installProposalbuilder.chaincodePath(installProposalRequest.getChaincodePath()); installProposalbuilder.chaincodeVersion(installProposalRequest.getChaincodeVersion()); installProposalbuilder.setChaincodeSource(installProposalRequest.getChaincodeSourceLocation()); installProposalbuilder.setChaincodeInputStream(installProposalRequest.getChaincodeInputStream()); installProposalbuilder.setChaincodeMetaInfLocation(installProposalRequest.getChaincodeMetaInfLocation()); FabricProposal.Proposal deploymentProposal = installProposalbuilder.build(); SignedProposal signedProposal = getSignedProposal(transactionContext, deploymentProposal); return sendProposalToPeers(peers, signedProposal, transactionContext); } catch (Exception e) { throw new ProposalException(e); } }
[ "Collection", "<", "ProposalResponse", ">", "sendInstallProposal", "(", "InstallProposalRequest", "installProposalRequest", ",", "Collection", "<", "Peer", ">", "peers", ")", "throws", "ProposalException", ",", "InvalidArgumentException", "{", "checkChannelState", "(", ")", ";", "checkPeers", "(", "peers", ")", ";", "if", "(", "null", "==", "installProposalRequest", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"InstallProposalRequest is null\"", ")", ";", "}", "try", "{", "TransactionContext", "transactionContext", "=", "getTransactionContext", "(", "installProposalRequest", ".", "getUserContext", "(", ")", ")", ";", "transactionContext", ".", "verify", "(", "false", ")", ";", "// Install will have no signing cause it's not really targeted to a channel.", "transactionContext", ".", "setProposalWaitTime", "(", "installProposalRequest", ".", "getProposalWaitTime", "(", ")", ")", ";", "InstallProposalBuilder", "installProposalbuilder", "=", "InstallProposalBuilder", ".", "newBuilder", "(", ")", ";", "installProposalbuilder", ".", "context", "(", "transactionContext", ")", ";", "installProposalbuilder", ".", "setChaincodeLanguage", "(", "installProposalRequest", ".", "getChaincodeLanguage", "(", ")", ")", ";", "installProposalbuilder", ".", "chaincodeName", "(", "installProposalRequest", ".", "getChaincodeName", "(", ")", ")", ";", "installProposalbuilder", ".", "chaincodePath", "(", "installProposalRequest", ".", "getChaincodePath", "(", ")", ")", ";", "installProposalbuilder", ".", "chaincodeVersion", "(", "installProposalRequest", ".", "getChaincodeVersion", "(", ")", ")", ";", "installProposalbuilder", ".", "setChaincodeSource", "(", "installProposalRequest", ".", "getChaincodeSourceLocation", "(", ")", ")", ";", "installProposalbuilder", ".", "setChaincodeInputStream", "(", "installProposalRequest", ".", "getChaincodeInputStream", "(", ")", ")", ";", "installProposalbuilder", ".", "setChaincodeMetaInfLocation", "(", "installProposalRequest", ".", "getChaincodeMetaInfLocation", "(", ")", ")", ";", "FabricProposal", ".", "Proposal", "deploymentProposal", "=", "installProposalbuilder", ".", "build", "(", ")", ";", "SignedProposal", "signedProposal", "=", "getSignedProposal", "(", "transactionContext", ",", "deploymentProposal", ")", ";", "return", "sendProposalToPeers", "(", "peers", ",", "signedProposal", ",", "transactionContext", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "ProposalException", "(", "e", ")", ";", "}", "}" ]
Send install chaincode request proposal to the channel. @param installProposalRequest @param peers @return @throws ProposalException @throws InvalidArgumentException
[ "Send", "install", "chaincode", "request", "proposal", "to", "the", "channel", "." ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L2528-L2559
opentable/otj-jaxrs
client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java
JaxRsClientFactory.createClientProxy
public <T> T createClientProxy(Class<T> proxyClass, WebTarget baseTarget) { """ Create a Client proxy for the given interface type. Note that different JAX-RS providers behave slightly differently for this feature. @param proxyClass the class to implement @param baseTarget the API root @return a proxy implementation that executes requests """ return factory(ctx).createClientProxy(proxyClass, baseTarget); }
java
public <T> T createClientProxy(Class<T> proxyClass, WebTarget baseTarget) { return factory(ctx).createClientProxy(proxyClass, baseTarget); }
[ "public", "<", "T", ">", "T", "createClientProxy", "(", "Class", "<", "T", ">", "proxyClass", ",", "WebTarget", "baseTarget", ")", "{", "return", "factory", "(", "ctx", ")", ".", "createClientProxy", "(", "proxyClass", ",", "baseTarget", ")", ";", "}" ]
Create a Client proxy for the given interface type. Note that different JAX-RS providers behave slightly differently for this feature. @param proxyClass the class to implement @param baseTarget the API root @return a proxy implementation that executes requests
[ "Create", "a", "Client", "proxy", "for", "the", "given", "interface", "type", ".", "Note", "that", "different", "JAX", "-", "RS", "providers", "behave", "slightly", "differently", "for", "this", "feature", "." ]
train
https://github.com/opentable/otj-jaxrs/blob/384e7094fe5a56d41b2a9970bfd783fa85cbbcb8/client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java#L276-L278
weld/core
impl/src/main/java/org/jboss/weld/interceptor/proxy/InterceptionContext.java
InterceptionContext.forConstructorInterception
public static InterceptionContext forConstructorInterception(InterceptionModel interceptionModel, CreationalContext<?> ctx, BeanManagerImpl manager, SlimAnnotatedType<?> type) { """ The context returned by this method may be later reused for other interception types. @param interceptionModel @param ctx @param manager @param type @return the interception context to be used for the AroundConstruct chain """ return of(interceptionModel, ctx, manager, null, type); }
java
public static InterceptionContext forConstructorInterception(InterceptionModel interceptionModel, CreationalContext<?> ctx, BeanManagerImpl manager, SlimAnnotatedType<?> type) { return of(interceptionModel, ctx, manager, null, type); }
[ "public", "static", "InterceptionContext", "forConstructorInterception", "(", "InterceptionModel", "interceptionModel", ",", "CreationalContext", "<", "?", ">", "ctx", ",", "BeanManagerImpl", "manager", ",", "SlimAnnotatedType", "<", "?", ">", "type", ")", "{", "return", "of", "(", "interceptionModel", ",", "ctx", ",", "manager", ",", "null", ",", "type", ")", ";", "}" ]
The context returned by this method may be later reused for other interception types. @param interceptionModel @param ctx @param manager @param type @return the interception context to be used for the AroundConstruct chain
[ "The", "context", "returned", "by", "this", "method", "may", "be", "later", "reused", "for", "other", "interception", "types", "." ]
train
https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/interceptor/proxy/InterceptionContext.java#L68-L70
ehcache/ehcache3
impl/src/main/java/org/ehcache/config/builders/CacheEventListenerConfigurationBuilder.java
CacheEventListenerConfigurationBuilder.newEventListenerConfiguration
public static CacheEventListenerConfigurationBuilder newEventListenerConfiguration( CacheEventListener<?, ?> listener, EventType eventType, EventType... eventTypes) { """ Creates a new builder instance using the given {@link CacheEventListener} instance and the {@link EventType}s it will listen to. <p> <ul> <li>{@link EventOrdering} defaults to {@link EventOrdering#UNORDERED}</li> <li>{@link EventFiring} defaults to {@link EventFiring#ASYNCHRONOUS}</li> </ul> @param listener the {@code CacheEventListener} instance @param eventType the mandatory event type to listen to @param eventTypes optional additional event types to listen to @return the new builder instance """ return new CacheEventListenerConfigurationBuilder(EnumSet.of(eventType, eventTypes), listener); }
java
public static CacheEventListenerConfigurationBuilder newEventListenerConfiguration( CacheEventListener<?, ?> listener, EventType eventType, EventType... eventTypes){ return new CacheEventListenerConfigurationBuilder(EnumSet.of(eventType, eventTypes), listener); }
[ "public", "static", "CacheEventListenerConfigurationBuilder", "newEventListenerConfiguration", "(", "CacheEventListener", "<", "?", ",", "?", ">", "listener", ",", "EventType", "eventType", ",", "EventType", "...", "eventTypes", ")", "{", "return", "new", "CacheEventListenerConfigurationBuilder", "(", "EnumSet", ".", "of", "(", "eventType", ",", "eventTypes", ")", ",", "listener", ")", ";", "}" ]
Creates a new builder instance using the given {@link CacheEventListener} instance and the {@link EventType}s it will listen to. <p> <ul> <li>{@link EventOrdering} defaults to {@link EventOrdering#UNORDERED}</li> <li>{@link EventFiring} defaults to {@link EventFiring#ASYNCHRONOUS}</li> </ul> @param listener the {@code CacheEventListener} instance @param eventType the mandatory event type to listen to @param eventTypes optional additional event types to listen to @return the new builder instance
[ "Creates", "a", "new", "builder", "instance", "using", "the", "given", "{", "@link", "CacheEventListener", "}", "instance", "and", "the", "{", "@link", "EventType", "}", "s", "it", "will", "listen", "to", ".", "<p", ">", "<ul", ">", "<li", ">", "{", "@link", "EventOrdering", "}", "defaults", "to", "{", "@link", "EventOrdering#UNORDERED", "}", "<", "/", "li", ">", "<li", ">", "{", "@link", "EventFiring", "}", "defaults", "to", "{", "@link", "EventFiring#ASYNCHRONOUS", "}", "<", "/", "li", ">", "<", "/", "ul", ">" ]
train
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/CacheEventListenerConfigurationBuilder.java#L100-L103
OpenBEL/openbel-framework
org.openbel.framework.common/src/main/java/org/openbel/framework/common/external/ExternalType.java
ExternalType.writeInteger
public static void writeInteger(final ObjectOutput out, final Integer i) throws IOException { """ Writes the {@link Integer} to the output. <p> This method and its equivalent {@link #readInteger(ObjectInput) read-variant} store {@code i} in a more efficient way than serializing the {@link Integer} class. </p> @param out Non-null {@link ObjectOutput} @param i {@link Integer}; may be null @throws IOException Thrown if an I/O error occurred @see #readInteger(ObjectInput) """ if (i == null) { out.writeByte(0); return; } out.writeByte(1); out.writeInt(i); }
java
public static void writeInteger(final ObjectOutput out, final Integer i) throws IOException { if (i == null) { out.writeByte(0); return; } out.writeByte(1); out.writeInt(i); }
[ "public", "static", "void", "writeInteger", "(", "final", "ObjectOutput", "out", ",", "final", "Integer", "i", ")", "throws", "IOException", "{", "if", "(", "i", "==", "null", ")", "{", "out", ".", "writeByte", "(", "0", ")", ";", "return", ";", "}", "out", ".", "writeByte", "(", "1", ")", ";", "out", ".", "writeInt", "(", "i", ")", ";", "}" ]
Writes the {@link Integer} to the output. <p> This method and its equivalent {@link #readInteger(ObjectInput) read-variant} store {@code i} in a more efficient way than serializing the {@link Integer} class. </p> @param out Non-null {@link ObjectOutput} @param i {@link Integer}; may be null @throws IOException Thrown if an I/O error occurred @see #readInteger(ObjectInput)
[ "Writes", "the", "{", "@link", "Integer", "}", "to", "the", "output", ".", "<p", ">", "This", "method", "and", "its", "equivalent", "{", "@link", "#readInteger", "(", "ObjectInput", ")", "read", "-", "variant", "}", "store", "{", "@code", "i", "}", "in", "a", "more", "efficient", "way", "than", "serializing", "the", "{", "@link", "Integer", "}", "class", ".", "<", "/", "p", ">" ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/external/ExternalType.java#L102-L110
sebastiangraf/jSCSI
bundles/initiator/src/main/java/org/jscsi/initiator/connection/SenderWorker.java
SenderWorker.receiveFromWire
public ProtocolDataUnit receiveFromWire () throws DigestException , InternetSCSIException , IOException { """ Receives a <code>ProtocolDataUnit</code> from the socket and appends it to the end of the receiving queue of this connection. @return Queue with the resulting units @throws IOException if an I/O error occurs. @throws InternetSCSIException if any violation of the iSCSI-Standard emerge. @throws DigestException if a mismatch of the digest exists. """ final ProtocolDataUnit protocolDataUnit = protocolDataUnitFactory.create(connection.getSetting(OperationalTextKey.HEADER_DIGEST), connection.getSetting(OperationalTextKey.DATA_DIGEST)); try { protocolDataUnit.read(socketChannel); } catch (ClosedChannelException e) { throw new InternetSCSIException(e); } LOGGER.debug("Receiving this PDU: " + protocolDataUnit); final Exception isCorrect = connection.getState().isCorrect(protocolDataUnit); if (isCorrect == null) { LOGGER.trace("Adding PDU to Receiving Queue."); final TargetMessageParser parser = (TargetMessageParser) protocolDataUnit.getBasicHeaderSegment().getParser(); final Session session = connection.getSession(); // the PDU maxCmdSN is greater than the local maxCmdSN, so we // have to update the local one if (session.getMaximumCommandSequenceNumber().compareTo(parser.getMaximumCommandSequenceNumber()) < 0) { session.setMaximumCommandSequenceNumber(parser.getMaximumCommandSequenceNumber()); } // the PDU expCmdSN is greater than the local expCmdSN, so we // have to update the local one if (parser.incrementSequenceNumber()) { if (connection.getExpectedStatusSequenceNumber().compareTo(parser.getStatusSequenceNumber()) >= 0) { connection.incrementExpectedStatusSequenceNumber(); } else { LOGGER.error("Status Sequence Number Mismatch (received, expected): " + parser.getStatusSequenceNumber() + ", " + (connection.getExpectedStatusSequenceNumber().getValue() - 1)); } } } else { throw new InternetSCSIException(isCorrect); } return protocolDataUnit; }
java
public ProtocolDataUnit receiveFromWire () throws DigestException , InternetSCSIException , IOException { final ProtocolDataUnit protocolDataUnit = protocolDataUnitFactory.create(connection.getSetting(OperationalTextKey.HEADER_DIGEST), connection.getSetting(OperationalTextKey.DATA_DIGEST)); try { protocolDataUnit.read(socketChannel); } catch (ClosedChannelException e) { throw new InternetSCSIException(e); } LOGGER.debug("Receiving this PDU: " + protocolDataUnit); final Exception isCorrect = connection.getState().isCorrect(protocolDataUnit); if (isCorrect == null) { LOGGER.trace("Adding PDU to Receiving Queue."); final TargetMessageParser parser = (TargetMessageParser) protocolDataUnit.getBasicHeaderSegment().getParser(); final Session session = connection.getSession(); // the PDU maxCmdSN is greater than the local maxCmdSN, so we // have to update the local one if (session.getMaximumCommandSequenceNumber().compareTo(parser.getMaximumCommandSequenceNumber()) < 0) { session.setMaximumCommandSequenceNumber(parser.getMaximumCommandSequenceNumber()); } // the PDU expCmdSN is greater than the local expCmdSN, so we // have to update the local one if (parser.incrementSequenceNumber()) { if (connection.getExpectedStatusSequenceNumber().compareTo(parser.getStatusSequenceNumber()) >= 0) { connection.incrementExpectedStatusSequenceNumber(); } else { LOGGER.error("Status Sequence Number Mismatch (received, expected): " + parser.getStatusSequenceNumber() + ", " + (connection.getExpectedStatusSequenceNumber().getValue() - 1)); } } } else { throw new InternetSCSIException(isCorrect); } return protocolDataUnit; }
[ "public", "ProtocolDataUnit", "receiveFromWire", "(", ")", "throws", "DigestException", ",", "InternetSCSIException", ",", "IOException", "{", "final", "ProtocolDataUnit", "protocolDataUnit", "=", "protocolDataUnitFactory", ".", "create", "(", "connection", ".", "getSetting", "(", "OperationalTextKey", ".", "HEADER_DIGEST", ")", ",", "connection", ".", "getSetting", "(", "OperationalTextKey", ".", "DATA_DIGEST", ")", ")", ";", "try", "{", "protocolDataUnit", ".", "read", "(", "socketChannel", ")", ";", "}", "catch", "(", "ClosedChannelException", "e", ")", "{", "throw", "new", "InternetSCSIException", "(", "e", ")", ";", "}", "LOGGER", ".", "debug", "(", "\"Receiving this PDU: \"", "+", "protocolDataUnit", ")", ";", "final", "Exception", "isCorrect", "=", "connection", ".", "getState", "(", ")", ".", "isCorrect", "(", "protocolDataUnit", ")", ";", "if", "(", "isCorrect", "==", "null", ")", "{", "LOGGER", ".", "trace", "(", "\"Adding PDU to Receiving Queue.\"", ")", ";", "final", "TargetMessageParser", "parser", "=", "(", "TargetMessageParser", ")", "protocolDataUnit", ".", "getBasicHeaderSegment", "(", ")", ".", "getParser", "(", ")", ";", "final", "Session", "session", "=", "connection", ".", "getSession", "(", ")", ";", "// the PDU maxCmdSN is greater than the local maxCmdSN, so we", "// have to update the local one", "if", "(", "session", ".", "getMaximumCommandSequenceNumber", "(", ")", ".", "compareTo", "(", "parser", ".", "getMaximumCommandSequenceNumber", "(", ")", ")", "<", "0", ")", "{", "session", ".", "setMaximumCommandSequenceNumber", "(", "parser", ".", "getMaximumCommandSequenceNumber", "(", ")", ")", ";", "}", "// the PDU expCmdSN is greater than the local expCmdSN, so we", "// have to update the local one", "if", "(", "parser", ".", "incrementSequenceNumber", "(", ")", ")", "{", "if", "(", "connection", ".", "getExpectedStatusSequenceNumber", "(", ")", ".", "compareTo", "(", "parser", ".", "getStatusSequenceNumber", "(", ")", ")", ">=", "0", ")", "{", "connection", ".", "incrementExpectedStatusSequenceNumber", "(", ")", ";", "}", "else", "{", "LOGGER", ".", "error", "(", "\"Status Sequence Number Mismatch (received, expected): \"", "+", "parser", ".", "getStatusSequenceNumber", "(", ")", "+", "\", \"", "+", "(", "connection", ".", "getExpectedStatusSequenceNumber", "(", ")", ".", "getValue", "(", ")", "-", "1", ")", ")", ";", "}", "}", "}", "else", "{", "throw", "new", "InternetSCSIException", "(", "isCorrect", ")", ";", "}", "return", "protocolDataUnit", ";", "}" ]
Receives a <code>ProtocolDataUnit</code> from the socket and appends it to the end of the receiving queue of this connection. @return Queue with the resulting units @throws IOException if an I/O error occurs. @throws InternetSCSIException if any violation of the iSCSI-Standard emerge. @throws DigestException if a mismatch of the digest exists.
[ "Receives", "a", "<code", ">", "ProtocolDataUnit<", "/", "code", ">", "from", "the", "socket", "and", "appends", "it", "to", "the", "end", "of", "the", "receiving", "queue", "of", "this", "connection", "." ]
train
https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/initiator/src/main/java/org/jscsi/initiator/connection/SenderWorker.java#L115-L155
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/clean/rdbms/scripts/MySQLCleaningScipts.java
MySQLCleaningScipts.filter
private Collection<String> filter(Collection<String> scripts) { """ Removing foreign key creation from initialization scripts for table JCR_S(M)ITEM and JCR_S(M)VALUE. It is not possible to create table with such foreign key if the same key exists in another table of database """ String JCR_ITEM_PRIMARY_KEY = "CONSTRAINT JCR_PK_" + itemTableSuffix + " PRIMARY KEY(ID)"; String JCR_ITEM_FOREIGN_KEY = "CONSTRAINT JCR_FK_" + itemTableSuffix + "_PARENT FOREIGN KEY(PARENT_ID) REFERENCES " + itemTableName + "(ID)"; String JCR_VALUE_PRIMARY_KEY = "CONSTRAINT JCR_PK_" + valueTableSuffix + " PRIMARY KEY(ID)"; String JCR_VALUE_FOREIGN_KEY = "CONSTRAINT JCR_FK_" + valueTableSuffix + "_PROPERTY FOREIGN KEY(PROPERTY_ID) REFERENCES " + itemTableName + "(ID)"; Collection<String> filteredScripts = new ArrayList<String>(); for (String script : scripts) { if (script.contains(JCR_ITEM_PRIMARY_KEY + ",")) { script = script.replace(JCR_ITEM_PRIMARY_KEY + ",", JCR_ITEM_PRIMARY_KEY); script = script.replace(JCR_ITEM_FOREIGN_KEY, ""); } else if (script.contains(JCR_VALUE_PRIMARY_KEY + ",")) { script = script.replace(JCR_VALUE_PRIMARY_KEY + ",", JCR_VALUE_PRIMARY_KEY); script = script.replace(JCR_VALUE_FOREIGN_KEY, ""); } filteredScripts.add(script); } return filteredScripts; }
java
private Collection<String> filter(Collection<String> scripts) { String JCR_ITEM_PRIMARY_KEY = "CONSTRAINT JCR_PK_" + itemTableSuffix + " PRIMARY KEY(ID)"; String JCR_ITEM_FOREIGN_KEY = "CONSTRAINT JCR_FK_" + itemTableSuffix + "_PARENT FOREIGN KEY(PARENT_ID) REFERENCES " + itemTableName + "(ID)"; String JCR_VALUE_PRIMARY_KEY = "CONSTRAINT JCR_PK_" + valueTableSuffix + " PRIMARY KEY(ID)"; String JCR_VALUE_FOREIGN_KEY = "CONSTRAINT JCR_FK_" + valueTableSuffix + "_PROPERTY FOREIGN KEY(PROPERTY_ID) REFERENCES " + itemTableName + "(ID)"; Collection<String> filteredScripts = new ArrayList<String>(); for (String script : scripts) { if (script.contains(JCR_ITEM_PRIMARY_KEY + ",")) { script = script.replace(JCR_ITEM_PRIMARY_KEY + ",", JCR_ITEM_PRIMARY_KEY); script = script.replace(JCR_ITEM_FOREIGN_KEY, ""); } else if (script.contains(JCR_VALUE_PRIMARY_KEY + ",")) { script = script.replace(JCR_VALUE_PRIMARY_KEY + ",", JCR_VALUE_PRIMARY_KEY); script = script.replace(JCR_VALUE_FOREIGN_KEY, ""); } filteredScripts.add(script); } return filteredScripts; }
[ "private", "Collection", "<", "String", ">", "filter", "(", "Collection", "<", "String", ">", "scripts", ")", "{", "String", "JCR_ITEM_PRIMARY_KEY", "=", "\"CONSTRAINT JCR_PK_\"", "+", "itemTableSuffix", "+", "\" PRIMARY KEY(ID)\"", ";", "String", "JCR_ITEM_FOREIGN_KEY", "=", "\"CONSTRAINT JCR_FK_\"", "+", "itemTableSuffix", "+", "\"_PARENT FOREIGN KEY(PARENT_ID) REFERENCES \"", "+", "itemTableName", "+", "\"(ID)\"", ";", "String", "JCR_VALUE_PRIMARY_KEY", "=", "\"CONSTRAINT JCR_PK_\"", "+", "valueTableSuffix", "+", "\" PRIMARY KEY(ID)\"", ";", "String", "JCR_VALUE_FOREIGN_KEY", "=", "\"CONSTRAINT JCR_FK_\"", "+", "valueTableSuffix", "+", "\"_PROPERTY FOREIGN KEY(PROPERTY_ID) REFERENCES \"", "+", "itemTableName", "+", "\"(ID)\"", ";", "Collection", "<", "String", ">", "filteredScripts", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "String", "script", ":", "scripts", ")", "{", "if", "(", "script", ".", "contains", "(", "JCR_ITEM_PRIMARY_KEY", "+", "\",\"", ")", ")", "{", "script", "=", "script", ".", "replace", "(", "JCR_ITEM_PRIMARY_KEY", "+", "\",\"", ",", "JCR_ITEM_PRIMARY_KEY", ")", ";", "script", "=", "script", ".", "replace", "(", "JCR_ITEM_FOREIGN_KEY", ",", "\"\"", ")", ";", "}", "else", "if", "(", "script", ".", "contains", "(", "JCR_VALUE_PRIMARY_KEY", "+", "\",\"", ")", ")", "{", "script", "=", "script", ".", "replace", "(", "JCR_VALUE_PRIMARY_KEY", "+", "\",\"", ",", "JCR_VALUE_PRIMARY_KEY", ")", ";", "script", "=", "script", ".", "replace", "(", "JCR_VALUE_FOREIGN_KEY", ",", "\"\"", ")", ";", "}", "filteredScripts", ".", "add", "(", "script", ")", ";", "}", "return", "filteredScripts", ";", "}" ]
Removing foreign key creation from initialization scripts for table JCR_S(M)ITEM and JCR_S(M)VALUE. It is not possible to create table with such foreign key if the same key exists in another table of database
[ "Removing", "foreign", "key", "creation", "from", "initialization", "scripts", "for", "table", "JCR_S", "(", "M", ")", "ITEM", "and", "JCR_S", "(", "M", ")", "VALUE", ".", "It", "is", "not", "possible", "to", "create", "table", "with", "such", "foreign", "key", "if", "the", "same", "key", "exists", "in", "another", "table", "of", "database" ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/clean/rdbms/scripts/MySQLCleaningScipts.java#L108-L138
alkacon/opencms-core
src/org/opencms/jsp/CmsJspTagLink.java
CmsJspTagLink.linkTagAction
public static String linkTagAction(String target, ServletRequest req) { """ Returns a link to a file in the OpenCms VFS that has been adjusted according to the web application path and the OpenCms static export rules.<p> The current OpenCms user context URI will be used as source of the link.</p> Since OpenCms version 7.0.2, you can also use this method in case you are not sure if the link is internal or external, as {@link CmsLinkManager#substituteLinkForUnknownTarget(org.opencms.file.CmsObject, String)} is used to calculate the link target.<p> Relative links are converted to absolute links, using the current element URI as base.<p> @param target the link that should be calculated, can be relative or absolute @param req the current request @return the target link adjusted according to the web application path and the OpenCms static export rules @see org.opencms.staticexport.CmsLinkManager#substituteLinkForUnknownTarget(org.opencms.file.CmsObject, String) """ return linkTagAction(target, req, null); }
java
public static String linkTagAction(String target, ServletRequest req) { return linkTagAction(target, req, null); }
[ "public", "static", "String", "linkTagAction", "(", "String", "target", ",", "ServletRequest", "req", ")", "{", "return", "linkTagAction", "(", "target", ",", "req", ",", "null", ")", ";", "}" ]
Returns a link to a file in the OpenCms VFS that has been adjusted according to the web application path and the OpenCms static export rules.<p> The current OpenCms user context URI will be used as source of the link.</p> Since OpenCms version 7.0.2, you can also use this method in case you are not sure if the link is internal or external, as {@link CmsLinkManager#substituteLinkForUnknownTarget(org.opencms.file.CmsObject, String)} is used to calculate the link target.<p> Relative links are converted to absolute links, using the current element URI as base.<p> @param target the link that should be calculated, can be relative or absolute @param req the current request @return the target link adjusted according to the web application path and the OpenCms static export rules @see org.opencms.staticexport.CmsLinkManager#substituteLinkForUnknownTarget(org.opencms.file.CmsObject, String)
[ "Returns", "a", "link", "to", "a", "file", "in", "the", "OpenCms", "VFS", "that", "has", "been", "adjusted", "according", "to", "the", "web", "application", "path", "and", "the", "OpenCms", "static", "export", "rules", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagLink.java#L93-L96
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/CollectionUtils.java
CollectionUtils.containsAny
public static <T> boolean containsAny(Collection<T> collection, Collection<T> toCheck) { """ if any item in toCheck is present in collection @param <T> @param collection @param toCheck @return """ for(T c: toCheck){ if(collection.contains(c)) return true; } return false; }
java
public static <T> boolean containsAny(Collection<T> collection, Collection<T> toCheck){ for(T c: toCheck){ if(collection.contains(c)) return true; } return false; }
[ "public", "static", "<", "T", ">", "boolean", "containsAny", "(", "Collection", "<", "T", ">", "collection", ",", "Collection", "<", "T", ">", "toCheck", ")", "{", "for", "(", "T", "c", ":", "toCheck", ")", "{", "if", "(", "collection", ".", "contains", "(", "c", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
if any item in toCheck is present in collection @param <T> @param collection @param toCheck @return
[ "if", "any", "item", "in", "toCheck", "is", "present", "in", "collection" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/CollectionUtils.java#L757-L764
Harium/keel
src/main/java/com/harium/keel/catalano/core/IntPoint.java
IntPoint.Divide
public static IntPoint Divide(IntPoint point1, IntPoint point2) { """ Divides values of two points. @param point1 IntPoint. @param point2 IntPoint. @return IntPoint that contains X and Y axis coordinate. """ IntPoint result = new IntPoint(point1); result.Divide(point2); return result; }
java
public static IntPoint Divide(IntPoint point1, IntPoint point2) { IntPoint result = new IntPoint(point1); result.Divide(point2); return result; }
[ "public", "static", "IntPoint", "Divide", "(", "IntPoint", "point1", ",", "IntPoint", "point2", ")", "{", "IntPoint", "result", "=", "new", "IntPoint", "(", "point1", ")", ";", "result", ".", "Divide", "(", "point2", ")", ";", "return", "result", ";", "}" ]
Divides values of two points. @param point1 IntPoint. @param point2 IntPoint. @return IntPoint that contains X and Y axis coordinate.
[ "Divides", "values", "of", "two", "points", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/core/IntPoint.java#L238-L242
radkovo/SwingBox
src/main/java/org/fit/cssbox/swingbox/view/DelegateView.java
DelegateView.modelToView
@Override public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { """ Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it. @param pos the position to convert @param a the allocated region to render into @return the bounding box of the given position """ if (view != null) { return view.modelToView(pos, a, b); } return null; }
java
@Override public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { if (view != null) { return view.modelToView(pos, a, b); } return null; }
[ "@", "Override", "public", "Shape", "modelToView", "(", "int", "pos", ",", "Shape", "a", ",", "Position", ".", "Bias", "b", ")", "throws", "BadLocationException", "{", "if", "(", "view", "!=", "null", ")", "{", "return", "view", ".", "modelToView", "(", "pos", ",", "a", ",", "b", ")", ";", "}", "return", "null", ";", "}" ]
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it. @param pos the position to convert @param a the allocated region to render into @return the bounding box of the given position
[ "Provides", "a", "mapping", "from", "the", "document", "model", "coordinate", "space", "to", "the", "coordinate", "space", "of", "the", "view", "mapped", "to", "it", "." ]
train
https://github.com/radkovo/SwingBox/blob/ff370f3dc54d248e4c8852c17513618c83c25984/src/main/java/org/fit/cssbox/swingbox/view/DelegateView.java#L358-L364
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/FitLinesToContour.java
FitLinesToContour.fitLine
boolean fitLine( int contourIndex0 , int contourIndex1 , LineGeneral2D_F64 line ) { """ Given a sequence of points on the contour find the best fit line. @param contourIndex0 contour index of first point in the sequence @param contourIndex1 contour index of last point (exclusive) in the sequence @param line storage for the found line @return true if successful or false if it failed """ int numPixels = CircularIndex.distanceP(contourIndex0,contourIndex1,contour.size()); // if its too small if( numPixels < minimumLineLength ) return false; Point2D_I32 c0 = contour.get(contourIndex0); Point2D_I32 c1 = contour.get(contourIndex1); double scale = c0.distance(c1); double centerX = (c1.x+c0.x)/2.0; double centerY = (c1.y+c0.y)/2.0; int numSamples = Math.min(maxSamples,numPixels); pointsFit.reset(); for (int i = 0; i < numSamples; i++) { int index = i*(numPixels-1)/(numSamples-1); Point2D_I32 c = contour.get( CircularIndex.addOffset(contourIndex0,index,contour.size())); Point2D_F64 p = pointsFit.grow(); p.x = (c.x-centerX)/scale; p.y = (c.y-centerY)/scale; } if( null == FitLine_F64.polar(pointsFit.toList(),linePolar) ) { return false; } UtilLine2D_F64.convert(linePolar,line); // go from local coordinates into global line.C = scale*line.C - centerX*line.A - centerY*line.B; return true; }
java
boolean fitLine( int contourIndex0 , int contourIndex1 , LineGeneral2D_F64 line ) { int numPixels = CircularIndex.distanceP(contourIndex0,contourIndex1,contour.size()); // if its too small if( numPixels < minimumLineLength ) return false; Point2D_I32 c0 = contour.get(contourIndex0); Point2D_I32 c1 = contour.get(contourIndex1); double scale = c0.distance(c1); double centerX = (c1.x+c0.x)/2.0; double centerY = (c1.y+c0.y)/2.0; int numSamples = Math.min(maxSamples,numPixels); pointsFit.reset(); for (int i = 0; i < numSamples; i++) { int index = i*(numPixels-1)/(numSamples-1); Point2D_I32 c = contour.get( CircularIndex.addOffset(contourIndex0,index,contour.size())); Point2D_F64 p = pointsFit.grow(); p.x = (c.x-centerX)/scale; p.y = (c.y-centerY)/scale; } if( null == FitLine_F64.polar(pointsFit.toList(),linePolar) ) { return false; } UtilLine2D_F64.convert(linePolar,line); // go from local coordinates into global line.C = scale*line.C - centerX*line.A - centerY*line.B; return true; }
[ "boolean", "fitLine", "(", "int", "contourIndex0", ",", "int", "contourIndex1", ",", "LineGeneral2D_F64", "line", ")", "{", "int", "numPixels", "=", "CircularIndex", ".", "distanceP", "(", "contourIndex0", ",", "contourIndex1", ",", "contour", ".", "size", "(", ")", ")", ";", "// if its too small", "if", "(", "numPixels", "<", "minimumLineLength", ")", "return", "false", ";", "Point2D_I32", "c0", "=", "contour", ".", "get", "(", "contourIndex0", ")", ";", "Point2D_I32", "c1", "=", "contour", ".", "get", "(", "contourIndex1", ")", ";", "double", "scale", "=", "c0", ".", "distance", "(", "c1", ")", ";", "double", "centerX", "=", "(", "c1", ".", "x", "+", "c0", ".", "x", ")", "/", "2.0", ";", "double", "centerY", "=", "(", "c1", ".", "y", "+", "c0", ".", "y", ")", "/", "2.0", ";", "int", "numSamples", "=", "Math", ".", "min", "(", "maxSamples", ",", "numPixels", ")", ";", "pointsFit", ".", "reset", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numSamples", ";", "i", "++", ")", "{", "int", "index", "=", "i", "*", "(", "numPixels", "-", "1", ")", "/", "(", "numSamples", "-", "1", ")", ";", "Point2D_I32", "c", "=", "contour", ".", "get", "(", "CircularIndex", ".", "addOffset", "(", "contourIndex0", ",", "index", ",", "contour", ".", "size", "(", ")", ")", ")", ";", "Point2D_F64", "p", "=", "pointsFit", ".", "grow", "(", ")", ";", "p", ".", "x", "=", "(", "c", ".", "x", "-", "centerX", ")", "/", "scale", ";", "p", ".", "y", "=", "(", "c", ".", "y", "-", "centerY", ")", "/", "scale", ";", "}", "if", "(", "null", "==", "FitLine_F64", ".", "polar", "(", "pointsFit", ".", "toList", "(", ")", ",", "linePolar", ")", ")", "{", "return", "false", ";", "}", "UtilLine2D_F64", ".", "convert", "(", "linePolar", ",", "line", ")", ";", "// go from local coordinates into global", "line", ".", "C", "=", "scale", "*", "line", ".", "C", "-", "centerX", "*", "line", ".", "A", "-", "centerY", "*", "line", ".", "B", ";", "return", "true", ";", "}" ]
Given a sequence of points on the contour find the best fit line. @param contourIndex0 contour index of first point in the sequence @param contourIndex1 contour index of last point (exclusive) in the sequence @param line storage for the found line @return true if successful or false if it failed
[ "Given", "a", "sequence", "of", "points", "on", "the", "contour", "find", "the", "best", "fit", "line", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/FitLinesToContour.java#L298-L335
carewebframework/carewebframework-vista
org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/Request.java
Request.addParameters
public void addParameters(Map<String, Object> parameters, boolean suppressNull) { """ Adds map-based parameters to the request. @param parameters Map of parameters. @param suppressNull If true, ignore null parameters. """ for (String name : parameters.keySet()) { Object value = parameters.get(name); if (!suppressNull || value != null) { addParameter(name, value); } } }
java
public void addParameters(Map<String, Object> parameters, boolean suppressNull) { for (String name : parameters.keySet()) { Object value = parameters.get(name); if (!suppressNull || value != null) { addParameter(name, value); } } }
[ "public", "void", "addParameters", "(", "Map", "<", "String", ",", "Object", ">", "parameters", ",", "boolean", "suppressNull", ")", "{", "for", "(", "String", "name", ":", "parameters", ".", "keySet", "(", ")", ")", "{", "Object", "value", "=", "parameters", ".", "get", "(", "name", ")", ";", "if", "(", "!", "suppressNull", "||", "value", "!=", "null", ")", "{", "addParameter", "(", "name", ",", "value", ")", ";", "}", "}", "}" ]
Adds map-based parameters to the request. @param parameters Map of parameters. @param suppressNull If true, ignore null parameters.
[ "Adds", "map", "-", "based", "parameters", "to", "the", "request", "." ]
train
https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/Request.java#L136-L145
Stratio/Decision
api/src/main/scala/com/stratio/decision/api/partitioner/JenkinsHash.java
JenkinsHash.gatherPartialLongLE
private static final long gatherPartialLongLE(final byte[] data, final int index, final int available) { """ gather a partial long from the specified index using the specified number of bytes into the byte array """ if(available >= 4) { int i = gatherIntLE(data, index); long l = uintToLong(i); int left = available - 4; if(left == 0) { return l; } int i2 = gatherPartialIntLE(data, index + 4, left); l <<= (left << 3); l |= (long) i2; return l; } else { return (long) gatherPartialIntLE(data, index, available); } }
java
private static final long gatherPartialLongLE(final byte[] data, final int index, final int available) { if(available >= 4) { int i = gatherIntLE(data, index); long l = uintToLong(i); int left = available - 4; if(left == 0) { return l; } int i2 = gatherPartialIntLE(data, index + 4, left); l <<= (left << 3); l |= (long) i2; return l; } else { return (long) gatherPartialIntLE(data, index, available); } }
[ "private", "static", "final", "long", "gatherPartialLongLE", "(", "final", "byte", "[", "]", "data", ",", "final", "int", "index", ",", "final", "int", "available", ")", "{", "if", "(", "available", ">=", "4", ")", "{", "int", "i", "=", "gatherIntLE", "(", "data", ",", "index", ")", ";", "long", "l", "=", "uintToLong", "(", "i", ")", ";", "int", "left", "=", "available", "-", "4", ";", "if", "(", "left", "==", "0", ")", "{", "return", "l", ";", "}", "int", "i2", "=", "gatherPartialIntLE", "(", "data", ",", "index", "+", "4", ",", "left", ")", ";", "l", "<<=", "(", "left", "<<", "3", ")", ";", "l", "|=", "(", "long", ")", "i2", ";", "return", "l", ";", "}", "else", "{", "return", "(", "long", ")", "gatherPartialIntLE", "(", "data", ",", "index", ",", "available", ")", ";", "}", "}" ]
gather a partial long from the specified index using the specified number of bytes into the byte array
[ "gather", "a", "partial", "long", "from", "the", "specified", "index", "using", "the", "specified", "number", "of", "bytes", "into", "the", "byte", "array" ]
train
https://github.com/Stratio/Decision/blob/675eb4f005031bfcaa6cf43200f37aa5ba288139/api/src/main/scala/com/stratio/decision/api/partitioner/JenkinsHash.java#L434-L454
Azure/azure-sdk-for-java
appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java
AppServiceCertificateOrdersInner.verifyDomainOwnershipAsync
public Observable<Void> verifyDomainOwnershipAsync(String resourceGroupName, String certificateOrderName) { """ Verify domain ownership for this certificate order. Verify domain ownership for this certificate order. @param resourceGroupName Name of the resource group to which the resource belongs. @param certificateOrderName Name of the certificate order. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful. """ return verifyDomainOwnershipWithServiceResponseAsync(resourceGroupName, certificateOrderName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> verifyDomainOwnershipAsync(String resourceGroupName, String certificateOrderName) { return verifyDomainOwnershipWithServiceResponseAsync(resourceGroupName, certificateOrderName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "verifyDomainOwnershipAsync", "(", "String", "resourceGroupName", ",", "String", "certificateOrderName", ")", "{", "return", "verifyDomainOwnershipWithServiceResponseAsync", "(", "resourceGroupName", ",", "certificateOrderName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Verify domain ownership for this certificate order. Verify domain ownership for this certificate order. @param resourceGroupName Name of the resource group to which the resource belongs. @param certificateOrderName Name of the certificate order. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Verify", "domain", "ownership", "for", "this", "certificate", "order", ".", "Verify", "domain", "ownership", "for", "this", "certificate", "order", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java#L2171-L2178
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/internal/provisioning/api/SamlSettingsApi.java
SamlSettingsApi.getSPMetadataAsync
public com.squareup.okhttp.Call getSPMetadataAsync(String location, Boolean download, Boolean noSpinner, final ApiCallback<GetSPMetadataResponse> callback) throws ApiException { """ Get Metadata (asynchronously) Returns exist Metadata xml file. @param location Define SAML location. (required) @param download Define if need download file. (required) @param noSpinner Define if need page reload (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object """ ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getSPMetadataValidateBeforeCall(location, download, noSpinner, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<GetSPMetadataResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
java
public com.squareup.okhttp.Call getSPMetadataAsync(String location, Boolean download, Boolean noSpinner, final ApiCallback<GetSPMetadataResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getSPMetadataValidateBeforeCall(location, download, noSpinner, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<GetSPMetadataResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "getSPMetadataAsync", "(", "String", "location", ",", "Boolean", "download", ",", "Boolean", "noSpinner", ",", "final", "ApiCallback", "<", "GetSPMetadataResponse", ">", "callback", ")", "throws", "ApiException", "{", "ProgressResponseBody", ".", "ProgressListener", "progressListener", "=", "null", ";", "ProgressRequestBody", ".", "ProgressRequestListener", "progressRequestListener", "=", "null", ";", "if", "(", "callback", "!=", "null", ")", "{", "progressListener", "=", "new", "ProgressResponseBody", ".", "ProgressListener", "(", ")", "{", "@", "Override", "public", "void", "update", "(", "long", "bytesRead", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onDownloadProgress", "(", "bytesRead", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "progressRequestListener", "=", "new", "ProgressRequestBody", ".", "ProgressRequestListener", "(", ")", "{", "@", "Override", "public", "void", "onRequestProgress", "(", "long", "bytesWritten", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onUploadProgress", "(", "bytesWritten", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "}", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "getSPMetadataValidateBeforeCall", "(", "location", ",", "download", ",", "noSpinner", ",", "progressListener", ",", "progressRequestListener", ")", ";", "Type", "localVarReturnType", "=", "new", "TypeToken", "<", "GetSPMetadataResponse", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "apiClient", ".", "executeAsync", "(", "call", ",", "localVarReturnType", ",", "callback", ")", ";", "return", "call", ";", "}" ]
Get Metadata (asynchronously) Returns exist Metadata xml file. @param location Define SAML location. (required) @param download Define if need download file. (required) @param noSpinner Define if need page reload (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "Get", "Metadata", "(", "asynchronously", ")", "Returns", "exist", "Metadata", "xml", "file", "." ]
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/SamlSettingsApi.java#L653-L678
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/deployer/BpmnDeployer.java
BpmnDeployer.adjustStartEventSubscriptions
protected void adjustStartEventSubscriptions(ProcessDefinitionEntity newLatestProcessDefinition, ProcessDefinitionEntity oldLatestProcessDefinition) { """ adjust all event subscriptions responsible to start process instances (timer start event, message start event). The default behavior is to remove the old subscriptions and add new ones for the new deployed process definitions. """ removeObsoleteTimers(newLatestProcessDefinition); addTimerDeclarations(newLatestProcessDefinition); removeObsoleteEventSubscriptions(newLatestProcessDefinition, oldLatestProcessDefinition); addEventSubscriptions(newLatestProcessDefinition); }
java
protected void adjustStartEventSubscriptions(ProcessDefinitionEntity newLatestProcessDefinition, ProcessDefinitionEntity oldLatestProcessDefinition) { removeObsoleteTimers(newLatestProcessDefinition); addTimerDeclarations(newLatestProcessDefinition); removeObsoleteEventSubscriptions(newLatestProcessDefinition, oldLatestProcessDefinition); addEventSubscriptions(newLatestProcessDefinition); }
[ "protected", "void", "adjustStartEventSubscriptions", "(", "ProcessDefinitionEntity", "newLatestProcessDefinition", ",", "ProcessDefinitionEntity", "oldLatestProcessDefinition", ")", "{", "removeObsoleteTimers", "(", "newLatestProcessDefinition", ")", ";", "addTimerDeclarations", "(", "newLatestProcessDefinition", ")", ";", "removeObsoleteEventSubscriptions", "(", "newLatestProcessDefinition", ",", "oldLatestProcessDefinition", ")", ";", "addEventSubscriptions", "(", "newLatestProcessDefinition", ")", ";", "}" ]
adjust all event subscriptions responsible to start process instances (timer start event, message start event). The default behavior is to remove the old subscriptions and add new ones for the new deployed process definitions.
[ "adjust", "all", "event", "subscriptions", "responsible", "to", "start", "process", "instances", "(", "timer", "start", "event", "message", "start", "event", ")", ".", "The", "default", "behavior", "is", "to", "remove", "the", "old", "subscriptions", "and", "add", "new", "ones", "for", "the", "new", "deployed", "process", "definitions", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/deployer/BpmnDeployer.java#L225-L231
OpenLiberty/open-liberty
dev/com.ibm.ws.security.wim.adapter.ldap/src/com/ibm/ws/security/wim/adapter/ldap/context/ContextManager.java
ContextManager.createDirContext
private TimedDirContext createDirContext(Hashtable<String, Object> env) throws NamingException { """ Create a directory context. @param env The JNDI environment to create the context with. @return The {@link TimedDirContext}. @throws NamingException If there was an issue binding to the LDAP server. """ return createDirContext(env, roundToSeconds(System.currentTimeMillis())); }
java
private TimedDirContext createDirContext(Hashtable<String, Object> env) throws NamingException { return createDirContext(env, roundToSeconds(System.currentTimeMillis())); }
[ "private", "TimedDirContext", "createDirContext", "(", "Hashtable", "<", "String", ",", "Object", ">", "env", ")", "throws", "NamingException", "{", "return", "createDirContext", "(", "env", ",", "roundToSeconds", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ")", ";", "}" ]
Create a directory context. @param env The JNDI environment to create the context with. @return The {@link TimedDirContext}. @throws NamingException If there was an issue binding to the LDAP server.
[ "Create", "a", "directory", "context", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.wim.adapter.ldap/src/com/ibm/ws/security/wim/adapter/ldap/context/ContextManager.java#L379-L381
ltearno/hexa.tools
hexa.core/src/main/java/fr/lteconsulting/hexa/client/datatable/DataTableTools.java
DataTableTools.insertFlatList
public static <T extends IHasIntegerId> void insertFlatList( List<T> list, TableCollectionManager<T> mng, Func1<T, Integer> parentIdGetter ) { """ Inserts a flat list as a tree in a TableCollectionManager. It does insert data in the right order for the creation of the tree (parents must be inserted first) @param list @param mng @param parentIdGetter """ HashSet<Integer> inserted = new HashSet<>(); List<T> toInsert = new ArrayList<>( list ); List<T> postPoned = new ArrayList<>(); List<T> inOrder = new ArrayList<>(); int nbInserted; while( ! toInsert.isEmpty() ) { nbInserted = 0; while( ! toInsert.isEmpty() ) { T a = toInsert.remove( 0 ); Integer parentId = parentIdGetter.exec( a ); if( parentId==null || parentId<=0 || inserted.contains( parentId ) || mng.getRowForRecordId( parentId )!=null ) { inOrder.add( a ); inserted.add( a.getId() ); nbInserted++; } else { postPoned.add( a ); } } toInsert = postPoned; postPoned = new ArrayList<>(); if( nbInserted == 0 && ! toInsert.isEmpty() ) { GWT.log("Cannot construct full tree !"); throw new RuntimeException( "Cannot construct full tree !" ); } } for( T t : inOrder ) mng.getDataPlug().updated( t ); }
java
public static <T extends IHasIntegerId> void insertFlatList( List<T> list, TableCollectionManager<T> mng, Func1<T, Integer> parentIdGetter ) { HashSet<Integer> inserted = new HashSet<>(); List<T> toInsert = new ArrayList<>( list ); List<T> postPoned = new ArrayList<>(); List<T> inOrder = new ArrayList<>(); int nbInserted; while( ! toInsert.isEmpty() ) { nbInserted = 0; while( ! toInsert.isEmpty() ) { T a = toInsert.remove( 0 ); Integer parentId = parentIdGetter.exec( a ); if( parentId==null || parentId<=0 || inserted.contains( parentId ) || mng.getRowForRecordId( parentId )!=null ) { inOrder.add( a ); inserted.add( a.getId() ); nbInserted++; } else { postPoned.add( a ); } } toInsert = postPoned; postPoned = new ArrayList<>(); if( nbInserted == 0 && ! toInsert.isEmpty() ) { GWT.log("Cannot construct full tree !"); throw new RuntimeException( "Cannot construct full tree !" ); } } for( T t : inOrder ) mng.getDataPlug().updated( t ); }
[ "public", "static", "<", "T", "extends", "IHasIntegerId", ">", "void", "insertFlatList", "(", "List", "<", "T", ">", "list", ",", "TableCollectionManager", "<", "T", ">", "mng", ",", "Func1", "<", "T", ",", "Integer", ">", "parentIdGetter", ")", "{", "HashSet", "<", "Integer", ">", "inserted", "=", "new", "HashSet", "<>", "(", ")", ";", "List", "<", "T", ">", "toInsert", "=", "new", "ArrayList", "<>", "(", "list", ")", ";", "List", "<", "T", ">", "postPoned", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "T", ">", "inOrder", "=", "new", "ArrayList", "<>", "(", ")", ";", "int", "nbInserted", ";", "while", "(", "!", "toInsert", ".", "isEmpty", "(", ")", ")", "{", "nbInserted", "=", "0", ";", "while", "(", "!", "toInsert", ".", "isEmpty", "(", ")", ")", "{", "T", "a", "=", "toInsert", ".", "remove", "(", "0", ")", ";", "Integer", "parentId", "=", "parentIdGetter", ".", "exec", "(", "a", ")", ";", "if", "(", "parentId", "==", "null", "||", "parentId", "<=", "0", "||", "inserted", ".", "contains", "(", "parentId", ")", "||", "mng", ".", "getRowForRecordId", "(", "parentId", ")", "!=", "null", ")", "{", "inOrder", ".", "add", "(", "a", ")", ";", "inserted", ".", "add", "(", "a", ".", "getId", "(", ")", ")", ";", "nbInserted", "++", ";", "}", "else", "{", "postPoned", ".", "add", "(", "a", ")", ";", "}", "}", "toInsert", "=", "postPoned", ";", "postPoned", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "nbInserted", "==", "0", "&&", "!", "toInsert", ".", "isEmpty", "(", ")", ")", "{", "GWT", ".", "log", "(", "\"Cannot construct full tree !\"", ")", ";", "throw", "new", "RuntimeException", "(", "\"Cannot construct full tree !\"", ")", ";", "}", "}", "for", "(", "T", "t", ":", "inOrder", ")", "mng", ".", "getDataPlug", "(", ")", ".", "updated", "(", "t", ")", ";", "}" ]
Inserts a flat list as a tree in a TableCollectionManager. It does insert data in the right order for the creation of the tree (parents must be inserted first) @param list @param mng @param parentIdGetter
[ "Inserts", "a", "flat", "list", "as", "a", "tree", "in", "a", "TableCollectionManager", ".", "It", "does", "insert", "data", "in", "the", "right", "order", "for", "the", "creation", "of", "the", "tree", "(", "parents", "must", "be", "inserted", "first", ")" ]
train
https://github.com/ltearno/hexa.tools/blob/604c804901b1bb13fe10b3823cc4a639f8993363/hexa.core/src/main/java/fr/lteconsulting/hexa/client/datatable/DataTableTools.java#L27-L69
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/XDMAuditor.java
XDMAuditor.auditPortableMediaCreate
public void auditPortableMediaCreate( RFC3881EventOutcomeCodes eventOutcome, String submissionSetUniqueId, String patientId, List<CodedValueType> purposesOfUse) { """ Audits a PHI Export event for the IHE XDM Portable Media Creator actor, ITI-32 Distribute Document Set on Media transaction. @param eventOutcome The event outcome indicator @param submissionSetUniqueId The Unique ID of the Submission Set exported @param patientId The ID of the Patient to which the Submission Set pertains """ if (!isAuditorEnabled()) { return; } ExportEvent exportEvent = new ExportEvent(true, eventOutcome, new IHETransactionEventTypeCodes.DistributeDocumentSetOnMedia(), purposesOfUse); exportEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId()); exportEvent.addSourceActiveParticipant(getSystemUserId(), getSystemAltUserId(), getSystemUserName(), getSystemNetworkId(), true); if (!EventUtils.isEmptyOrNull(patientId)) { exportEvent.addPatientParticipantObject(patientId); } exportEvent.addSubmissionSetParticipantObject(submissionSetUniqueId); audit(exportEvent); }
java
public void auditPortableMediaCreate( RFC3881EventOutcomeCodes eventOutcome, String submissionSetUniqueId, String patientId, List<CodedValueType> purposesOfUse) { if (!isAuditorEnabled()) { return; } ExportEvent exportEvent = new ExportEvent(true, eventOutcome, new IHETransactionEventTypeCodes.DistributeDocumentSetOnMedia(), purposesOfUse); exportEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId()); exportEvent.addSourceActiveParticipant(getSystemUserId(), getSystemAltUserId(), getSystemUserName(), getSystemNetworkId(), true); if (!EventUtils.isEmptyOrNull(patientId)) { exportEvent.addPatientParticipantObject(patientId); } exportEvent.addSubmissionSetParticipantObject(submissionSetUniqueId); audit(exportEvent); }
[ "public", "void", "auditPortableMediaCreate", "(", "RFC3881EventOutcomeCodes", "eventOutcome", ",", "String", "submissionSetUniqueId", ",", "String", "patientId", ",", "List", "<", "CodedValueType", ">", "purposesOfUse", ")", "{", "if", "(", "!", "isAuditorEnabled", "(", ")", ")", "{", "return", ";", "}", "ExportEvent", "exportEvent", "=", "new", "ExportEvent", "(", "true", ",", "eventOutcome", ",", "new", "IHETransactionEventTypeCodes", ".", "DistributeDocumentSetOnMedia", "(", ")", ",", "purposesOfUse", ")", ";", "exportEvent", ".", "setAuditSourceId", "(", "getAuditSourceId", "(", ")", ",", "getAuditEnterpriseSiteId", "(", ")", ")", ";", "exportEvent", ".", "addSourceActiveParticipant", "(", "getSystemUserId", "(", ")", ",", "getSystemAltUserId", "(", ")", ",", "getSystemUserName", "(", ")", ",", "getSystemNetworkId", "(", ")", ",", "true", ")", ";", "if", "(", "!", "EventUtils", ".", "isEmptyOrNull", "(", "patientId", ")", ")", "{", "exportEvent", ".", "addPatientParticipantObject", "(", "patientId", ")", ";", "}", "exportEvent", ".", "addSubmissionSetParticipantObject", "(", "submissionSetUniqueId", ")", ";", "audit", "(", "exportEvent", ")", ";", "}" ]
Audits a PHI Export event for the IHE XDM Portable Media Creator actor, ITI-32 Distribute Document Set on Media transaction. @param eventOutcome The event outcome indicator @param submissionSetUniqueId The Unique ID of the Submission Set exported @param patientId The ID of the Patient to which the Submission Set pertains
[ "Audits", "a", "PHI", "Export", "event", "for", "the", "IHE", "XDM", "Portable", "Media", "Creator", "actor", "ITI", "-", "32", "Distribute", "Document", "Set", "on", "Media", "transaction", "." ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/XDMAuditor.java#L81-L98
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java
ThreadLocalRandom.nextDouble
public double nextDouble(double origin, double bound) { """ Returns a pseudorandom {@code double} value between the specified origin (inclusive) and bound (exclusive). @param origin the least value returned @param bound the upper bound (exclusive) @return a pseudorandom {@code double} value between the origin (inclusive) and the bound (exclusive) @throws IllegalArgumentException if {@code origin} is greater than or equal to {@code bound} """ if (!(origin < bound)) throw new IllegalArgumentException(BAD_RANGE); return internalNextDouble(origin, bound); }
java
public double nextDouble(double origin, double bound) { if (!(origin < bound)) throw new IllegalArgumentException(BAD_RANGE); return internalNextDouble(origin, bound); }
[ "public", "double", "nextDouble", "(", "double", "origin", ",", "double", "bound", ")", "{", "if", "(", "!", "(", "origin", "<", "bound", ")", ")", "throw", "new", "IllegalArgumentException", "(", "BAD_RANGE", ")", ";", "return", "internalNextDouble", "(", "origin", ",", "bound", ")", ";", "}" ]
Returns a pseudorandom {@code double} value between the specified origin (inclusive) and bound (exclusive). @param origin the least value returned @param bound the upper bound (exclusive) @return a pseudorandom {@code double} value between the origin (inclusive) and the bound (exclusive) @throws IllegalArgumentException if {@code origin} is greater than or equal to {@code bound}
[ "Returns", "a", "pseudorandom", "{", "@code", "double", "}", "value", "between", "the", "specified", "origin", "(", "inclusive", ")", "and", "bound", "(", "exclusive", ")", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java#L418-L422
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-default/src/main/java/org/xwiki/component/embed/EmbeddableComponentManager.java
EmbeddableComponentManager.removeComponentWithoutException
private void removeComponentWithoutException(Type role, String hint) { """ Note: This method shouldn't exist but register/unregister methods should throw a {@link ComponentLifecycleException} but that would break backward compatibility to add it. """ try { removeComponent(role, hint); } catch (Exception e) { this.logger.warn("Instance released but disposal failed. Some resources may not have been released.", e); } }
java
private void removeComponentWithoutException(Type role, String hint) { try { removeComponent(role, hint); } catch (Exception e) { this.logger.warn("Instance released but disposal failed. Some resources may not have been released.", e); } }
[ "private", "void", "removeComponentWithoutException", "(", "Type", "role", ",", "String", "hint", ")", "{", "try", "{", "removeComponent", "(", "role", ",", "hint", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "this", ".", "logger", ".", "warn", "(", "\"Instance released but disposal failed. Some resources may not have been released.\"", ",", "e", ")", ";", "}", "}" ]
Note: This method shouldn't exist but register/unregister methods should throw a {@link ComponentLifecycleException} but that would break backward compatibility to add it.
[ "Note", ":", "This", "method", "shouldn", "t", "exist", "but", "register", "/", "unregister", "methods", "should", "throw", "a", "{" ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-default/src/main/java/org/xwiki/component/embed/EmbeddableComponentManager.java#L605-L612
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/DistributedFlowletInstanceUpdater.java
DistributedFlowletInstanceUpdater.waitForInstances
private void waitForInstances(String flowletId, int expectedInstances) throws InterruptedException, TimeoutException { """ it cannot change instances without being in the suspended state. """ int numRunningFlowlets = getNumberOfProvisionedInstances(flowletId); int secondsWaited = 0; while (numRunningFlowlets != expectedInstances) { LOG.debug("waiting for {} instances of {} before suspending flowlets", expectedInstances, flowletId); TimeUnit.SECONDS.sleep(SECONDS_PER_WAIT); secondsWaited += SECONDS_PER_WAIT; if (secondsWaited > MAX_WAIT_SECONDS) { String errmsg = String.format("waited %d seconds for instances of %s to reach expected count of %d, but %d are running", secondsWaited, flowletId, expectedInstances, numRunningFlowlets); LOG.error(errmsg); throw new TimeoutException(errmsg); } numRunningFlowlets = getNumberOfProvisionedInstances(flowletId); } }
java
private void waitForInstances(String flowletId, int expectedInstances) throws InterruptedException, TimeoutException { int numRunningFlowlets = getNumberOfProvisionedInstances(flowletId); int secondsWaited = 0; while (numRunningFlowlets != expectedInstances) { LOG.debug("waiting for {} instances of {} before suspending flowlets", expectedInstances, flowletId); TimeUnit.SECONDS.sleep(SECONDS_PER_WAIT); secondsWaited += SECONDS_PER_WAIT; if (secondsWaited > MAX_WAIT_SECONDS) { String errmsg = String.format("waited %d seconds for instances of %s to reach expected count of %d, but %d are running", secondsWaited, flowletId, expectedInstances, numRunningFlowlets); LOG.error(errmsg); throw new TimeoutException(errmsg); } numRunningFlowlets = getNumberOfProvisionedInstances(flowletId); } }
[ "private", "void", "waitForInstances", "(", "String", "flowletId", ",", "int", "expectedInstances", ")", "throws", "InterruptedException", ",", "TimeoutException", "{", "int", "numRunningFlowlets", "=", "getNumberOfProvisionedInstances", "(", "flowletId", ")", ";", "int", "secondsWaited", "=", "0", ";", "while", "(", "numRunningFlowlets", "!=", "expectedInstances", ")", "{", "LOG", ".", "debug", "(", "\"waiting for {} instances of {} before suspending flowlets\"", ",", "expectedInstances", ",", "flowletId", ")", ";", "TimeUnit", ".", "SECONDS", ".", "sleep", "(", "SECONDS_PER_WAIT", ")", ";", "secondsWaited", "+=", "SECONDS_PER_WAIT", ";", "if", "(", "secondsWaited", ">", "MAX_WAIT_SECONDS", ")", "{", "String", "errmsg", "=", "String", ".", "format", "(", "\"waited %d seconds for instances of %s to reach expected count of %d, but %d are running\"", ",", "secondsWaited", ",", "flowletId", ",", "expectedInstances", ",", "numRunningFlowlets", ")", ";", "LOG", ".", "error", "(", "errmsg", ")", ";", "throw", "new", "TimeoutException", "(", "errmsg", ")", ";", "}", "numRunningFlowlets", "=", "getNumberOfProvisionedInstances", "(", "flowletId", ")", ";", "}", "}" ]
it cannot change instances without being in the suspended state.
[ "it", "cannot", "change", "instances", "without", "being", "in", "the", "suspended", "state", "." ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/DistributedFlowletInstanceUpdater.java#L75-L91
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java
CassandraSchemaManager.getColumnMetadata
private ColumnDef getColumnMetadata(ColumnInfo columnInfo, TableInfo tableInfo) { """ getColumnMetadata use for getting column metadata for specific columnInfo. @param columnInfo the column info @param tableInfo the table info @return the column metadata """ ColumnDef columnDef = new ColumnDef(); columnDef.setName(columnInfo.getColumnName().getBytes()); columnDef.setValidation_class(CassandraValidationClassMapper.getValidationClass(columnInfo.getType(), isCql3Enabled(tableInfo))); if (columnInfo.isIndexable()) { IndexInfo indexInfo = tableInfo.getColumnToBeIndexed(columnInfo.getColumnName()); columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType())); // if (!indexInfo.getIndexName().equals(indexInfo.getColumnName())) // { // columnDef.setIndex_name(indexInfo.getIndexName()); // } } return columnDef; }
java
private ColumnDef getColumnMetadata(ColumnInfo columnInfo, TableInfo tableInfo) { ColumnDef columnDef = new ColumnDef(); columnDef.setName(columnInfo.getColumnName().getBytes()); columnDef.setValidation_class(CassandraValidationClassMapper.getValidationClass(columnInfo.getType(), isCql3Enabled(tableInfo))); if (columnInfo.isIndexable()) { IndexInfo indexInfo = tableInfo.getColumnToBeIndexed(columnInfo.getColumnName()); columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType())); // if (!indexInfo.getIndexName().equals(indexInfo.getColumnName())) // { // columnDef.setIndex_name(indexInfo.getIndexName()); // } } return columnDef; }
[ "private", "ColumnDef", "getColumnMetadata", "(", "ColumnInfo", "columnInfo", ",", "TableInfo", "tableInfo", ")", "{", "ColumnDef", "columnDef", "=", "new", "ColumnDef", "(", ")", ";", "columnDef", ".", "setName", "(", "columnInfo", ".", "getColumnName", "(", ")", ".", "getBytes", "(", ")", ")", ";", "columnDef", ".", "setValidation_class", "(", "CassandraValidationClassMapper", ".", "getValidationClass", "(", "columnInfo", ".", "getType", "(", ")", ",", "isCql3Enabled", "(", "tableInfo", ")", ")", ")", ";", "if", "(", "columnInfo", ".", "isIndexable", "(", ")", ")", "{", "IndexInfo", "indexInfo", "=", "tableInfo", ".", "getColumnToBeIndexed", "(", "columnInfo", ".", "getColumnName", "(", ")", ")", ";", "columnDef", ".", "setIndex_type", "(", "CassandraIndexHelper", ".", "getIndexType", "(", "indexInfo", ".", "getIndexType", "(", ")", ")", ")", ";", "// if (!indexInfo.getIndexName().equals(indexInfo.getColumnName()))", "// {", "// columnDef.setIndex_name(indexInfo.getIndexName());", "// }", "}", "return", "columnDef", ";", "}" ]
getColumnMetadata use for getting column metadata for specific columnInfo. @param columnInfo the column info @param tableInfo the table info @return the column metadata
[ "getColumnMetadata", "use", "for", "getting", "column", "metadata", "for", "specific", "columnInfo", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java#L2130-L2147
TakahikoKawasaki/nv-websocket-client
src/main/java/com/neovisionaries/ws/client/ByteArray.java
ByteArray.put
public void put(byte[] source, int index, int length) { """ Add data at the current position. @param source Source data. @param index The index in the source data. Data from the index is copied. @param length The length of data to copy. """ // If the buffer is small. if (mBuffer.capacity() < (mLength + length)) { expandBuffer(mLength + length + ADDITIONAL_BUFFER_SIZE); } mBuffer.put(source, index, length); mLength += length; }
java
public void put(byte[] source, int index, int length) { // If the buffer is small. if (mBuffer.capacity() < (mLength + length)) { expandBuffer(mLength + length + ADDITIONAL_BUFFER_SIZE); } mBuffer.put(source, index, length); mLength += length; }
[ "public", "void", "put", "(", "byte", "[", "]", "source", ",", "int", "index", ",", "int", "length", ")", "{", "// If the buffer is small.", "if", "(", "mBuffer", ".", "capacity", "(", ")", "<", "(", "mLength", "+", "length", ")", ")", "{", "expandBuffer", "(", "mLength", "+", "length", "+", "ADDITIONAL_BUFFER_SIZE", ")", ";", "}", "mBuffer", ".", "put", "(", "source", ",", "index", ",", "length", ")", ";", "mLength", "+=", "length", ";", "}" ]
Add data at the current position. @param source Source data. @param index The index in the source data. Data from the index is copied. @param length The length of data to copy.
[ "Add", "data", "at", "the", "current", "position", "." ]
train
https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/ByteArray.java#L154-L164
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LocalNetworkGatewaysInner.java
LocalNetworkGatewaysInner.beginUpdateTagsAsync
public Observable<LocalNetworkGatewayInner> beginUpdateTagsAsync(String resourceGroupName, String localNetworkGatewayName, Map<String, String> tags) { """ Updates a local network gateway tags. @param resourceGroupName The name of the resource group. @param localNetworkGatewayName The name of the local network gateway. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the LocalNetworkGatewayInner object """ return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, localNetworkGatewayName, tags).map(new Func1<ServiceResponse<LocalNetworkGatewayInner>, LocalNetworkGatewayInner>() { @Override public LocalNetworkGatewayInner call(ServiceResponse<LocalNetworkGatewayInner> response) { return response.body(); } }); }
java
public Observable<LocalNetworkGatewayInner> beginUpdateTagsAsync(String resourceGroupName, String localNetworkGatewayName, Map<String, String> tags) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, localNetworkGatewayName, tags).map(new Func1<ServiceResponse<LocalNetworkGatewayInner>, LocalNetworkGatewayInner>() { @Override public LocalNetworkGatewayInner call(ServiceResponse<LocalNetworkGatewayInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "LocalNetworkGatewayInner", ">", "beginUpdateTagsAsync", "(", "String", "resourceGroupName", ",", "String", "localNetworkGatewayName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "beginUpdateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "localNetworkGatewayName", ",", "tags", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "LocalNetworkGatewayInner", ">", ",", "LocalNetworkGatewayInner", ">", "(", ")", "{", "@", "Override", "public", "LocalNetworkGatewayInner", "call", "(", "ServiceResponse", "<", "LocalNetworkGatewayInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates a local network gateway tags. @param resourceGroupName The name of the resource group. @param localNetworkGatewayName The name of the local network gateway. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the LocalNetworkGatewayInner object
[ "Updates", "a", "local", "network", "gateway", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LocalNetworkGatewaysInner.java#L771-L778
vincentk/joptimizer
src/main/java/com/joptimizer/optimizers/LPPrimalDualMethod.java
LPPrimalDualMethod.optimize
@Override public int optimize() throws Exception { """ Solves an LP in the form of: min(c) s.t. A.x = b G.x < h lb <= x <= ub """ log.info("optimize"); LPOptimizationRequest lpRequest = getLPOptimizationRequest(); if(log.isDebugEnabled() && lpRequest.isDumpProblem()){ log.debug("LP problem: " + lpRequest.toString()); } //standard form conversion LPStandardConverter lpConverter = new LPStandardConverter();//the slack variables will have default unboundedUBValue lpConverter.toStandardForm(getC(), getG(), getH(), getA(), getB(), getLb(), getUb()); int nOfSlackVariables = lpConverter.getStandardS(); log.debug("nOfSlackVariables: " + nOfSlackVariables); DoubleMatrix1D standardC = lpConverter.getStandardC(); DoubleMatrix2D standardA = lpConverter.getStandardA(); DoubleMatrix1D standardB = lpConverter.getStandardB(); DoubleMatrix1D standardLb = lpConverter.getStandardLB(); DoubleMatrix1D standardUb = lpConverter.getStandardUB(); //solve the standard form problem LPOptimizationRequest standardLPRequest = lpRequest.cloneMe(); standardLPRequest.setC(standardC); standardLPRequest.setA(standardA); standardLPRequest.setB(standardB); standardLPRequest.setLb(ColtUtils.replaceValues(standardLb, lpConverter.getUnboundedLBValue(), minLBValue));//substitute not-double numbers standardLPRequest.setUb(ColtUtils.replaceValues(standardUb, lpConverter.getUnboundedUBValue(), maxUBValue));//substitute not-double numbers if(getInitialPoint()!=null){ standardLPRequest.setInitialPoint(lpConverter.getStandardComponents(getInitialPoint().toArray())); } if(getNotFeasibleInitialPoint()!=null){ standardLPRequest.setNotFeasibleInitialPoint(lpConverter.getStandardComponents(getNotFeasibleInitialPoint().toArray())); } //optimization LPPrimalDualMethod opt = new LPPrimalDualMethod(minLBValue, maxUBValue); opt.setLPOptimizationRequest(standardLPRequest); if(opt.optimizeStandardLP(nOfSlackVariables) == OptimizationResponse.FAILED){ return OptimizationResponse.FAILED; } //back to original form LPOptimizationResponse lpResponse = opt.getLPOptimizationResponse(); double[] standardSolution = lpResponse.getSolution(); double[] originalSol = lpConverter.postConvert(standardSolution); lpResponse.setSolution(originalSol); setLPOptimizationResponse(lpResponse); return lpResponse.getReturnCode(); }
java
@Override public int optimize() throws Exception { log.info("optimize"); LPOptimizationRequest lpRequest = getLPOptimizationRequest(); if(log.isDebugEnabled() && lpRequest.isDumpProblem()){ log.debug("LP problem: " + lpRequest.toString()); } //standard form conversion LPStandardConverter lpConverter = new LPStandardConverter();//the slack variables will have default unboundedUBValue lpConverter.toStandardForm(getC(), getG(), getH(), getA(), getB(), getLb(), getUb()); int nOfSlackVariables = lpConverter.getStandardS(); log.debug("nOfSlackVariables: " + nOfSlackVariables); DoubleMatrix1D standardC = lpConverter.getStandardC(); DoubleMatrix2D standardA = lpConverter.getStandardA(); DoubleMatrix1D standardB = lpConverter.getStandardB(); DoubleMatrix1D standardLb = lpConverter.getStandardLB(); DoubleMatrix1D standardUb = lpConverter.getStandardUB(); //solve the standard form problem LPOptimizationRequest standardLPRequest = lpRequest.cloneMe(); standardLPRequest.setC(standardC); standardLPRequest.setA(standardA); standardLPRequest.setB(standardB); standardLPRequest.setLb(ColtUtils.replaceValues(standardLb, lpConverter.getUnboundedLBValue(), minLBValue));//substitute not-double numbers standardLPRequest.setUb(ColtUtils.replaceValues(standardUb, lpConverter.getUnboundedUBValue(), maxUBValue));//substitute not-double numbers if(getInitialPoint()!=null){ standardLPRequest.setInitialPoint(lpConverter.getStandardComponents(getInitialPoint().toArray())); } if(getNotFeasibleInitialPoint()!=null){ standardLPRequest.setNotFeasibleInitialPoint(lpConverter.getStandardComponents(getNotFeasibleInitialPoint().toArray())); } //optimization LPPrimalDualMethod opt = new LPPrimalDualMethod(minLBValue, maxUBValue); opt.setLPOptimizationRequest(standardLPRequest); if(opt.optimizeStandardLP(nOfSlackVariables) == OptimizationResponse.FAILED){ return OptimizationResponse.FAILED; } //back to original form LPOptimizationResponse lpResponse = opt.getLPOptimizationResponse(); double[] standardSolution = lpResponse.getSolution(); double[] originalSol = lpConverter.postConvert(standardSolution); lpResponse.setSolution(originalSol); setLPOptimizationResponse(lpResponse); return lpResponse.getReturnCode(); }
[ "@", "Override", "public", "int", "optimize", "(", ")", "throws", "Exception", "{", "log", ".", "info", "(", "\"optimize\"", ")", ";", "LPOptimizationRequest", "lpRequest", "=", "getLPOptimizationRequest", "(", ")", ";", "if", "(", "log", ".", "isDebugEnabled", "(", ")", "&&", "lpRequest", ".", "isDumpProblem", "(", ")", ")", "{", "log", ".", "debug", "(", "\"LP problem: \"", "+", "lpRequest", ".", "toString", "(", ")", ")", ";", "}", "//standard form conversion\r", "LPStandardConverter", "lpConverter", "=", "new", "LPStandardConverter", "(", ")", ";", "//the slack variables will have default unboundedUBValue\r", "lpConverter", ".", "toStandardForm", "(", "getC", "(", ")", ",", "getG", "(", ")", ",", "getH", "(", ")", ",", "getA", "(", ")", ",", "getB", "(", ")", ",", "getLb", "(", ")", ",", "getUb", "(", ")", ")", ";", "int", "nOfSlackVariables", "=", "lpConverter", ".", "getStandardS", "(", ")", ";", "log", ".", "debug", "(", "\"nOfSlackVariables: \"", "+", "nOfSlackVariables", ")", ";", "DoubleMatrix1D", "standardC", "=", "lpConverter", ".", "getStandardC", "(", ")", ";", "DoubleMatrix2D", "standardA", "=", "lpConverter", ".", "getStandardA", "(", ")", ";", "DoubleMatrix1D", "standardB", "=", "lpConverter", ".", "getStandardB", "(", ")", ";", "DoubleMatrix1D", "standardLb", "=", "lpConverter", ".", "getStandardLB", "(", ")", ";", "DoubleMatrix1D", "standardUb", "=", "lpConverter", ".", "getStandardUB", "(", ")", ";", "//solve the standard form problem\r", "LPOptimizationRequest", "standardLPRequest", "=", "lpRequest", ".", "cloneMe", "(", ")", ";", "standardLPRequest", ".", "setC", "(", "standardC", ")", ";", "standardLPRequest", ".", "setA", "(", "standardA", ")", ";", "standardLPRequest", ".", "setB", "(", "standardB", ")", ";", "standardLPRequest", ".", "setLb", "(", "ColtUtils", ".", "replaceValues", "(", "standardLb", ",", "lpConverter", ".", "getUnboundedLBValue", "(", ")", ",", "minLBValue", ")", ")", ";", "//substitute not-double numbers\r", "standardLPRequest", ".", "setUb", "(", "ColtUtils", ".", "replaceValues", "(", "standardUb", ",", "lpConverter", ".", "getUnboundedUBValue", "(", ")", ",", "maxUBValue", ")", ")", ";", "//substitute not-double numbers\r", "if", "(", "getInitialPoint", "(", ")", "!=", "null", ")", "{", "standardLPRequest", ".", "setInitialPoint", "(", "lpConverter", ".", "getStandardComponents", "(", "getInitialPoint", "(", ")", ".", "toArray", "(", ")", ")", ")", ";", "}", "if", "(", "getNotFeasibleInitialPoint", "(", ")", "!=", "null", ")", "{", "standardLPRequest", ".", "setNotFeasibleInitialPoint", "(", "lpConverter", ".", "getStandardComponents", "(", "getNotFeasibleInitialPoint", "(", ")", ".", "toArray", "(", ")", ")", ")", ";", "}", "//optimization\r", "LPPrimalDualMethod", "opt", "=", "new", "LPPrimalDualMethod", "(", "minLBValue", ",", "maxUBValue", ")", ";", "opt", ".", "setLPOptimizationRequest", "(", "standardLPRequest", ")", ";", "if", "(", "opt", ".", "optimizeStandardLP", "(", "nOfSlackVariables", ")", "==", "OptimizationResponse", ".", "FAILED", ")", "{", "return", "OptimizationResponse", ".", "FAILED", ";", "}", "//back to original form\r", "LPOptimizationResponse", "lpResponse", "=", "opt", ".", "getLPOptimizationResponse", "(", ")", ";", "double", "[", "]", "standardSolution", "=", "lpResponse", ".", "getSolution", "(", ")", ";", "double", "[", "]", "originalSol", "=", "lpConverter", ".", "postConvert", "(", "standardSolution", ")", ";", "lpResponse", ".", "setSolution", "(", "originalSol", ")", ";", "setLPOptimizationResponse", "(", "lpResponse", ")", ";", "return", "lpResponse", ".", "getReturnCode", "(", ")", ";", "}" ]
Solves an LP in the form of: min(c) s.t. A.x = b G.x < h lb <= x <= ub
[ "Solves", "an", "LP", "in", "the", "form", "of", ":", "min", "(", "c", ")", "s", ".", "t", ".", "A", ".", "x", "=", "b", "G", ".", "x", "<", "h", "lb", "<", "=", "x", "<", "=", "ub" ]
train
https://github.com/vincentk/joptimizer/blob/65064c1bb0b26c7261358021e4c93d06dd43564f/src/main/java/com/joptimizer/optimizers/LPPrimalDualMethod.java#L111-L160
osglworks/java-mvc
src/main/java/org/osgl/mvc/result/UnavailableForLegalReasons.java
UnavailableForLegalReasons.of
public static UnavailableForLegalReasons of(int errorCode) { """ Returns a static UnavailableForLegalReasons instance and set the {@link #payload} thread local with error code and default message. When calling the instance on {@link #getMessage()} method, it will return whatever stored in the {@link #payload} thread local @param errorCode the app defined error code @return a static UnavailableForLegalReasons instance as described above """ if (_localizedErrorMsg()) { return of(errorCode, defaultMessage(UNAVAILABLE_FOR_LEGAL_REASONS)); } else { touchPayload().errorCode(errorCode); return _INSTANCE; } }
java
public static UnavailableForLegalReasons of(int errorCode) { if (_localizedErrorMsg()) { return of(errorCode, defaultMessage(UNAVAILABLE_FOR_LEGAL_REASONS)); } else { touchPayload().errorCode(errorCode); return _INSTANCE; } }
[ "public", "static", "UnavailableForLegalReasons", "of", "(", "int", "errorCode", ")", "{", "if", "(", "_localizedErrorMsg", "(", ")", ")", "{", "return", "of", "(", "errorCode", ",", "defaultMessage", "(", "UNAVAILABLE_FOR_LEGAL_REASONS", ")", ")", ";", "}", "else", "{", "touchPayload", "(", ")", ".", "errorCode", "(", "errorCode", ")", ";", "return", "_INSTANCE", ";", "}", "}" ]
Returns a static UnavailableForLegalReasons instance and set the {@link #payload} thread local with error code and default message. When calling the instance on {@link #getMessage()} method, it will return whatever stored in the {@link #payload} thread local @param errorCode the app defined error code @return a static UnavailableForLegalReasons instance as described above
[ "Returns", "a", "static", "UnavailableForLegalReasons", "instance", "and", "set", "the", "{", "@link", "#payload", "}", "thread", "local", "with", "error", "code", "and", "default", "message", "." ]
train
https://github.com/osglworks/java-mvc/blob/4d2b2ec40498ac6ee7040c0424377cbeacab124b/src/main/java/org/osgl/mvc/result/UnavailableForLegalReasons.java#L160-L167
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/ns/admin_ns_config.java
admin_ns_config.modify
public static admin_ns_config modify(nitro_service client, admin_ns_config resource) throws Exception { """ <pre> Use this operation to apply admin configuration on NetScaler Instance. </pre> """ resource.validate("modify"); return ((admin_ns_config[]) resource.update_resource(client))[0]; }
java
public static admin_ns_config modify(nitro_service client, admin_ns_config resource) throws Exception { resource.validate("modify"); return ((admin_ns_config[]) resource.update_resource(client))[0]; }
[ "public", "static", "admin_ns_config", "modify", "(", "nitro_service", "client", ",", "admin_ns_config", "resource", ")", "throws", "Exception", "{", "resource", ".", "validate", "(", "\"modify\"", ")", ";", "return", "(", "(", "admin_ns_config", "[", "]", ")", "resource", ".", "update_resource", "(", "client", ")", ")", "[", "0", "]", ";", "}" ]
<pre> Use this operation to apply admin configuration on NetScaler Instance. </pre>
[ "<pre", ">", "Use", "this", "operation", "to", "apply", "admin", "configuration", "on", "NetScaler", "Instance", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/admin_ns_config.java#L85-L89
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/corona/Session.java
Session.incrementRequestCount
protected void incrementRequestCount(ResourceType type, int delta) { """ Increase a request count for a resource for this session. It cannot exceed the max concurrent request count. @param type Resource type @param delta incremental request count """ Context c = getContext(type); int newRequestCount = c.requestCount + delta; c.requestCount = newRequestCount; if (newRequestCount > c.maxConcurrentRequestCount) { c.maxConcurrentRequestCount = newRequestCount; } }
java
protected void incrementRequestCount(ResourceType type, int delta) { Context c = getContext(type); int newRequestCount = c.requestCount + delta; c.requestCount = newRequestCount; if (newRequestCount > c.maxConcurrentRequestCount) { c.maxConcurrentRequestCount = newRequestCount; } }
[ "protected", "void", "incrementRequestCount", "(", "ResourceType", "type", ",", "int", "delta", ")", "{", "Context", "c", "=", "getContext", "(", "type", ")", ";", "int", "newRequestCount", "=", "c", ".", "requestCount", "+", "delta", ";", "c", ".", "requestCount", "=", "newRequestCount", ";", "if", "(", "newRequestCount", ">", "c", ".", "maxConcurrentRequestCount", ")", "{", "c", ".", "maxConcurrentRequestCount", "=", "newRequestCount", ";", "}", "}" ]
Increase a request count for a resource for this session. It cannot exceed the max concurrent request count. @param type Resource type @param delta incremental request count
[ "Increase", "a", "request", "count", "for", "a", "resource", "for", "this", "session", ".", "It", "cannot", "exceed", "the", "max", "concurrent", "request", "count", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/Session.java#L620-L627
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/NetworkClient.java
NetworkClient.insertNetwork
@BetaApi public final Operation insertNetwork(ProjectName project, Network networkResource) { """ Creates a network in the specified project using the data included in the request. <p>Sample code: <pre><code> try (NetworkClient networkClient = NetworkClient.create()) { ProjectName project = ProjectName.of("[PROJECT]"); Network networkResource = Network.newBuilder().build(); Operation response = networkClient.insertNetwork(project, networkResource); } </code></pre> @param project Project ID for this request. @param networkResource Represents a Network resource. Read Virtual Private Cloud (VPC) Network Overview for more information. (== resource_for v1.networks ==) (== resource_for beta.networks ==) @throws com.google.api.gax.rpc.ApiException if the remote call fails """ InsertNetworkHttpRequest request = InsertNetworkHttpRequest.newBuilder() .setProject(project == null ? null : project.toString()) .setNetworkResource(networkResource) .build(); return insertNetwork(request); }
java
@BetaApi public final Operation insertNetwork(ProjectName project, Network networkResource) { InsertNetworkHttpRequest request = InsertNetworkHttpRequest.newBuilder() .setProject(project == null ? null : project.toString()) .setNetworkResource(networkResource) .build(); return insertNetwork(request); }
[ "@", "BetaApi", "public", "final", "Operation", "insertNetwork", "(", "ProjectName", "project", ",", "Network", "networkResource", ")", "{", "InsertNetworkHttpRequest", "request", "=", "InsertNetworkHttpRequest", ".", "newBuilder", "(", ")", ".", "setProject", "(", "project", "==", "null", "?", "null", ":", "project", ".", "toString", "(", ")", ")", ".", "setNetworkResource", "(", "networkResource", ")", ".", "build", "(", ")", ";", "return", "insertNetwork", "(", "request", ")", ";", "}" ]
Creates a network in the specified project using the data included in the request. <p>Sample code: <pre><code> try (NetworkClient networkClient = NetworkClient.create()) { ProjectName project = ProjectName.of("[PROJECT]"); Network networkResource = Network.newBuilder().build(); Operation response = networkClient.insertNetwork(project, networkResource); } </code></pre> @param project Project ID for this request. @param networkResource Represents a Network resource. Read Virtual Private Cloud (VPC) Network Overview for more information. (== resource_for v1.networks ==) (== resource_for beta.networks ==) @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Creates", "a", "network", "in", "the", "specified", "project", "using", "the", "data", "included", "in", "the", "request", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/NetworkClient.java#L480-L489
vekexasia/android-edittext-validator
library/src/com/andreabaccega/widget/FormAutoCompleteTextView.java
FormAutoCompleteTextView.onKeyPreIme
@Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { """ Don't send delete key so edit text doesn't capture it and close error """ if (TextUtils.isEmpty(getText().toString()) && keyCode == KeyEvent.KEYCODE_DEL) return true; else return super.onKeyPreIme(keyCode, event); }
java
@Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (TextUtils.isEmpty(getText().toString()) && keyCode == KeyEvent.KEYCODE_DEL) return true; else return super.onKeyPreIme(keyCode, event); }
[ "@", "Override", "public", "boolean", "onKeyPreIme", "(", "int", "keyCode", ",", "KeyEvent", "event", ")", "{", "if", "(", "TextUtils", ".", "isEmpty", "(", "getText", "(", ")", ".", "toString", "(", ")", ")", "&&", "keyCode", "==", "KeyEvent", ".", "KEYCODE_DEL", ")", "return", "true", ";", "else", "return", "super", ".", "onKeyPreIme", "(", "keyCode", ",", "event", ")", ";", "}" ]
Don't send delete key so edit text doesn't capture it and close error
[ "Don", "t", "send", "delete", "key", "so", "edit", "text", "doesn", "t", "capture", "it", "and", "close", "error" ]
train
https://github.com/vekexasia/android-edittext-validator/blob/4a100e3d708b232133f4dd8ceb37ad7447fc7a1b/library/src/com/andreabaccega/widget/FormAutoCompleteTextView.java#L79-L86
j256/ormlite-android
src/main/java/com/j256/ormlite/android/apptools/OrmLiteCursorAdapter.java
OrmLiteCursorAdapter.doBindView
protected void doBindView(View itemView, Context context, Cursor cursor) { """ This is here to make sure that the user really wants to override it. """ try { @SuppressWarnings("unchecked") ViewType itemViewType = (ViewType) itemView; bindView(itemViewType, context, cursorToObject(cursor)); } catch (SQLException e) { throw new RuntimeException(e); } }
java
protected void doBindView(View itemView, Context context, Cursor cursor) { try { @SuppressWarnings("unchecked") ViewType itemViewType = (ViewType) itemView; bindView(itemViewType, context, cursorToObject(cursor)); } catch (SQLException e) { throw new RuntimeException(e); } }
[ "protected", "void", "doBindView", "(", "View", "itemView", ",", "Context", "context", ",", "Cursor", "cursor", ")", "{", "try", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "ViewType", "itemViewType", "=", "(", "ViewType", ")", "itemView", ";", "bindView", "(", "itemViewType", ",", "context", ",", "cursorToObject", "(", "cursor", ")", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
This is here to make sure that the user really wants to override it.
[ "This", "is", "here", "to", "make", "sure", "that", "the", "user", "really", "wants", "to", "override", "it", "." ]
train
https://github.com/j256/ormlite-android/blob/e82327a868ae242f994730fe2389f79684d7bcab/src/main/java/com/j256/ormlite/android/apptools/OrmLiteCursorAdapter.java#L45-L53