repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
b3log/latke
latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java
JdbcRepository.buildOrderBy
private void buildOrderBy(final StringBuilder orderByBuilder, final Map<String, SortDirection> sorts) { """ Builds 'ORDER BY' part with the specified order by build and sorts. @param orderByBuilder the specified order by builder @param sorts the specified sorts """ boolean isFirst = true; String querySortDirection; for (final Map.Entry<String, SortDirection> sort : sorts.entrySet()) { if (isFirst) { orderByBuilder.append(" ORDER BY "); isFirst = false; } else { orderByBuilder.append(", "); } if (sort.getValue().equals(SortDirection.ASCENDING)) { querySortDirection = "ASC"; } else { querySortDirection = "DESC"; } orderByBuilder.append(sort.getKey()).append(" ").append(querySortDirection); } }
java
private void buildOrderBy(final StringBuilder orderByBuilder, final Map<String, SortDirection> sorts) { boolean isFirst = true; String querySortDirection; for (final Map.Entry<String, SortDirection> sort : sorts.entrySet()) { if (isFirst) { orderByBuilder.append(" ORDER BY "); isFirst = false; } else { orderByBuilder.append(", "); } if (sort.getValue().equals(SortDirection.ASCENDING)) { querySortDirection = "ASC"; } else { querySortDirection = "DESC"; } orderByBuilder.append(sort.getKey()).append(" ").append(querySortDirection); } }
[ "private", "void", "buildOrderBy", "(", "final", "StringBuilder", "orderByBuilder", ",", "final", "Map", "<", "String", ",", "SortDirection", ">", "sorts", ")", "{", "boolean", "isFirst", "=", "true", ";", "String", "querySortDirection", ";", "for", "(", "final", "Map", ".", "Entry", "<", "String", ",", "SortDirection", ">", "sort", ":", "sorts", ".", "entrySet", "(", ")", ")", "{", "if", "(", "isFirst", ")", "{", "orderByBuilder", ".", "append", "(", "\" ORDER BY \"", ")", ";", "isFirst", "=", "false", ";", "}", "else", "{", "orderByBuilder", ".", "append", "(", "\", \"", ")", ";", "}", "if", "(", "sort", ".", "getValue", "(", ")", ".", "equals", "(", "SortDirection", ".", "ASCENDING", ")", ")", "{", "querySortDirection", "=", "\"ASC\"", ";", "}", "else", "{", "querySortDirection", "=", "\"DESC\"", ";", "}", "orderByBuilder", ".", "append", "(", "sort", ".", "getKey", "(", ")", ")", ".", "append", "(", "\" \"", ")", ".", "append", "(", "querySortDirection", ")", ";", "}", "}" ]
Builds 'ORDER BY' part with the specified order by build and sorts. @param orderByBuilder the specified order by builder @param sorts the specified sorts
[ "Builds", "ORDER", "BY", "part", "with", "the", "specified", "order", "by", "build", "and", "sorts", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L619-L638
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/query/impl/QueryContext.java
QueryContext.matchIndex
public Index matchIndex(String pattern, IndexMatchHint matchHint) { """ Matches an index for the given pattern and match hint. @param pattern the pattern to match an index for. May be either an attribute name or an exact index name. @param matchHint the match hint. @return the matched index or {@code null} if nothing matched. @see QueryContext.IndexMatchHint """ return indexes.matchIndex(pattern, matchHint); }
java
public Index matchIndex(String pattern, IndexMatchHint matchHint) { return indexes.matchIndex(pattern, matchHint); }
[ "public", "Index", "matchIndex", "(", "String", "pattern", ",", "IndexMatchHint", "matchHint", ")", "{", "return", "indexes", ".", "matchIndex", "(", "pattern", ",", "matchHint", ")", ";", "}" ]
Matches an index for the given pattern and match hint. @param pattern the pattern to match an index for. May be either an attribute name or an exact index name. @param matchHint the match hint. @return the matched index or {@code null} if nothing matched. @see QueryContext.IndexMatchHint
[ "Matches", "an", "index", "for", "the", "given", "pattern", "and", "match", "hint", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/query/impl/QueryContext.java#L78-L80
xwiki/xwiki-rendering
xwiki-rendering-wikimodel/src/main/java/org/xwiki/rendering/wikimodel/WikiPageUtil.java
WikiPageUtil.isValidXmlNameChar
public static boolean isValidXmlNameChar(char ch, boolean colonEnabled) { """ Returns <code>true</code> if the given value is a valid XML name character. <p> See http://www.w3.org/TR/xml/#NT-NameChar. </p> @param ch the character to check @param colonEnabled if this flag is <code>true</code> then this method accepts the ':' symbol. @return <code>true</code> if the given value is a valid XML name character """ return isValidXmlNameStartChar(ch, colonEnabled) || (ch == '-') || (ch == '.') || (ch >= '0' && ch <= '9') || (ch == 0xB7) || (ch >= 0x0300 && ch <= 0x036F) || (ch >= 0x203F && ch <= 0x2040); }
java
public static boolean isValidXmlNameChar(char ch, boolean colonEnabled) { return isValidXmlNameStartChar(ch, colonEnabled) || (ch == '-') || (ch == '.') || (ch >= '0' && ch <= '9') || (ch == 0xB7) || (ch >= 0x0300 && ch <= 0x036F) || (ch >= 0x203F && ch <= 0x2040); }
[ "public", "static", "boolean", "isValidXmlNameChar", "(", "char", "ch", ",", "boolean", "colonEnabled", ")", "{", "return", "isValidXmlNameStartChar", "(", "ch", ",", "colonEnabled", ")", "||", "(", "ch", "==", "'", "'", ")", "||", "(", "ch", "==", "'", "'", ")", "||", "(", "ch", ">=", "'", "'", "&&", "ch", "<=", "'", "'", ")", "||", "(", "ch", "==", "0xB7", ")", "||", "(", "ch", ">=", "0x0300", "&&", "ch", "<=", "0x036F", ")", "||", "(", "ch", ">=", "0x203F", "&&", "ch", "<=", "0x2040", ")", ";", "}" ]
Returns <code>true</code> if the given value is a valid XML name character. <p> See http://www.w3.org/TR/xml/#NT-NameChar. </p> @param ch the character to check @param colonEnabled if this flag is <code>true</code> then this method accepts the ':' symbol. @return <code>true</code> if the given value is a valid XML name character
[ "Returns", "<code", ">", "true<", "/", "code", ">", "if", "the", "given", "value", "is", "a", "valid", "XML", "name", "character", ".", "<p", ">", "See", "http", ":", "//", "www", ".", "w3", ".", "org", "/", "TR", "/", "xml", "/", "#NT", "-", "NameChar", ".", "<", "/", "p", ">" ]
train
https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-wikimodel/src/main/java/org/xwiki/rendering/wikimodel/WikiPageUtil.java#L267-L276
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/ops/transforms/Transforms.java
Transforms.timesOneMinus
public static INDArray timesOneMinus(INDArray in, boolean copy) { """ out = in * (1-in) @param in Input array @param copy If true: copy. False: apply in-place @return """ return Nd4j.getExecutioner().exec(new TimesOneMinus(in, (copy ? in.ulike() : in))); }
java
public static INDArray timesOneMinus(INDArray in, boolean copy){ return Nd4j.getExecutioner().exec(new TimesOneMinus(in, (copy ? in.ulike() : in))); }
[ "public", "static", "INDArray", "timesOneMinus", "(", "INDArray", "in", ",", "boolean", "copy", ")", "{", "return", "Nd4j", ".", "getExecutioner", "(", ")", ".", "exec", "(", "new", "TimesOneMinus", "(", "in", ",", "(", "copy", "?", "in", ".", "ulike", "(", ")", ":", "in", ")", ")", ")", ";", "}" ]
out = in * (1-in) @param in Input array @param copy If true: copy. False: apply in-place @return
[ "out", "=", "in", "*", "(", "1", "-", "in", ")" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/ops/transforms/Transforms.java#L520-L522
CloudSlang/cs-actions
cs-vmware/src/main/java/io/cloudslang/content/vmware/services/GuestService.java
GuestService.mountTools
public Map<String, String> mountTools(HttpInputs httpInputs, VmInputs vmInputs) throws Exception { """ Method used to connect to specified data center and start the Install Tools process on virtual machine identified by the inputs provided. @param httpInputs Object that has all the inputs necessary to made a connection to data center @param vmInputs Object that has all the specific inputs necessary to identify the targeted virtual machine @return Map with String as key and value that contains returnCode of the operation, success message or failure message and the exception if there is one @throws Exception """ ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs); try { ManagedObjectReference vmMor = new MorObjectHandler() .getMor(connectionResources, ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName()); if (vmMor != null) { connectionResources.getVimPortType().mountToolsInstaller(vmMor); return ResponseUtils.getResultsMap(INITIATED_TOOLS_INSTALLER_MOUNT + vmInputs.getVirtualMachineName(), Outputs.RETURN_CODE_SUCCESS); } else { return ResponseUtils.getVmNotFoundResultsMap(vmInputs); } } catch (Exception ex) { return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE); } finally { if (httpInputs.isCloseSession()) { connectionResources.getConnection().disconnect(); clearConnectionFromContext(httpInputs.getGlobalSessionObject()); } } }
java
public Map<String, String> mountTools(HttpInputs httpInputs, VmInputs vmInputs) throws Exception { ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs); try { ManagedObjectReference vmMor = new MorObjectHandler() .getMor(connectionResources, ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName()); if (vmMor != null) { connectionResources.getVimPortType().mountToolsInstaller(vmMor); return ResponseUtils.getResultsMap(INITIATED_TOOLS_INSTALLER_MOUNT + vmInputs.getVirtualMachineName(), Outputs.RETURN_CODE_SUCCESS); } else { return ResponseUtils.getVmNotFoundResultsMap(vmInputs); } } catch (Exception ex) { return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE); } finally { if (httpInputs.isCloseSession()) { connectionResources.getConnection().disconnect(); clearConnectionFromContext(httpInputs.getGlobalSessionObject()); } } }
[ "public", "Map", "<", "String", ",", "String", ">", "mountTools", "(", "HttpInputs", "httpInputs", ",", "VmInputs", "vmInputs", ")", "throws", "Exception", "{", "ConnectionResources", "connectionResources", "=", "new", "ConnectionResources", "(", "httpInputs", ",", "vmInputs", ")", ";", "try", "{", "ManagedObjectReference", "vmMor", "=", "new", "MorObjectHandler", "(", ")", ".", "getMor", "(", "connectionResources", ",", "ManagedObjectType", ".", "VIRTUAL_MACHINE", ".", "getValue", "(", ")", ",", "vmInputs", ".", "getVirtualMachineName", "(", ")", ")", ";", "if", "(", "vmMor", "!=", "null", ")", "{", "connectionResources", ".", "getVimPortType", "(", ")", ".", "mountToolsInstaller", "(", "vmMor", ")", ";", "return", "ResponseUtils", ".", "getResultsMap", "(", "INITIATED_TOOLS_INSTALLER_MOUNT", "+", "vmInputs", ".", "getVirtualMachineName", "(", ")", ",", "Outputs", ".", "RETURN_CODE_SUCCESS", ")", ";", "}", "else", "{", "return", "ResponseUtils", ".", "getVmNotFoundResultsMap", "(", "vmInputs", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "return", "ResponseUtils", ".", "getResultsMap", "(", "ex", ".", "toString", "(", ")", ",", "Outputs", ".", "RETURN_CODE_FAILURE", ")", ";", "}", "finally", "{", "if", "(", "httpInputs", ".", "isCloseSession", "(", ")", ")", "{", "connectionResources", ".", "getConnection", "(", ")", ".", "disconnect", "(", ")", ";", "clearConnectionFromContext", "(", "httpInputs", ".", "getGlobalSessionObject", "(", ")", ")", ";", "}", "}", "}" ]
Method used to connect to specified data center and start the Install Tools process on virtual machine identified by the inputs provided. @param httpInputs Object that has all the inputs necessary to made a connection to data center @param vmInputs Object that has all the specific inputs necessary to identify the targeted virtual machine @return Map with String as key and value that contains returnCode of the operation, success message or failure message and the exception if there is one @throws Exception
[ "Method", "used", "to", "connect", "to", "specified", "data", "center", "and", "start", "the", "Install", "Tools", "process", "on", "virtual", "machine", "identified", "by", "the", "inputs", "provided", "." ]
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/GuestService.java#L81-L101
alkacon/opencms-core
src/org/opencms/db/generic/CmsSqlManager.java
CmsSqlManager.readQuery
public String readQuery(CmsUUID projectId, String queryKey) { """ Searches for the SQL query with the specified key and project-ID.<p> For projectIds &ne; 0, the pattern {@link #QUERY_PROJECT_SEARCH_PATTERN} in table names of queries is replaced with "_ONLINE_" or "_OFFLINE_" to choose the right database tables for SQL queries that are project dependent! @param projectId the ID of the specified CmsProject @param queryKey the key of the SQL query @return the the SQL query in this property list with the specified key """ String key; if ((projectId != null) && !projectId.isNullUUID()) { // id 0 is special, please see below StringBuffer buffer = new StringBuffer(128); buffer.append(queryKey); if (projectId.equals(CmsProject.ONLINE_PROJECT_ID)) { buffer.append("_ONLINE"); } else { buffer.append("_OFFLINE"); } key = buffer.toString(); } else { key = queryKey; } // look up the query in the cache String query = m_cachedQueries.get(key); if (query == null) { // the query has not been cached yet // get the SQL statement from the properties hash query = readQuery(queryKey); if (query == null) { throw new CmsRuntimeException(Messages.get().container(Messages.ERR_QUERY_NOT_FOUND_1, queryKey)); } // replace control chars. query = CmsStringUtil.substitute(query, "\t", " "); query = CmsStringUtil.substitute(query, "\n", " "); if ((projectId != null) && !projectId.isNullUUID()) { // a project ID = 0 is an internal indicator that a project-independent // query was requested - further regex operations are not required then query = CmsSqlManager.replaceProjectPattern(projectId, query); } // to minimize costs, all statements with replaced expressions are cached in a map m_cachedQueries.put(key, query); } return query; }
java
public String readQuery(CmsUUID projectId, String queryKey) { String key; if ((projectId != null) && !projectId.isNullUUID()) { // id 0 is special, please see below StringBuffer buffer = new StringBuffer(128); buffer.append(queryKey); if (projectId.equals(CmsProject.ONLINE_PROJECT_ID)) { buffer.append("_ONLINE"); } else { buffer.append("_OFFLINE"); } key = buffer.toString(); } else { key = queryKey; } // look up the query in the cache String query = m_cachedQueries.get(key); if (query == null) { // the query has not been cached yet // get the SQL statement from the properties hash query = readQuery(queryKey); if (query == null) { throw new CmsRuntimeException(Messages.get().container(Messages.ERR_QUERY_NOT_FOUND_1, queryKey)); } // replace control chars. query = CmsStringUtil.substitute(query, "\t", " "); query = CmsStringUtil.substitute(query, "\n", " "); if ((projectId != null) && !projectId.isNullUUID()) { // a project ID = 0 is an internal indicator that a project-independent // query was requested - further regex operations are not required then query = CmsSqlManager.replaceProjectPattern(projectId, query); } // to minimize costs, all statements with replaced expressions are cached in a map m_cachedQueries.put(key, query); } return query; }
[ "public", "String", "readQuery", "(", "CmsUUID", "projectId", ",", "String", "queryKey", ")", "{", "String", "key", ";", "if", "(", "(", "projectId", "!=", "null", ")", "&&", "!", "projectId", ".", "isNullUUID", "(", ")", ")", "{", "// id 0 is special, please see below", "StringBuffer", "buffer", "=", "new", "StringBuffer", "(", "128", ")", ";", "buffer", ".", "append", "(", "queryKey", ")", ";", "if", "(", "projectId", ".", "equals", "(", "CmsProject", ".", "ONLINE_PROJECT_ID", ")", ")", "{", "buffer", ".", "append", "(", "\"_ONLINE\"", ")", ";", "}", "else", "{", "buffer", ".", "append", "(", "\"_OFFLINE\"", ")", ";", "}", "key", "=", "buffer", ".", "toString", "(", ")", ";", "}", "else", "{", "key", "=", "queryKey", ";", "}", "// look up the query in the cache", "String", "query", "=", "m_cachedQueries", ".", "get", "(", "key", ")", ";", "if", "(", "query", "==", "null", ")", "{", "// the query has not been cached yet", "// get the SQL statement from the properties hash", "query", "=", "readQuery", "(", "queryKey", ")", ";", "if", "(", "query", "==", "null", ")", "{", "throw", "new", "CmsRuntimeException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_QUERY_NOT_FOUND_1", ",", "queryKey", ")", ")", ";", "}", "// replace control chars.", "query", "=", "CmsStringUtil", ".", "substitute", "(", "query", ",", "\"\\t\"", ",", "\" \"", ")", ";", "query", "=", "CmsStringUtil", ".", "substitute", "(", "query", ",", "\"\\n\"", ",", "\" \"", ")", ";", "if", "(", "(", "projectId", "!=", "null", ")", "&&", "!", "projectId", ".", "isNullUUID", "(", ")", ")", "{", "// a project ID = 0 is an internal indicator that a project-independent", "// query was requested - further regex operations are not required then", "query", "=", "CmsSqlManager", ".", "replaceProjectPattern", "(", "projectId", ",", "query", ")", ";", "}", "// to minimize costs, all statements with replaced expressions are cached in a map", "m_cachedQueries", ".", "put", "(", "key", ",", "query", ")", ";", "}", "return", "query", ";", "}" ]
Searches for the SQL query with the specified key and project-ID.<p> For projectIds &ne; 0, the pattern {@link #QUERY_PROJECT_SEARCH_PATTERN} in table names of queries is replaced with "_ONLINE_" or "_OFFLINE_" to choose the right database tables for SQL queries that are project dependent! @param projectId the ID of the specified CmsProject @param queryKey the key of the SQL query @return the the SQL query in this property list with the specified key
[ "Searches", "for", "the", "SQL", "query", "with", "the", "specified", "key", "and", "project", "-", "ID", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsSqlManager.java#L329-L373
OpenLiberty/open-liberty
dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/execution/impl/JobExecutionHelper.java
JobExecutionHelper.createJobStartExecution
public RuntimeJobExecution createJobStartExecution(final WSJobInstance jobInstance, IJobXMLSource jslSource, Properties jobParameters, long executionId) throws JobStartException { """ Note: this method is called on the job submission thread. Updates the jobinstance record with the jobXML and jobname (jobid in jobxml). @return a new RuntimeJobExecution record, ready to be dispatched. """ // TODO - redesign to avoid cast? final JobInstanceEntity jobInstanceImpl = (JobInstanceEntity) jobInstance; long instanceId = jobInstance.getInstanceId(); ModelNavigator<JSLJob> navigator = createFirstExecution(jobInstanceImpl, jslSource, jobParameters); JobExecutionEntity jobExec = null; try { jobExec = getPersistenceManagerService().getJobExecutionMostRecent(instanceId); // Check to make sure the executionId belongs to the most recent execution. // If not, a restart may have occurred. So, fail the start. // Also check to make sure a stop did not come in while the start was on the queue. BatchStatus currentBatchStatus = jobExec.getBatchStatus(); if (jobExec.getExecutionId() != executionId || currentBatchStatus.equals(BatchStatus.STOPPING) || currentBatchStatus.equals(BatchStatus.STOPPED)) { throw new JobStartException(); } } catch (IllegalStateException ie) { // If no execution exists, request came from old dispatch path. jobExec = getPersistenceManagerService().createJobExecution(instanceId, jobParameters, new Date()); BatchEventsPublisher eventsPublisher = batchKernelImpl.getBatchEventsPublisher(); if (eventsPublisher != null) { String correlationId = getCorrelationId(jobParameters); eventsPublisher.publishJobExecutionEvent(jobExec, BatchEventsPublisher.TOPIC_EXECUTION_STARTING, correlationId); } } TopLevelNameInstanceExecutionInfo topLevelInfo = new TopLevelNameInstanceExecutionInfo(jobInstanceImpl.getJobName(), instanceId, jobExec.getExecutionId()); return new RuntimeJobExecution(topLevelInfo, jobParameters, navigator); }
java
public RuntimeJobExecution createJobStartExecution(final WSJobInstance jobInstance, IJobXMLSource jslSource, Properties jobParameters, long executionId) throws JobStartException { // TODO - redesign to avoid cast? final JobInstanceEntity jobInstanceImpl = (JobInstanceEntity) jobInstance; long instanceId = jobInstance.getInstanceId(); ModelNavigator<JSLJob> navigator = createFirstExecution(jobInstanceImpl, jslSource, jobParameters); JobExecutionEntity jobExec = null; try { jobExec = getPersistenceManagerService().getJobExecutionMostRecent(instanceId); // Check to make sure the executionId belongs to the most recent execution. // If not, a restart may have occurred. So, fail the start. // Also check to make sure a stop did not come in while the start was on the queue. BatchStatus currentBatchStatus = jobExec.getBatchStatus(); if (jobExec.getExecutionId() != executionId || currentBatchStatus.equals(BatchStatus.STOPPING) || currentBatchStatus.equals(BatchStatus.STOPPED)) { throw new JobStartException(); } } catch (IllegalStateException ie) { // If no execution exists, request came from old dispatch path. jobExec = getPersistenceManagerService().createJobExecution(instanceId, jobParameters, new Date()); BatchEventsPublisher eventsPublisher = batchKernelImpl.getBatchEventsPublisher(); if (eventsPublisher != null) { String correlationId = getCorrelationId(jobParameters); eventsPublisher.publishJobExecutionEvent(jobExec, BatchEventsPublisher.TOPIC_EXECUTION_STARTING, correlationId); } } TopLevelNameInstanceExecutionInfo topLevelInfo = new TopLevelNameInstanceExecutionInfo(jobInstanceImpl.getJobName(), instanceId, jobExec.getExecutionId()); return new RuntimeJobExecution(topLevelInfo, jobParameters, navigator); }
[ "public", "RuntimeJobExecution", "createJobStartExecution", "(", "final", "WSJobInstance", "jobInstance", ",", "IJobXMLSource", "jslSource", ",", "Properties", "jobParameters", ",", "long", "executionId", ")", "throws", "JobStartException", "{", "// TODO - redesign to avoid cast?", "final", "JobInstanceEntity", "jobInstanceImpl", "=", "(", "JobInstanceEntity", ")", "jobInstance", ";", "long", "instanceId", "=", "jobInstance", ".", "getInstanceId", "(", ")", ";", "ModelNavigator", "<", "JSLJob", ">", "navigator", "=", "createFirstExecution", "(", "jobInstanceImpl", ",", "jslSource", ",", "jobParameters", ")", ";", "JobExecutionEntity", "jobExec", "=", "null", ";", "try", "{", "jobExec", "=", "getPersistenceManagerService", "(", ")", ".", "getJobExecutionMostRecent", "(", "instanceId", ")", ";", "// Check to make sure the executionId belongs to the most recent execution.", "// If not, a restart may have occurred. So, fail the start.", "// Also check to make sure a stop did not come in while the start was on the queue.", "BatchStatus", "currentBatchStatus", "=", "jobExec", ".", "getBatchStatus", "(", ")", ";", "if", "(", "jobExec", ".", "getExecutionId", "(", ")", "!=", "executionId", "||", "currentBatchStatus", ".", "equals", "(", "BatchStatus", ".", "STOPPING", ")", "||", "currentBatchStatus", ".", "equals", "(", "BatchStatus", ".", "STOPPED", ")", ")", "{", "throw", "new", "JobStartException", "(", ")", ";", "}", "}", "catch", "(", "IllegalStateException", "ie", ")", "{", "// If no execution exists, request came from old dispatch path. ", "jobExec", "=", "getPersistenceManagerService", "(", ")", ".", "createJobExecution", "(", "instanceId", ",", "jobParameters", ",", "new", "Date", "(", ")", ")", ";", "BatchEventsPublisher", "eventsPublisher", "=", "batchKernelImpl", ".", "getBatchEventsPublisher", "(", ")", ";", "if", "(", "eventsPublisher", "!=", "null", ")", "{", "String", "correlationId", "=", "getCorrelationId", "(", "jobParameters", ")", ";", "eventsPublisher", ".", "publishJobExecutionEvent", "(", "jobExec", ",", "BatchEventsPublisher", ".", "TOPIC_EXECUTION_STARTING", ",", "correlationId", ")", ";", "}", "}", "TopLevelNameInstanceExecutionInfo", "topLevelInfo", "=", "new", "TopLevelNameInstanceExecutionInfo", "(", "jobInstanceImpl", ".", "getJobName", "(", ")", ",", "instanceId", ",", "jobExec", ".", "getExecutionId", "(", ")", ")", ";", "return", "new", "RuntimeJobExecution", "(", "topLevelInfo", ",", "jobParameters", ",", "navigator", ")", ";", "}" ]
Note: this method is called on the job submission thread. Updates the jobinstance record with the jobXML and jobname (jobid in jobxml). @return a new RuntimeJobExecution record, ready to be dispatched.
[ "Note", ":", "this", "method", "is", "called", "on", "the", "job", "submission", "thread", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/execution/impl/JobExecutionHelper.java#L86-L122
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java
SwaptionDataLattice.convertLattice
public SwaptionDataLattice convertLattice(QuotingConvention targetConvention, double displacement, AnalyticModel model) { """ Convert this lattice to store data in the given convention. Conversion involving receiver premium assumes zero wide collar. @param targetConvention The convention to store the data in. @param displacement The displacement to use, if applicable. @param model The model for context. @return The converted lattice. """ if(displacement != 0 && targetConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) { throw new IllegalArgumentException("SwaptionDataLattice only supports displacement, when using QuotingCOnvention.PAYERVOLATILITYLOGNORMAL."); } //Reverse sign of moneyness, if switching between payer and receiver convention. int reverse = ((targetConvention == QuotingConvention.RECEIVERPRICE) ^ (quotingConvention == QuotingConvention.RECEIVERPRICE)) ? -1 : 1; List<Integer> maturities = new ArrayList<>(); List<Integer> tenors = new ArrayList<>(); List<Integer> moneynesss = new ArrayList<>(); List<Double> values = new ArrayList<>(); for(DataKey key : entryMap.keySet()) { maturities.add(key.maturity); tenors.add(key.tenor); moneynesss.add(key.moneyness * reverse); values.add(getValue(key.maturity, key.tenor, key.moneyness, targetConvention, displacement, model)); } return new SwaptionDataLattice(referenceDate, targetConvention, displacement, forwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule, maturities.stream().mapToInt(Integer::intValue).toArray(), tenors.stream().mapToInt(Integer::intValue).toArray(), moneynesss.stream().mapToInt(Integer::intValue).toArray(), values.stream().mapToDouble(Double::doubleValue).toArray()); }
java
public SwaptionDataLattice convertLattice(QuotingConvention targetConvention, double displacement, AnalyticModel model) { if(displacement != 0 && targetConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) { throw new IllegalArgumentException("SwaptionDataLattice only supports displacement, when using QuotingCOnvention.PAYERVOLATILITYLOGNORMAL."); } //Reverse sign of moneyness, if switching between payer and receiver convention. int reverse = ((targetConvention == QuotingConvention.RECEIVERPRICE) ^ (quotingConvention == QuotingConvention.RECEIVERPRICE)) ? -1 : 1; List<Integer> maturities = new ArrayList<>(); List<Integer> tenors = new ArrayList<>(); List<Integer> moneynesss = new ArrayList<>(); List<Double> values = new ArrayList<>(); for(DataKey key : entryMap.keySet()) { maturities.add(key.maturity); tenors.add(key.tenor); moneynesss.add(key.moneyness * reverse); values.add(getValue(key.maturity, key.tenor, key.moneyness, targetConvention, displacement, model)); } return new SwaptionDataLattice(referenceDate, targetConvention, displacement, forwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule, maturities.stream().mapToInt(Integer::intValue).toArray(), tenors.stream().mapToInt(Integer::intValue).toArray(), moneynesss.stream().mapToInt(Integer::intValue).toArray(), values.stream().mapToDouble(Double::doubleValue).toArray()); }
[ "public", "SwaptionDataLattice", "convertLattice", "(", "QuotingConvention", "targetConvention", ",", "double", "displacement", ",", "AnalyticModel", "model", ")", "{", "if", "(", "displacement", "!=", "0", "&&", "targetConvention", "!=", "QuotingConvention", ".", "PAYERVOLATILITYLOGNORMAL", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"SwaptionDataLattice only supports displacement, when using QuotingCOnvention.PAYERVOLATILITYLOGNORMAL.\"", ")", ";", "}", "//Reverse sign of moneyness, if switching between payer and receiver convention.\r", "int", "reverse", "=", "(", "(", "targetConvention", "==", "QuotingConvention", ".", "RECEIVERPRICE", ")", "^", "(", "quotingConvention", "==", "QuotingConvention", ".", "RECEIVERPRICE", ")", ")", "?", "-", "1", ":", "1", ";", "List", "<", "Integer", ">", "maturities", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "Integer", ">", "tenors", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "Integer", ">", "moneynesss", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "Double", ">", "values", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "DataKey", "key", ":", "entryMap", ".", "keySet", "(", ")", ")", "{", "maturities", ".", "add", "(", "key", ".", "maturity", ")", ";", "tenors", ".", "add", "(", "key", ".", "tenor", ")", ";", "moneynesss", ".", "add", "(", "key", ".", "moneyness", "*", "reverse", ")", ";", "values", ".", "add", "(", "getValue", "(", "key", ".", "maturity", ",", "key", ".", "tenor", ",", "key", ".", "moneyness", ",", "targetConvention", ",", "displacement", ",", "model", ")", ")", ";", "}", "return", "new", "SwaptionDataLattice", "(", "referenceDate", ",", "targetConvention", ",", "displacement", ",", "forwardCurveName", ",", "discountCurveName", ",", "floatMetaSchedule", ",", "fixMetaSchedule", ",", "maturities", ".", "stream", "(", ")", ".", "mapToInt", "(", "Integer", "::", "intValue", ")", ".", "toArray", "(", ")", ",", "tenors", ".", "stream", "(", ")", ".", "mapToInt", "(", "Integer", "::", "intValue", ")", ".", "toArray", "(", ")", ",", "moneynesss", ".", "stream", "(", ")", ".", "mapToInt", "(", "Integer", "::", "intValue", ")", ".", "toArray", "(", ")", ",", "values", ".", "stream", "(", ")", ".", "mapToDouble", "(", "Double", "::", "doubleValue", ")", ".", "toArray", "(", ")", ")", ";", "}" ]
Convert this lattice to store data in the given convention. Conversion involving receiver premium assumes zero wide collar. @param targetConvention The convention to store the data in. @param displacement The displacement to use, if applicable. @param model The model for context. @return The converted lattice.
[ "Convert", "this", "lattice", "to", "store", "data", "in", "the", "given", "convention", ".", "Conversion", "involving", "receiver", "premium", "assumes", "zero", "wide", "collar", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L260-L287
kite-sdk/kite
kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/api/Record.java
Record.replaceValues
public void replaceValues(String key, Object value) { """ Removes all values that are associated with the given key, and then associates the given value with the given key. """ // fields.replaceValues(key, Collections.singletonList(value)); // unnecessarily slow List<Object> list = fields.get(key); list.clear(); list.add(value); }
java
public void replaceValues(String key, Object value) { // fields.replaceValues(key, Collections.singletonList(value)); // unnecessarily slow List<Object> list = fields.get(key); list.clear(); list.add(value); }
[ "public", "void", "replaceValues", "(", "String", "key", ",", "Object", "value", ")", "{", "// fields.replaceValues(key, Collections.singletonList(value)); // unnecessarily slow", "List", "<", "Object", ">", "list", "=", "fields", ".", "get", "(", "key", ")", ";", "list", ".", "clear", "(", ")", ";", "list", ".", "add", "(", "value", ")", ";", "}" ]
Removes all values that are associated with the given key, and then associates the given value with the given key.
[ "Removes", "all", "values", "that", "are", "associated", "with", "the", "given", "key", "and", "then", "associates", "the", "given", "value", "with", "the", "given", "key", "." ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/api/Record.java#L85-L90
hal/core
gui/src/main/java/org/jboss/as/console/client/v3/elemento/Elements.java
Elements.dataElement
public static Element dataElement(Element context, String name) { """ Looks for an element below {@code context} using the CSS selector {@code [data-element=&lt;name&gt;]} """ return context != null ? context.querySelector("[data-element=" + name + "]") : null; }
java
public static Element dataElement(Element context, String name) { return context != null ? context.querySelector("[data-element=" + name + "]") : null; }
[ "public", "static", "Element", "dataElement", "(", "Element", "context", ",", "String", "name", ")", "{", "return", "context", "!=", "null", "?", "context", ".", "querySelector", "(", "\"[data-element=\"", "+", "name", "+", "\"]\"", ")", ":", "null", ";", "}" ]
Looks for an element below {@code context} using the CSS selector {@code [data-element=&lt;name&gt;]}
[ "Looks", "for", "an", "element", "below", "{" ]
train
https://github.com/hal/core/blob/d6d03f0bb128dc0470f5dc75fdb1ea1014400602/gui/src/main/java/org/jboss/as/console/client/v3/elemento/Elements.java#L583-L585
powermock/powermock
powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java
PowerMock.createNicePartialMock
public static <T> T createNicePartialMock(Class<T> type, String methodName, Class<?>[] methodParameterTypes, Object[] constructorArguments, Class<?>[] constructorParameterTypes) { """ A utility method that may be used to nicely mock several methods in an easy way (by just passing in the method names of the method you wish to mock). Use this to handle overloaded methods <i>and</i> overloaded constructors. The mock object created will support mocking of final and native methods and invokes a specific constructor based on the supplied argument values. @param <T> the type of the mock object @param type the type of the mock object @param methodName The names of the methods that should be mocked. If {@code null}, then this method will have the same effect as just calling {@link #createMock(Class, Method...)} with the second parameter as {@code new Method[0]} (i.e. all methods in that class will be mocked). @param methodParameterTypes Parameter types that defines the method. Note that this is only needed to separate overloaded methods. @param constructorArguments The constructor arguments that will be used to invoke a certain constructor. @param constructorParameterTypes Parameter types that defines the constructor that should be invoked. Note that this is only needed to separate overloaded constructors. @return the mock object. """ ConstructorArgs constructorArgs = new ConstructorArgs(Whitebox.getConstructor(type, constructorParameterTypes), constructorArguments); return doMockSpecific(type, new NiceMockStrategy(), new String[]{methodName}, constructorArgs, methodParameterTypes); }
java
public static <T> T createNicePartialMock(Class<T> type, String methodName, Class<?>[] methodParameterTypes, Object[] constructorArguments, Class<?>[] constructorParameterTypes) { ConstructorArgs constructorArgs = new ConstructorArgs(Whitebox.getConstructor(type, constructorParameterTypes), constructorArguments); return doMockSpecific(type, new NiceMockStrategy(), new String[]{methodName}, constructorArgs, methodParameterTypes); }
[ "public", "static", "<", "T", ">", "T", "createNicePartialMock", "(", "Class", "<", "T", ">", "type", ",", "String", "methodName", ",", "Class", "<", "?", ">", "[", "]", "methodParameterTypes", ",", "Object", "[", "]", "constructorArguments", ",", "Class", "<", "?", ">", "[", "]", "constructorParameterTypes", ")", "{", "ConstructorArgs", "constructorArgs", "=", "new", "ConstructorArgs", "(", "Whitebox", ".", "getConstructor", "(", "type", ",", "constructorParameterTypes", ")", ",", "constructorArguments", ")", ";", "return", "doMockSpecific", "(", "type", ",", "new", "NiceMockStrategy", "(", ")", ",", "new", "String", "[", "]", "{", "methodName", "}", ",", "constructorArgs", ",", "methodParameterTypes", ")", ";", "}" ]
A utility method that may be used to nicely mock several methods in an easy way (by just passing in the method names of the method you wish to mock). Use this to handle overloaded methods <i>and</i> overloaded constructors. The mock object created will support mocking of final and native methods and invokes a specific constructor based on the supplied argument values. @param <T> the type of the mock object @param type the type of the mock object @param methodName The names of the methods that should be mocked. If {@code null}, then this method will have the same effect as just calling {@link #createMock(Class, Method...)} with the second parameter as {@code new Method[0]} (i.e. all methods in that class will be mocked). @param methodParameterTypes Parameter types that defines the method. Note that this is only needed to separate overloaded methods. @param constructorArguments The constructor arguments that will be used to invoke a certain constructor. @param constructorParameterTypes Parameter types that defines the constructor that should be invoked. Note that this is only needed to separate overloaded constructors. @return the mock object.
[ "A", "utility", "method", "that", "may", "be", "used", "to", "nicely", "mock", "several", "methods", "in", "an", "easy", "way", "(", "by", "just", "passing", "in", "the", "method", "names", "of", "the", "method", "you", "wish", "to", "mock", ")", ".", "Use", "this", "to", "handle", "overloaded", "methods", "<i", ">", "and<", "/", "i", ">", "overloaded", "constructors", ".", "The", "mock", "object", "created", "will", "support", "mocking", "of", "final", "and", "native", "methods", "and", "invokes", "a", "specific", "constructor", "based", "on", "the", "supplied", "argument", "values", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L1128-L1134
dihedron/dihedron-commons
src/main/java/org/dihedron/patterns/activities/base/CompoundActivity.java
CompoundActivity.perform
@Override public ActivityData perform(ActivityContext context, ActivityData data) throws ActivityException { """ Runs a set of sub-activities in a sequence (one at a time), with no parallelism. As soon as one of the activities throws an exception the whole processing is aborted and the exception is propagated to its wrapping activities. @see org.dihedron.tasks.Task#execute(org.dihedron.tasks.ExecutionContext) """ TypedVector<ActivityInfo> infos = new TypedVector<ActivityInfo>(); int i = 0; for(Activity activity : activities) { logger.trace("adding activity number {} with id '{}'...", i, activity.getId()); ActivityInfo info = new ActivityInfo(); info .setActivity(activity) .setContext(context) //.setData(i == 0 ? data : null); .setData(data); infos.add(info); logger.trace("... activity {} added!", i); ++i; } logger.trace("launching activity execution..."); return engine.execute(infos); }
java
@Override public ActivityData perform(ActivityContext context, ActivityData data) throws ActivityException { TypedVector<ActivityInfo> infos = new TypedVector<ActivityInfo>(); int i = 0; for(Activity activity : activities) { logger.trace("adding activity number {} with id '{}'...", i, activity.getId()); ActivityInfo info = new ActivityInfo(); info .setActivity(activity) .setContext(context) //.setData(i == 0 ? data : null); .setData(data); infos.add(info); logger.trace("... activity {} added!", i); ++i; } logger.trace("launching activity execution..."); return engine.execute(infos); }
[ "@", "Override", "public", "ActivityData", "perform", "(", "ActivityContext", "context", ",", "ActivityData", "data", ")", "throws", "ActivityException", "{", "TypedVector", "<", "ActivityInfo", ">", "infos", "=", "new", "TypedVector", "<", "ActivityInfo", ">", "(", ")", ";", "int", "i", "=", "0", ";", "for", "(", "Activity", "activity", ":", "activities", ")", "{", "logger", ".", "trace", "(", "\"adding activity number {} with id '{}'...\"", ",", "i", ",", "activity", ".", "getId", "(", ")", ")", ";", "ActivityInfo", "info", "=", "new", "ActivityInfo", "(", ")", ";", "info", ".", "setActivity", "(", "activity", ")", ".", "setContext", "(", "context", ")", "//.setData(i == 0 ? data : null);", ".", "setData", "(", "data", ")", ";", "infos", ".", "add", "(", "info", ")", ";", "logger", ".", "trace", "(", "\"... activity {} added!\"", ",", "i", ")", ";", "++", "i", ";", "}", "logger", ".", "trace", "(", "\"launching activity execution...\"", ")", ";", "return", "engine", ".", "execute", "(", "infos", ")", ";", "}" ]
Runs a set of sub-activities in a sequence (one at a time), with no parallelism. As soon as one of the activities throws an exception the whole processing is aborted and the exception is propagated to its wrapping activities. @see org.dihedron.tasks.Task#execute(org.dihedron.tasks.ExecutionContext)
[ "Runs", "a", "set", "of", "sub", "-", "activities", "in", "a", "sequence", "(", "one", "at", "a", "time", ")", "with", "no", "parallelism", ".", "As", "soon", "as", "one", "of", "the", "activities", "throws", "an", "exception", "the", "whole", "processing", "is", "aborted", "and", "the", "exception", "is", "propagated", "to", "its", "wrapping", "activities", "." ]
train
https://github.com/dihedron/dihedron-commons/blob/a5194cdaa0d6417ef4aade6ea407a1cad6e8458e/src/main/java/org/dihedron/patterns/activities/base/CompoundActivity.java#L64-L83
Azure/azure-sdk-for-java
containerregistry/resource-manager/v2017_03_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_03_01/implementation/RegistriesInner.java
RegistriesInner.regenerateCredential
public RegistryListCredentialsResultInner regenerateCredential(String resourceGroupName, String registryName, PasswordName name) { """ Regenerates one of the login credentials for the specified container registry. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param name Specifies name of the password which should be regenerated -- password or password2. Possible values include: 'password', 'password2' @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 RegistryListCredentialsResultInner object if successful. """ return regenerateCredentialWithServiceResponseAsync(resourceGroupName, registryName, name).toBlocking().single().body(); }
java
public RegistryListCredentialsResultInner regenerateCredential(String resourceGroupName, String registryName, PasswordName name) { return regenerateCredentialWithServiceResponseAsync(resourceGroupName, registryName, name).toBlocking().single().body(); }
[ "public", "RegistryListCredentialsResultInner", "regenerateCredential", "(", "String", "resourceGroupName", ",", "String", "registryName", ",", "PasswordName", "name", ")", "{", "return", "regenerateCredentialWithServiceResponseAsync", "(", "resourceGroupName", ",", "registryName", ",", "name", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Regenerates one of the login credentials for the specified container registry. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param name Specifies name of the password which should be regenerated -- password or password2. Possible values include: 'password', 'password2' @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 RegistryListCredentialsResultInner object if successful.
[ "Regenerates", "one", "of", "the", "login", "credentials", "for", "the", "specified", "container", "registry", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2017_03_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_03_01/implementation/RegistriesInner.java#L962-L964
alkacon/opencms-core
src-modules/org/opencms/workplace/tools/searchindex/CmsEditSearchIndexDialog.java
CmsEditSearchIndexDialog.getRebuildModeWidgetConfiguration
private List<CmsSelectWidgetOption> getRebuildModeWidgetConfiguration() { """ Returns the rebuild mode widget configuration.<p> @return the rebuild mode widget configuration """ List<CmsSelectWidgetOption> result = new ArrayList<CmsSelectWidgetOption>(); String rebuildMode = getSearchIndexIndex().getRebuildMode(); result.add(new CmsSelectWidgetOption("auto", "auto".equals(rebuildMode))); result.add(new CmsSelectWidgetOption("manual", "manual".equals(rebuildMode))); result.add(new CmsSelectWidgetOption("offline", "offline".equals(rebuildMode))); return result; }
java
private List<CmsSelectWidgetOption> getRebuildModeWidgetConfiguration() { List<CmsSelectWidgetOption> result = new ArrayList<CmsSelectWidgetOption>(); String rebuildMode = getSearchIndexIndex().getRebuildMode(); result.add(new CmsSelectWidgetOption("auto", "auto".equals(rebuildMode))); result.add(new CmsSelectWidgetOption("manual", "manual".equals(rebuildMode))); result.add(new CmsSelectWidgetOption("offline", "offline".equals(rebuildMode))); return result; }
[ "private", "List", "<", "CmsSelectWidgetOption", ">", "getRebuildModeWidgetConfiguration", "(", ")", "{", "List", "<", "CmsSelectWidgetOption", ">", "result", "=", "new", "ArrayList", "<", "CmsSelectWidgetOption", ">", "(", ")", ";", "String", "rebuildMode", "=", "getSearchIndexIndex", "(", ")", ".", "getRebuildMode", "(", ")", ";", "result", ".", "add", "(", "new", "CmsSelectWidgetOption", "(", "\"auto\"", ",", "\"auto\"", ".", "equals", "(", "rebuildMode", ")", ")", ")", ";", "result", ".", "add", "(", "new", "CmsSelectWidgetOption", "(", "\"manual\"", ",", "\"manual\"", ".", "equals", "(", "rebuildMode", ")", ")", ")", ";", "result", ".", "add", "(", "new", "CmsSelectWidgetOption", "(", "\"offline\"", ",", "\"offline\"", ".", "equals", "(", "rebuildMode", ")", ")", ")", ";", "return", "result", ";", "}" ]
Returns the rebuild mode widget configuration.<p> @return the rebuild mode widget configuration
[ "Returns", "the", "rebuild", "mode", "widget", "configuration", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/searchindex/CmsEditSearchIndexDialog.java#L233-L241
gosu-lang/gosu-lang
gosu-lab/src/main/java/editor/util/EditorUtilities.java
EditorUtilities.findAncestor
public static <T> T findAncestor( Component start, Class<T> aClass ) { """ Finds the first widget above the passed in widget of the given class """ if( start == null ) { return null; } return findAtOrAbove( start.getParent(), aClass ); }
java
public static <T> T findAncestor( Component start, Class<T> aClass ) { if( start == null ) { return null; } return findAtOrAbove( start.getParent(), aClass ); }
[ "public", "static", "<", "T", ">", "T", "findAncestor", "(", "Component", "start", ",", "Class", "<", "T", ">", "aClass", ")", "{", "if", "(", "start", "==", "null", ")", "{", "return", "null", ";", "}", "return", "findAtOrAbove", "(", "start", ".", "getParent", "(", ")", ",", "aClass", ")", ";", "}" ]
Finds the first widget above the passed in widget of the given class
[ "Finds", "the", "first", "widget", "above", "the", "passed", "in", "widget", "of", "the", "given", "class" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-lab/src/main/java/editor/util/EditorUtilities.java#L757-L764
undertow-io/undertow
servlet/src/main/java/io/undertow/servlet/Servlets.java
Servlets.errorPage
public static ErrorPage errorPage(String location, Class<? extends Throwable> exceptionType) { """ Create an ErrorPage instance for a given exception type @param location The location to redirect to @param exceptionType The exception type @return The error page definition """ return new ErrorPage(location, exceptionType); }
java
public static ErrorPage errorPage(String location, Class<? extends Throwable> exceptionType) { return new ErrorPage(location, exceptionType); }
[ "public", "static", "ErrorPage", "errorPage", "(", "String", "location", ",", "Class", "<", "?", "extends", "Throwable", ">", "exceptionType", ")", "{", "return", "new", "ErrorPage", "(", "location", ",", "exceptionType", ")", ";", "}" ]
Create an ErrorPage instance for a given exception type @param location The location to redirect to @param exceptionType The exception type @return The error page definition
[ "Create", "an", "ErrorPage", "instance", "for", "a", "given", "exception", "type" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/Servlets.java#L204-L206
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/xml/XmlIO.java
XmlIO.save
public static void save(final AnnotationMappingInfo xmlInfo, final File file, final String encoding) throws XmlOperateException { """ XMLをファイルに保存する。 @since 1.1 @param xmlInfo XML情報。 @param file 書き込み先 @param encoding ファイルの文字コード。 @throws XmlOperateException XMLの書き込みに失敗した場合。 @throws IllegalArgumentException xmlInfo is null. @throws IllegalArgumentException file is null or encoding is empty. """ ArgUtils.notNull(xmlInfo, "xmlInfo"); ArgUtils.notNull(file, "file"); ArgUtils.notEmpty(encoding, "encoding"); final Marshaller marshaller; try { JAXBContext context = JAXBContext.newInstance(xmlInfo.getClass()); marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); } catch (JAXBException e) { throw new XmlOperateException("fail setting JAXB context.", e); } File dir = file.getParentFile(); if(dir != null && !dir.exists()) { dir.mkdirs(); } try(Writer writer = new OutputStreamWriter(new FileOutputStream(file), encoding)) { marshaller.marshal(xmlInfo, writer); } catch(JAXBException | IOException e) { throw new XmlOperateException(String.format("fail save xml file '%s'.", file.getPath()), e); } }
java
public static void save(final AnnotationMappingInfo xmlInfo, final File file, final String encoding) throws XmlOperateException { ArgUtils.notNull(xmlInfo, "xmlInfo"); ArgUtils.notNull(file, "file"); ArgUtils.notEmpty(encoding, "encoding"); final Marshaller marshaller; try { JAXBContext context = JAXBContext.newInstance(xmlInfo.getClass()); marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); } catch (JAXBException e) { throw new XmlOperateException("fail setting JAXB context.", e); } File dir = file.getParentFile(); if(dir != null && !dir.exists()) { dir.mkdirs(); } try(Writer writer = new OutputStreamWriter(new FileOutputStream(file), encoding)) { marshaller.marshal(xmlInfo, writer); } catch(JAXBException | IOException e) { throw new XmlOperateException(String.format("fail save xml file '%s'.", file.getPath()), e); } }
[ "public", "static", "void", "save", "(", "final", "AnnotationMappingInfo", "xmlInfo", ",", "final", "File", "file", ",", "final", "String", "encoding", ")", "throws", "XmlOperateException", "{", "ArgUtils", ".", "notNull", "(", "xmlInfo", ",", "\"xmlInfo\"", ")", ";", "ArgUtils", ".", "notNull", "(", "file", ",", "\"file\"", ")", ";", "ArgUtils", ".", "notEmpty", "(", "encoding", ",", "\"encoding\"", ")", ";", "final", "Marshaller", "marshaller", ";", "try", "{", "JAXBContext", "context", "=", "JAXBContext", ".", "newInstance", "(", "xmlInfo", ".", "getClass", "(", ")", ")", ";", "marshaller", "=", "context", ".", "createMarshaller", "(", ")", ";", "marshaller", ".", "setProperty", "(", "Marshaller", ".", "JAXB_ENCODING", ",", "encoding", ")", ";", "marshaller", ".", "setProperty", "(", "Marshaller", ".", "JAXB_FORMATTED_OUTPUT", ",", "true", ")", ";", "}", "catch", "(", "JAXBException", "e", ")", "{", "throw", "new", "XmlOperateException", "(", "\"fail setting JAXB context.\"", ",", "e", ")", ";", "}", "File", "dir", "=", "file", ".", "getParentFile", "(", ")", ";", "if", "(", "dir", "!=", "null", "&&", "!", "dir", ".", "exists", "(", ")", ")", "{", "dir", ".", "mkdirs", "(", ")", ";", "}", "try", "(", "Writer", "writer", "=", "new", "OutputStreamWriter", "(", "new", "FileOutputStream", "(", "file", ")", ",", "encoding", ")", ")", "{", "marshaller", ".", "marshal", "(", "xmlInfo", ",", "writer", ")", ";", "}", "catch", "(", "JAXBException", "|", "IOException", "e", ")", "{", "throw", "new", "XmlOperateException", "(", "String", ".", "format", "(", "\"fail save xml file '%s'.\"", ",", "file", ".", "getPath", "(", ")", ")", ",", "e", ")", ";", "}", "}" ]
XMLをファイルに保存する。 @since 1.1 @param xmlInfo XML情報。 @param file 書き込み先 @param encoding ファイルの文字コード。 @throws XmlOperateException XMLの書き込みに失敗した場合。 @throws IllegalArgumentException xmlInfo is null. @throws IllegalArgumentException file is null or encoding is empty.
[ "XMLをファイルに保存する。" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/xml/XmlIO.java#L154-L183
hibernate/hibernate-ogm
mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/MongoDBDialect.java
MongoDBDialect.getAssociationStorageStrategy
private static AssociationStorageStrategy getAssociationStorageStrategy(AssociationKeyMetadata keyMetadata, AssociationTypeContext associationTypeContext) { """ Returns the {@link AssociationStorageStrategy} effectively applying for the given association. If a setting is given via the option mechanism, that one will be taken, otherwise the default value as given via the corresponding configuration property is applied. """ AssociationStorageType associationStorage = associationTypeContext .getOptionsContext() .getUnique( AssociationStorageOption.class ); AssociationDocumentStorageType associationDocumentStorageType = associationTypeContext .getOptionsContext() .getUnique( AssociationDocumentStorageOption.class ); return AssociationStorageStrategy.getInstance( keyMetadata, associationStorage, associationDocumentStorageType ); }
java
private static AssociationStorageStrategy getAssociationStorageStrategy(AssociationKeyMetadata keyMetadata, AssociationTypeContext associationTypeContext) { AssociationStorageType associationStorage = associationTypeContext .getOptionsContext() .getUnique( AssociationStorageOption.class ); AssociationDocumentStorageType associationDocumentStorageType = associationTypeContext .getOptionsContext() .getUnique( AssociationDocumentStorageOption.class ); return AssociationStorageStrategy.getInstance( keyMetadata, associationStorage, associationDocumentStorageType ); }
[ "private", "static", "AssociationStorageStrategy", "getAssociationStorageStrategy", "(", "AssociationKeyMetadata", "keyMetadata", ",", "AssociationTypeContext", "associationTypeContext", ")", "{", "AssociationStorageType", "associationStorage", "=", "associationTypeContext", ".", "getOptionsContext", "(", ")", ".", "getUnique", "(", "AssociationStorageOption", ".", "class", ")", ";", "AssociationDocumentStorageType", "associationDocumentStorageType", "=", "associationTypeContext", ".", "getOptionsContext", "(", ")", ".", "getUnique", "(", "AssociationDocumentStorageOption", ".", "class", ")", ";", "return", "AssociationStorageStrategy", ".", "getInstance", "(", "keyMetadata", ",", "associationStorage", ",", "associationDocumentStorageType", ")", ";", "}" ]
Returns the {@link AssociationStorageStrategy} effectively applying for the given association. If a setting is given via the option mechanism, that one will be taken, otherwise the default value as given via the corresponding configuration property is applied.
[ "Returns", "the", "{" ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/MongoDBDialect.java#L1561-L1571
Alluxio/alluxio
core/common/src/main/java/alluxio/metrics/MetricsSystem.java
MetricsSystem.checkMinimalPollingPeriod
public static void checkMinimalPollingPeriod(TimeUnit pollUnit, int pollPeriod) throws IllegalArgumentException { """ Checks if the poll period is smaller that the minimal poll period which is 1 second. @param pollUnit the polling unit @param pollPeriod the polling period @throws IllegalArgumentException if the polling period is invalid """ int period = (int) MINIMAL_POLL_UNIT.convert(pollPeriod, pollUnit); Preconditions.checkArgument(period >= MINIMAL_POLL_PERIOD, "Polling period %d %d is below the minimal polling period", pollPeriod, pollUnit); }
java
public static void checkMinimalPollingPeriod(TimeUnit pollUnit, int pollPeriod) throws IllegalArgumentException { int period = (int) MINIMAL_POLL_UNIT.convert(pollPeriod, pollUnit); Preconditions.checkArgument(period >= MINIMAL_POLL_PERIOD, "Polling period %d %d is below the minimal polling period", pollPeriod, pollUnit); }
[ "public", "static", "void", "checkMinimalPollingPeriod", "(", "TimeUnit", "pollUnit", ",", "int", "pollPeriod", ")", "throws", "IllegalArgumentException", "{", "int", "period", "=", "(", "int", ")", "MINIMAL_POLL_UNIT", ".", "convert", "(", "pollPeriod", ",", "pollUnit", ")", ";", "Preconditions", ".", "checkArgument", "(", "period", ">=", "MINIMAL_POLL_PERIOD", ",", "\"Polling period %d %d is below the minimal polling period\"", ",", "pollPeriod", ",", "pollUnit", ")", ";", "}" ]
Checks if the poll period is smaller that the minimal poll period which is 1 second. @param pollUnit the polling unit @param pollPeriod the polling period @throws IllegalArgumentException if the polling period is invalid
[ "Checks", "if", "the", "poll", "period", "is", "smaller", "that", "the", "minimal", "poll", "period", "which", "is", "1", "second", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/metrics/MetricsSystem.java#L331-L336
lucee/Lucee
core/src/main/java/lucee/commons/lang/StringUtil.java
StringUtil.removeQuotes
public static String removeQuotes(String string, boolean trim) { """ removes quotes(",') that wraps the string @param string @return """ if (string == null) return string; if (trim) string = string.trim(); if (string.length() < 2) return string; if ((StringUtil.startsWith(string, '"') && StringUtil.endsWith(string, '"')) || (StringUtil.startsWith(string, '\'') && StringUtil.endsWith(string, '\''))) { string = string.substring(1, string.length() - 1); if (trim) string = string.trim(); } return string; }
java
public static String removeQuotes(String string, boolean trim) { if (string == null) return string; if (trim) string = string.trim(); if (string.length() < 2) return string; if ((StringUtil.startsWith(string, '"') && StringUtil.endsWith(string, '"')) || (StringUtil.startsWith(string, '\'') && StringUtil.endsWith(string, '\''))) { string = string.substring(1, string.length() - 1); if (trim) string = string.trim(); } return string; }
[ "public", "static", "String", "removeQuotes", "(", "String", "string", ",", "boolean", "trim", ")", "{", "if", "(", "string", "==", "null", ")", "return", "string", ";", "if", "(", "trim", ")", "string", "=", "string", ".", "trim", "(", ")", ";", "if", "(", "string", ".", "length", "(", ")", "<", "2", ")", "return", "string", ";", "if", "(", "(", "StringUtil", ".", "startsWith", "(", "string", ",", "'", "'", ")", "&&", "StringUtil", ".", "endsWith", "(", "string", ",", "'", "'", ")", ")", "||", "(", "StringUtil", ".", "startsWith", "(", "string", ",", "'", "'", ")", "&&", "StringUtil", ".", "endsWith", "(", "string", ",", "'", "'", ")", ")", ")", "{", "string", "=", "string", ".", "substring", "(", "1", ",", "string", ".", "length", "(", ")", "-", "1", ")", ";", "if", "(", "trim", ")", "string", "=", "string", ".", "trim", "(", ")", ";", "}", "return", "string", ";", "}" ]
removes quotes(",') that wraps the string @param string @return
[ "removes", "quotes", "(", ")", "that", "wraps", "the", "string" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/lang/StringUtil.java#L1076-L1086
playn/playn
core/src/playn/core/Assets.java
Assets.getRemoteImage
public Image getRemoteImage (String url, int width, int height) { """ Asynchronously loads and returns the image at the specified URL. The width and height of the image will be the supplied {@code width} and {@code height} until the image is loaded. <em>Note:</em> on non-HTML platforms, this spawns a new thread for each loaded image. Thus, attempts to load large numbers of remote images simultaneously may result in poor performance. """ Exception error = new Exception( "Remote image loading not yet supported: " + url + "@" + width + "x" + height); ImageImpl image = createImage(false, width, height, url); image.fail(error); return image; }
java
public Image getRemoteImage (String url, int width, int height) { Exception error = new Exception( "Remote image loading not yet supported: " + url + "@" + width + "x" + height); ImageImpl image = createImage(false, width, height, url); image.fail(error); return image; }
[ "public", "Image", "getRemoteImage", "(", "String", "url", ",", "int", "width", ",", "int", "height", ")", "{", "Exception", "error", "=", "new", "Exception", "(", "\"Remote image loading not yet supported: \"", "+", "url", "+", "\"@\"", "+", "width", "+", "\"x\"", "+", "height", ")", ";", "ImageImpl", "image", "=", "createImage", "(", "false", ",", "width", ",", "height", ",", "url", ")", ";", "image", ".", "fail", "(", "error", ")", ";", "return", "image", ";", "}" ]
Asynchronously loads and returns the image at the specified URL. The width and height of the image will be the supplied {@code width} and {@code height} until the image is loaded. <em>Note:</em> on non-HTML platforms, this spawns a new thread for each loaded image. Thus, attempts to load large numbers of remote images simultaneously may result in poor performance.
[ "Asynchronously", "loads", "and", "returns", "the", "image", "at", "the", "specified", "URL", ".", "The", "width", "and", "height", "of", "the", "image", "will", "be", "the", "supplied", "{" ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/Assets.java#L85-L91
Azure/azure-sdk-for-java
eventgrid/resource-manager/v2018_09_15_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_09_15_preview/implementation/DomainsInner.java
DomainsInner.regenerateKeyAsync
public Observable<DomainSharedAccessKeysInner> regenerateKeyAsync(String resourceGroupName, String domainName, String keyName) { """ Regenerate key for a domain. Regenerate a shared access key for a domain. @param resourceGroupName The name of the resource group within the user's subscription. @param domainName Name of the domain @param keyName Key name to regenerate key1 or key2 @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DomainSharedAccessKeysInner object """ return regenerateKeyWithServiceResponseAsync(resourceGroupName, domainName, keyName).map(new Func1<ServiceResponse<DomainSharedAccessKeysInner>, DomainSharedAccessKeysInner>() { @Override public DomainSharedAccessKeysInner call(ServiceResponse<DomainSharedAccessKeysInner> response) { return response.body(); } }); }
java
public Observable<DomainSharedAccessKeysInner> regenerateKeyAsync(String resourceGroupName, String domainName, String keyName) { return regenerateKeyWithServiceResponseAsync(resourceGroupName, domainName, keyName).map(new Func1<ServiceResponse<DomainSharedAccessKeysInner>, DomainSharedAccessKeysInner>() { @Override public DomainSharedAccessKeysInner call(ServiceResponse<DomainSharedAccessKeysInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DomainSharedAccessKeysInner", ">", "regenerateKeyAsync", "(", "String", "resourceGroupName", ",", "String", "domainName", ",", "String", "keyName", ")", "{", "return", "regenerateKeyWithServiceResponseAsync", "(", "resourceGroupName", ",", "domainName", ",", "keyName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "DomainSharedAccessKeysInner", ">", ",", "DomainSharedAccessKeysInner", ">", "(", ")", "{", "@", "Override", "public", "DomainSharedAccessKeysInner", "call", "(", "ServiceResponse", "<", "DomainSharedAccessKeysInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Regenerate key for a domain. Regenerate a shared access key for a domain. @param resourceGroupName The name of the resource group within the user's subscription. @param domainName Name of the domain @param keyName Key name to regenerate key1 or key2 @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DomainSharedAccessKeysInner object
[ "Regenerate", "key", "for", "a", "domain", ".", "Regenerate", "a", "shared", "access", "key", "for", "a", "domain", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2018_09_15_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_09_15_preview/implementation/DomainsInner.java#L1192-L1199
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/DFSOutputStream.java
DFSOutputStream.setupPipelineForAppend
private boolean setupPipelineForAppend(LocatedBlock lastBlock) throws IOException { """ Setup the Append pipeline, the length of current pipeline will shrink if any datanodes are dead during the process. """ if (nodes == null || nodes.length == 0) { String msg = "Could not get block locations. " + "Source file \"" + src + "\" - Aborting..."; DFSClient.LOG.warn(msg); setLastException(new IOException(msg)); closed = true; if (streamer != null) streamer.close(); return false; } boolean success = createBlockOutputStream(nodes, dfsClient.clientName, false, true); long oldGenerationStamp = ((LocatedBlockWithOldGS)lastBlock).getOldGenerationStamp(); if (success) { // bump up the generation stamp in NN. Block newBlock = lastBlock.getBlock(); Block oldBlock = new Block(newBlock.getBlockId(), newBlock.getNumBytes(), oldGenerationStamp); dfsClient.namenode.updatePipeline(dfsClient.clientName, oldBlock, newBlock, nodes); } else { DFSClient.LOG.warn("Fall back to block recovery process when trying" + " to setup the append pipeline for file " + src); // set the old generation stamp block.setGenerationStamp(oldGenerationStamp); // fall back the block recovery while(processDatanodeError(true, true)) { try { Thread.sleep(1000); } catch (InterruptedException e) { lastException = new IOException(e); break; } } } return success; }
java
private boolean setupPipelineForAppend(LocatedBlock lastBlock) throws IOException { if (nodes == null || nodes.length == 0) { String msg = "Could not get block locations. " + "Source file \"" + src + "\" - Aborting..."; DFSClient.LOG.warn(msg); setLastException(new IOException(msg)); closed = true; if (streamer != null) streamer.close(); return false; } boolean success = createBlockOutputStream(nodes, dfsClient.clientName, false, true); long oldGenerationStamp = ((LocatedBlockWithOldGS)lastBlock).getOldGenerationStamp(); if (success) { // bump up the generation stamp in NN. Block newBlock = lastBlock.getBlock(); Block oldBlock = new Block(newBlock.getBlockId(), newBlock.getNumBytes(), oldGenerationStamp); dfsClient.namenode.updatePipeline(dfsClient.clientName, oldBlock, newBlock, nodes); } else { DFSClient.LOG.warn("Fall back to block recovery process when trying" + " to setup the append pipeline for file " + src); // set the old generation stamp block.setGenerationStamp(oldGenerationStamp); // fall back the block recovery while(processDatanodeError(true, true)) { try { Thread.sleep(1000); } catch (InterruptedException e) { lastException = new IOException(e); break; } } } return success; }
[ "private", "boolean", "setupPipelineForAppend", "(", "LocatedBlock", "lastBlock", ")", "throws", "IOException", "{", "if", "(", "nodes", "==", "null", "||", "nodes", ".", "length", "==", "0", ")", "{", "String", "msg", "=", "\"Could not get block locations. \"", "+", "\"Source file \\\"\"", "+", "src", "+", "\"\\\" - Aborting...\"", ";", "DFSClient", ".", "LOG", ".", "warn", "(", "msg", ")", ";", "setLastException", "(", "new", "IOException", "(", "msg", ")", ")", ";", "closed", "=", "true", ";", "if", "(", "streamer", "!=", "null", ")", "streamer", ".", "close", "(", ")", ";", "return", "false", ";", "}", "boolean", "success", "=", "createBlockOutputStream", "(", "nodes", ",", "dfsClient", ".", "clientName", ",", "false", ",", "true", ")", ";", "long", "oldGenerationStamp", "=", "(", "(", "LocatedBlockWithOldGS", ")", "lastBlock", ")", ".", "getOldGenerationStamp", "(", ")", ";", "if", "(", "success", ")", "{", "// bump up the generation stamp in NN.", "Block", "newBlock", "=", "lastBlock", ".", "getBlock", "(", ")", ";", "Block", "oldBlock", "=", "new", "Block", "(", "newBlock", ".", "getBlockId", "(", ")", ",", "newBlock", ".", "getNumBytes", "(", ")", ",", "oldGenerationStamp", ")", ";", "dfsClient", ".", "namenode", ".", "updatePipeline", "(", "dfsClient", ".", "clientName", ",", "oldBlock", ",", "newBlock", ",", "nodes", ")", ";", "}", "else", "{", "DFSClient", ".", "LOG", ".", "warn", "(", "\"Fall back to block recovery process when trying\"", "+", "\" to setup the append pipeline for file \"", "+", "src", ")", ";", "// set the old generation stamp ", "block", ".", "setGenerationStamp", "(", "oldGenerationStamp", ")", ";", "// fall back the block recovery", "while", "(", "processDatanodeError", "(", "true", ",", "true", ")", ")", "{", "try", "{", "Thread", ".", "sleep", "(", "1000", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "lastException", "=", "new", "IOException", "(", "e", ")", ";", "break", ";", "}", "}", "}", "return", "success", ";", "}" ]
Setup the Append pipeline, the length of current pipeline will shrink if any datanodes are dead during the process.
[ "Setup", "the", "Append", "pipeline", "the", "length", "of", "current", "pipeline", "will", "shrink", "if", "any", "datanodes", "are", "dead", "during", "the", "process", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/DFSOutputStream.java#L1226-L1265
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/repository/internal/AbstractCachedExtensionRepository.java
AbstractCachedExtensionRepository.removeCachedExtensionVersion
protected void removeCachedExtensionVersion(String feature, E extension) { """ Remove passed extension associated to passed feature from the cache. @param feature the feature associated to the extension @param extension the extension """ // versions List<E> extensionVersions = this.extensionsVersions.get(feature); extensionVersions.remove(extension); if (extensionVersions.isEmpty()) { this.extensionsVersions.remove(feature); } }
java
protected void removeCachedExtensionVersion(String feature, E extension) { // versions List<E> extensionVersions = this.extensionsVersions.get(feature); extensionVersions.remove(extension); if (extensionVersions.isEmpty()) { this.extensionsVersions.remove(feature); } }
[ "protected", "void", "removeCachedExtensionVersion", "(", "String", "feature", ",", "E", "extension", ")", "{", "// versions", "List", "<", "E", ">", "extensionVersions", "=", "this", ".", "extensionsVersions", ".", "get", "(", "feature", ")", ";", "extensionVersions", ".", "remove", "(", "extension", ")", ";", "if", "(", "extensionVersions", ".", "isEmpty", "(", ")", ")", "{", "this", ".", "extensionsVersions", ".", "remove", "(", "feature", ")", ";", "}", "}" ]
Remove passed extension associated to passed feature from the cache. @param feature the feature associated to the extension @param extension the extension
[ "Remove", "passed", "extension", "associated", "to", "passed", "feature", "from", "the", "cache", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/repository/internal/AbstractCachedExtensionRepository.java#L167-L175
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.createPrebuiltEntityRole
public UUID createPrebuiltEntityRole(UUID appId, String versionId, UUID entityId, CreatePrebuiltEntityRoleOptionalParameter createPrebuiltEntityRoleOptionalParameter) { """ Create an entity role for an entity in the application. @param appId The application ID. @param versionId The version ID. @param entityId The entity model ID. @param createPrebuiltEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the UUID object if successful. """ return createPrebuiltEntityRoleWithServiceResponseAsync(appId, versionId, entityId, createPrebuiltEntityRoleOptionalParameter).toBlocking().single().body(); }
java
public UUID createPrebuiltEntityRole(UUID appId, String versionId, UUID entityId, CreatePrebuiltEntityRoleOptionalParameter createPrebuiltEntityRoleOptionalParameter) { return createPrebuiltEntityRoleWithServiceResponseAsync(appId, versionId, entityId, createPrebuiltEntityRoleOptionalParameter).toBlocking().single().body(); }
[ "public", "UUID", "createPrebuiltEntityRole", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ",", "CreatePrebuiltEntityRoleOptionalParameter", "createPrebuiltEntityRoleOptionalParameter", ")", "{", "return", "createPrebuiltEntityRoleWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "entityId", ",", "createPrebuiltEntityRoleOptionalParameter", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Create an entity role for an entity in the application. @param appId The application ID. @param versionId The version ID. @param entityId The entity model ID. @param createPrebuiltEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the UUID object if successful.
[ "Create", "an", "entity", "role", "for", "an", "entity", "in", "the", "application", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L8032-L8034
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/parser/XPathParser.java
XPathParser.parseIfExpr
private void parseIfExpr() throws TTXPathException { """ Parses the the rule IfExpr according to the following production rule: <p> [7] IfExpr ::= <"if" "("> Expr ")" "then" ExprSingle "else" ExprSingle. </p> @throws TTXPathException """ // parse if expression consume("if", true); consume(TokenType.OPEN_BR, true); // parse test expression axis parseExpression(); consume(TokenType.CLOSE_BR, true); // parse then expression consume("then", true); parseExprSingle(); // parse else expression consume("else", true); parseExprSingle(); mPipeBuilder.addIfExpression(getTransaction()); }
java
private void parseIfExpr() throws TTXPathException { // parse if expression consume("if", true); consume(TokenType.OPEN_BR, true); // parse test expression axis parseExpression(); consume(TokenType.CLOSE_BR, true); // parse then expression consume("then", true); parseExprSingle(); // parse else expression consume("else", true); parseExprSingle(); mPipeBuilder.addIfExpression(getTransaction()); }
[ "private", "void", "parseIfExpr", "(", ")", "throws", "TTXPathException", "{", "// parse if expression", "consume", "(", "\"if\"", ",", "true", ")", ";", "consume", "(", "TokenType", ".", "OPEN_BR", ",", "true", ")", ";", "// parse test expression axis", "parseExpression", "(", ")", ";", "consume", "(", "TokenType", ".", "CLOSE_BR", ",", "true", ")", ";", "// parse then expression", "consume", "(", "\"then\"", ",", "true", ")", ";", "parseExprSingle", "(", ")", ";", "// parse else expression", "consume", "(", "\"else\"", ",", "true", ")", ";", "parseExprSingle", "(", ")", ";", "mPipeBuilder", ".", "addIfExpression", "(", "getTransaction", "(", ")", ")", ";", "}" ]
Parses the the rule IfExpr according to the following production rule: <p> [7] IfExpr ::= <"if" "("> Expr ")" "then" ExprSingle "else" ExprSingle. </p> @throws TTXPathException
[ "Parses", "the", "the", "rule", "IfExpr", "according", "to", "the", "following", "production", "rule", ":", "<p", ">", "[", "7", "]", "IfExpr", "::", "=", "<", "if", "(", ">", "Expr", ")", "then", "ExprSingle", "else", "ExprSingle", ".", "<", "/", "p", ">" ]
train
https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/parser/XPathParser.java#L290-L310
phax/ph-schedule
ph-mini-quartz/src/main/java/com/helger/quartz/TriggerBuilder.java
TriggerBuilder.withIdentity
@Nonnull public TriggerBuilder <T> withIdentity (final String name) { """ Use a <code>TriggerKey</code> with the given name and default group to identify the Trigger. <p> If none of the 'withIdentity' methods are set on the TriggerBuilder, then a random, unique TriggerKey will be generated. </p> @param name the name element for the Trigger's TriggerKey @return the updated TriggerBuilder @see TriggerKey @see ITrigger#getKey() """ m_aKey = new TriggerKey (name, null); return this; }
java
@Nonnull public TriggerBuilder <T> withIdentity (final String name) { m_aKey = new TriggerKey (name, null); return this; }
[ "@", "Nonnull", "public", "TriggerBuilder", "<", "T", ">", "withIdentity", "(", "final", "String", "name", ")", "{", "m_aKey", "=", "new", "TriggerKey", "(", "name", ",", "null", ")", ";", "return", "this", ";", "}" ]
Use a <code>TriggerKey</code> with the given name and default group to identify the Trigger. <p> If none of the 'withIdentity' methods are set on the TriggerBuilder, then a random, unique TriggerKey will be generated. </p> @param name the name element for the Trigger's TriggerKey @return the updated TriggerBuilder @see TriggerKey @see ITrigger#getKey()
[ "Use", "a", "<code", ">", "TriggerKey<", "/", "code", ">", "with", "the", "given", "name", "and", "default", "group", "to", "identify", "the", "Trigger", ".", "<p", ">", "If", "none", "of", "the", "withIdentity", "methods", "are", "set", "on", "the", "TriggerBuilder", "then", "a", "random", "unique", "TriggerKey", "will", "be", "generated", ".", "<", "/", "p", ">" ]
train
https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-mini-quartz/src/main/java/com/helger/quartz/TriggerBuilder.java#L132-L137
intive-FDV/DynamicJasper
src/main/java/ar/com/fdvs/dj/util/StreamUtils.java
StreamUtils.copyThenClose
public static void copyThenClose(InputStream input, OutputStream output) throws IOException { """ Copies information between specified streams and then closes both of the streams. @throws java.io.IOException """ copy(input, output); input.close(); output.close(); }
java
public static void copyThenClose(InputStream input, OutputStream output) throws IOException { copy(input, output); input.close(); output.close(); }
[ "public", "static", "void", "copyThenClose", "(", "InputStream", "input", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "copy", "(", "input", ",", "output", ")", ";", "input", ".", "close", "(", ")", ";", "output", ".", "close", "(", ")", ";", "}" ]
Copies information between specified streams and then closes both of the streams. @throws java.io.IOException
[ "Copies", "information", "between", "specified", "streams", "and", "then", "closes", "both", "of", "the", "streams", "." ]
train
https://github.com/intive-FDV/DynamicJasper/blob/63919574cc401ae40574d13129f628e66d1682a3/src/main/java/ar/com/fdvs/dj/util/StreamUtils.java#L61-L66
GwtMaterialDesign/gwt-material-addins
src/main/java/gwt/material/design/addins/client/pathanimator/MaterialPathAnimator.java
MaterialPathAnimator.animate
public static void animate(Widget source, Widget target, Functions.Func callback) { """ Helper method to apply the path animator with callback. @param source Source widget to apply the Path Animator @param target Target widget to apply the Path Animator @param callback The callback method to be called when the path animator is applied """ animate(source.getElement(), target.getElement(), callback); }
java
public static void animate(Widget source, Widget target, Functions.Func callback) { animate(source.getElement(), target.getElement(), callback); }
[ "public", "static", "void", "animate", "(", "Widget", "source", ",", "Widget", "target", ",", "Functions", ".", "Func", "callback", ")", "{", "animate", "(", "source", ".", "getElement", "(", ")", ",", "target", ".", "getElement", "(", ")", ",", "callback", ")", ";", "}" ]
Helper method to apply the path animator with callback. @param source Source widget to apply the Path Animator @param target Target widget to apply the Path Animator @param callback The callback method to be called when the path animator is applied
[ "Helper", "method", "to", "apply", "the", "path", "animator", "with", "callback", "." ]
train
https://github.com/GwtMaterialDesign/gwt-material-addins/blob/11aec9d92918225f70f936285d0ae94f2178c36e/src/main/java/gwt/material/design/addins/client/pathanimator/MaterialPathAnimator.java#L121-L123
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java
JBBPDslBuilder.IntArray
public JBBPDslBuilder IntArray(final String name, final String sizeExpression) { """ Add named integer array with size calculated through expression. @param name name of field, can be nul for anonymous @param sizeExpression expression to be used to calculate size, must not be null @return the builder instance, must not be null """ final Item item = new Item(BinType.INT_ARRAY, name, this.byteOrder); item.sizeExpression = assertExpressionChars(sizeExpression); this.addItem(item); return this; }
java
public JBBPDslBuilder IntArray(final String name, final String sizeExpression) { final Item item = new Item(BinType.INT_ARRAY, name, this.byteOrder); item.sizeExpression = assertExpressionChars(sizeExpression); this.addItem(item); return this; }
[ "public", "JBBPDslBuilder", "IntArray", "(", "final", "String", "name", ",", "final", "String", "sizeExpression", ")", "{", "final", "Item", "item", "=", "new", "Item", "(", "BinType", ".", "INT_ARRAY", ",", "name", ",", "this", ".", "byteOrder", ")", ";", "item", ".", "sizeExpression", "=", "assertExpressionChars", "(", "sizeExpression", ")", ";", "this", ".", "addItem", "(", "item", ")", ";", "return", "this", ";", "}" ]
Add named integer array with size calculated through expression. @param name name of field, can be nul for anonymous @param sizeExpression expression to be used to calculate size, must not be null @return the builder instance, must not be null
[ "Add", "named", "integer", "array", "with", "size", "calculated", "through", "expression", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L1135-L1140
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/attributedefinition/attributes/AttributeVocabularyValueUrl.java
AttributeVocabularyValueUrl.deleteAttributeVocabularyValueLocalizedContentUrl
public static MozuUrl deleteAttributeVocabularyValueLocalizedContentUrl(String attributeFQN, String localeCode, String value) { """ Get Resource Url for DeleteAttributeVocabularyValueLocalizedContent @param attributeFQN Fully qualified name for an attribute. @param localeCode The two character country code that sets the locale, such as US for United States. Sites, tenants, and catalogs use locale codes for localizing content, such as translated product text per supported country. @param value The value string to create. @return String Resource Url """ UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/VocabularyValues/{value}/LocalizedContent/{localeCode}"); formatter.formatUrl("attributeFQN", attributeFQN); formatter.formatUrl("localeCode", localeCode); formatter.formatUrl("value", value); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl deleteAttributeVocabularyValueLocalizedContentUrl(String attributeFQN, String localeCode, String value) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/VocabularyValues/{value}/LocalizedContent/{localeCode}"); formatter.formatUrl("attributeFQN", attributeFQN); formatter.formatUrl("localeCode", localeCode); formatter.formatUrl("value", value); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "deleteAttributeVocabularyValueLocalizedContentUrl", "(", "String", "attributeFQN", ",", "String", "localeCode", ",", "String", "value", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/catalog/admin/attributedefinition/attributes/{attributeFQN}/VocabularyValues/{value}/LocalizedContent/{localeCode}\"", ")", ";", "formatter", ".", "formatUrl", "(", "\"attributeFQN\"", ",", "attributeFQN", ")", ";", "formatter", ".", "formatUrl", "(", "\"localeCode\"", ",", "localeCode", ")", ";", "formatter", ".", "formatUrl", "(", "\"value\"", ",", "value", ")", ";", "return", "new", "MozuUrl", "(", "formatter", ".", "getResourceUrl", "(", ")", ",", "MozuUrl", ".", "UrlLocation", ".", "TENANT_POD", ")", ";", "}" ]
Get Resource Url for DeleteAttributeVocabularyValueLocalizedContent @param attributeFQN Fully qualified name for an attribute. @param localeCode The two character country code that sets the locale, such as US for United States. Sites, tenants, and catalogs use locale codes for localizing content, such as translated product text per supported country. @param value The value string to create. @return String Resource Url
[ "Get", "Resource", "Url", "for", "DeleteAttributeVocabularyValueLocalizedContent" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/attributedefinition/attributes/AttributeVocabularyValueUrl.java#L187-L194
Samsung/GearVRf
GVRf/Extensions/gvrf-physics/src/main/java/org/gearvrf/physics/GVRRigidBody.java
GVRRigidBody.applyCentralImpulse
public void applyCentralImpulse(final float x, final float y, final float z) { """ Apply a central vector vector [X, Y, Z] to this {@linkplain GVRRigidBody rigid body} @param x impulse factor on the 'X' axis. @param y impulse factor on the 'Y' axis. @param z impulse factor on the 'Z' axis. """ mPhysicsContext.runOnPhysicsThread(new Runnable() { @Override public void run() { Native3DRigidBody.applyCentralImpulse(getNative(), x, y, z); } }); }
java
public void applyCentralImpulse(final float x, final float y, final float z) { mPhysicsContext.runOnPhysicsThread(new Runnable() { @Override public void run() { Native3DRigidBody.applyCentralImpulse(getNative(), x, y, z); } }); }
[ "public", "void", "applyCentralImpulse", "(", "final", "float", "x", ",", "final", "float", "y", ",", "final", "float", "z", ")", "{", "mPhysicsContext", ".", "runOnPhysicsThread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "Native3DRigidBody", ".", "applyCentralImpulse", "(", "getNative", "(", ")", ",", "x", ",", "y", ",", "z", ")", ";", "}", "}", ")", ";", "}" ]
Apply a central vector vector [X, Y, Z] to this {@linkplain GVRRigidBody rigid body} @param x impulse factor on the 'X' axis. @param y impulse factor on the 'Y' axis. @param z impulse factor on the 'Z' axis.
[ "Apply", "a", "central", "vector", "vector", "[", "X", "Y", "Z", "]", "to", "this", "{", "@linkplain", "GVRRigidBody", "rigid", "body", "}" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/gvrf-physics/src/main/java/org/gearvrf/physics/GVRRigidBody.java#L217-L224
liferay/com-liferay-commerce
commerce-wish-list-service/src/main/java/com/liferay/commerce/wish/list/service/persistence/impl/CommerceWishListItemPersistenceImpl.java
CommerceWishListItemPersistenceImpl.removeByCW_CP
@Override public void removeByCW_CP(long commerceWishListId, long CProductId) { """ Removes all the commerce wish list items where commerceWishListId = &#63; and CProductId = &#63; from the database. @param commerceWishListId the commerce wish list ID @param CProductId the c product ID """ for (CommerceWishListItem commerceWishListItem : findByCW_CP( commerceWishListId, CProductId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceWishListItem); } }
java
@Override public void removeByCW_CP(long commerceWishListId, long CProductId) { for (CommerceWishListItem commerceWishListItem : findByCW_CP( commerceWishListId, CProductId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceWishListItem); } }
[ "@", "Override", "public", "void", "removeByCW_CP", "(", "long", "commerceWishListId", ",", "long", "CProductId", ")", "{", "for", "(", "CommerceWishListItem", "commerceWishListItem", ":", "findByCW_CP", "(", "commerceWishListId", ",", "CProductId", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ")", "{", "remove", "(", "commerceWishListItem", ")", ";", "}", "}" ]
Removes all the commerce wish list items where commerceWishListId = &#63; and CProductId = &#63; from the database. @param commerceWishListId the commerce wish list ID @param CProductId the c product ID
[ "Removes", "all", "the", "commerce", "wish", "list", "items", "where", "commerceWishListId", "=", "&#63", ";", "and", "CProductId", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-wish-list-service/src/main/java/com/liferay/commerce/wish/list/service/persistence/impl/CommerceWishListItemPersistenceImpl.java#L2797-L2804
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPRuleAssetCategoryRelPersistenceImpl.java
CPRuleAssetCategoryRelPersistenceImpl.findByCPRuleId
@Override public List<CPRuleAssetCategoryRel> findByCPRuleId(long CPRuleId, int start, int end) { """ Returns a range of all the cp rule asset category rels where CPRuleId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPRuleAssetCategoryRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param CPRuleId the cp rule ID @param start the lower bound of the range of cp rule asset category rels @param end the upper bound of the range of cp rule asset category rels (not inclusive) @return the range of matching cp rule asset category rels """ return findByCPRuleId(CPRuleId, start, end, null); }
java
@Override public List<CPRuleAssetCategoryRel> findByCPRuleId(long CPRuleId, int start, int end) { return findByCPRuleId(CPRuleId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CPRuleAssetCategoryRel", ">", "findByCPRuleId", "(", "long", "CPRuleId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByCPRuleId", "(", "CPRuleId", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the cp rule asset category rels where CPRuleId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPRuleAssetCategoryRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param CPRuleId the cp rule ID @param start the lower bound of the range of cp rule asset category rels @param end the upper bound of the range of cp rule asset category rels (not inclusive) @return the range of matching cp rule asset category rels
[ "Returns", "a", "range", "of", "all", "the", "cp", "rule", "asset", "category", "rels", "where", "CPRuleId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPRuleAssetCategoryRelPersistenceImpl.java#L140-L144
dihedron/dihedron-commons
src/main/java/org/dihedron/core/streams/Streams.java
Streams.copy
public static long copy(InputStream input, OutputStream output) throws IOException { """ Copies all the bytes it can read from the input stream into the output stream; input and output streams management (opening, flushing, closing) are all up to the caller. @param input an open and ready-to-be-read input stream. @param output an open output stream. @return the total number of bytes copied. @throws IOException """ return copy(input, output, false); }
java
public static long copy(InputStream input, OutputStream output) throws IOException { return copy(input, output, false); }
[ "public", "static", "long", "copy", "(", "InputStream", "input", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "return", "copy", "(", "input", ",", "output", ",", "false", ")", ";", "}" ]
Copies all the bytes it can read from the input stream into the output stream; input and output streams management (opening, flushing, closing) are all up to the caller. @param input an open and ready-to-be-read input stream. @param output an open output stream. @return the total number of bytes copied. @throws IOException
[ "Copies", "all", "the", "bytes", "it", "can", "read", "from", "the", "input", "stream", "into", "the", "output", "stream", ";", "input", "and", "output", "streams", "management", "(", "opening", "flushing", "closing", ")", "are", "all", "up", "to", "the", "caller", "." ]
train
https://github.com/dihedron/dihedron-commons/blob/a5194cdaa0d6417ef4aade6ea407a1cad6e8458e/src/main/java/org/dihedron/core/streams/Streams.java#L56-L58
ggrandes/kvstore
src/main/java/org/javastack/kvstore/structures/hash/IntHashMap.java
IntHashMap.put
public V put(final int key, final V value) { """ Maps the specified key to the specified value. @param key the key. @param value the value. @return the value of any previous mapping with the specified key or {@code null} if there was no such mapping. """ int index = (key & 0x7FFFFFFF) % elementData.length; IntEntry<V> entry = elementData[index]; while (entry != null && key != entry.key) { entry = entry.nextInSlot; } if (entry == null) { if (++elementCount > threshold) { rehash(); index = (key & 0x7FFFFFFF) % elementData.length; } entry = createHashedEntry(key, index); } V result = entry.value; entry.value = value; return result; }
java
public V put(final int key, final V value) { int index = (key & 0x7FFFFFFF) % elementData.length; IntEntry<V> entry = elementData[index]; while (entry != null && key != entry.key) { entry = entry.nextInSlot; } if (entry == null) { if (++elementCount > threshold) { rehash(); index = (key & 0x7FFFFFFF) % elementData.length; } entry = createHashedEntry(key, index); } V result = entry.value; entry.value = value; return result; }
[ "public", "V", "put", "(", "final", "int", "key", ",", "final", "V", "value", ")", "{", "int", "index", "=", "(", "key", "&", "0x7FFFFFFF", ")", "%", "elementData", ".", "length", ";", "IntEntry", "<", "V", ">", "entry", "=", "elementData", "[", "index", "]", ";", "while", "(", "entry", "!=", "null", "&&", "key", "!=", "entry", ".", "key", ")", "{", "entry", "=", "entry", ".", "nextInSlot", ";", "}", "if", "(", "entry", "==", "null", ")", "{", "if", "(", "++", "elementCount", ">", "threshold", ")", "{", "rehash", "(", ")", ";", "index", "=", "(", "key", "&", "0x7FFFFFFF", ")", "%", "elementData", ".", "length", ";", "}", "entry", "=", "createHashedEntry", "(", "key", ",", "index", ")", ";", "}", "V", "result", "=", "entry", ".", "value", ";", "entry", ".", "value", "=", "value", ";", "return", "result", ";", "}" ]
Maps the specified key to the specified value. @param key the key. @param value the value. @return the value of any previous mapping with the specified key or {@code null} if there was no such mapping.
[ "Maps", "the", "specified", "key", "to", "the", "specified", "value", "." ]
train
https://github.com/ggrandes/kvstore/blob/c79277f79f4604e0fec8349a98519838e3de38f0/src/main/java/org/javastack/kvstore/structures/hash/IntHashMap.java#L152-L171
ReactiveX/RxJavaAsyncUtil
src/main/java/rx/util/async/Async.java
Async.forEachFuture
public static <T> FutureTask<Void> forEachFuture( Observable<? extends T> source, Action1<? super T> onNext) { """ Subscribes to the given source and calls the callback for each emitted item, and surfaces the completion or error through a Future. <p> <em>Important note:</em> The returned task blocks indefinitely unless the {@code run()} method is called or the task is scheduled on an Executor. <p> <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/forEachFuture.png" alt=""> @param <T> the source value type @param source the source Observable @param onNext the action to call with each emitted element @return the Future representing the entire for-each operation @see #forEachFuture(rx.Observable, rx.functions.Action1, rx.Scheduler) @see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-foreachfuture">RxJava Wiki: forEachFuture()</a> """ return OperatorForEachFuture.forEachFuture(source, onNext); }
java
public static <T> FutureTask<Void> forEachFuture( Observable<? extends T> source, Action1<? super T> onNext) { return OperatorForEachFuture.forEachFuture(source, onNext); }
[ "public", "static", "<", "T", ">", "FutureTask", "<", "Void", ">", "forEachFuture", "(", "Observable", "<", "?", "extends", "T", ">", "source", ",", "Action1", "<", "?", "super", "T", ">", "onNext", ")", "{", "return", "OperatorForEachFuture", ".", "forEachFuture", "(", "source", ",", "onNext", ")", ";", "}" ]
Subscribes to the given source and calls the callback for each emitted item, and surfaces the completion or error through a Future. <p> <em>Important note:</em> The returned task blocks indefinitely unless the {@code run()} method is called or the task is scheduled on an Executor. <p> <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/forEachFuture.png" alt=""> @param <T> the source value type @param source the source Observable @param onNext the action to call with each emitted element @return the Future representing the entire for-each operation @see #forEachFuture(rx.Observable, rx.functions.Action1, rx.Scheduler) @see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-foreachfuture">RxJava Wiki: forEachFuture()</a>
[ "Subscribes", "to", "the", "given", "source", "and", "calls", "the", "callback", "for", "each", "emitted", "item", "and", "surfaces", "the", "completion", "or", "error", "through", "a", "Future", ".", "<p", ">", "<em", ">", "Important", "note", ":", "<", "/", "em", ">", "The", "returned", "task", "blocks", "indefinitely", "unless", "the", "{", "@code", "run", "()", "}", "method", "is", "called", "or", "the", "task", "is", "scheduled", "on", "an", "Executor", ".", "<p", ">", "<img", "width", "=", "640", "src", "=", "https", ":", "//", "raw", ".", "github", ".", "com", "/", "wiki", "/", "ReactiveX", "/", "RxJava", "/", "images", "/", "rx", "-", "operators", "/", "forEachFuture", ".", "png", "alt", "=", ">" ]
train
https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L1838-L1842
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/ServerBlobAuditingPoliciesInner.java
ServerBlobAuditingPoliciesInner.beginCreateOrUpdate
public ServerBlobAuditingPolicyInner beginCreateOrUpdate(String resourceGroupName, String serverName, ServerBlobAuditingPolicyInner parameters) { """ Creates or updates a server's blob auditing policy. @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 Properties of blob auditing policy @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 ServerBlobAuditingPolicyInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).toBlocking().single().body(); }
java
public ServerBlobAuditingPolicyInner beginCreateOrUpdate(String resourceGroupName, String serverName, ServerBlobAuditingPolicyInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).toBlocking().single().body(); }
[ "public", "ServerBlobAuditingPolicyInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "ServerBlobAuditingPolicyInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates a server's blob auditing policy. @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 Properties of blob auditing policy @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 ServerBlobAuditingPolicyInner object if successful.
[ "Creates", "or", "updates", "a", "server", "s", "blob", "auditing", "policy", "." ]
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/ServerBlobAuditingPoliciesInner.java#L247-L249
terrestris/shogun-core
src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/HttpProxyService.java
HttpProxyService.buildUriWithParameters
private URL buildUriWithParameters(URL url, Map<String, String> params) throws URISyntaxException, MalformedURLException { """ Helper method to build an {@link URL} from a baseUri and request parameters @param url Base {@link URL} @param params request parameters @return URI """ if (params == null || params.isEmpty()) { return url; } URIBuilder uriBuilder = new URIBuilder(url.toURI()); for (String paramName : params.keySet()) { uriBuilder.addParameter(paramName, params.get(paramName)); } return uriBuilder.build().toURL(); }
java
private URL buildUriWithParameters(URL url, Map<String, String> params) throws URISyntaxException, MalformedURLException { if (params == null || params.isEmpty()) { return url; } URIBuilder uriBuilder = new URIBuilder(url.toURI()); for (String paramName : params.keySet()) { uriBuilder.addParameter(paramName, params.get(paramName)); } return uriBuilder.build().toURL(); }
[ "private", "URL", "buildUriWithParameters", "(", "URL", "url", ",", "Map", "<", "String", ",", "String", ">", "params", ")", "throws", "URISyntaxException", ",", "MalformedURLException", "{", "if", "(", "params", "==", "null", "||", "params", ".", "isEmpty", "(", ")", ")", "{", "return", "url", ";", "}", "URIBuilder", "uriBuilder", "=", "new", "URIBuilder", "(", "url", ".", "toURI", "(", ")", ")", ";", "for", "(", "String", "paramName", ":", "params", ".", "keySet", "(", ")", ")", "{", "uriBuilder", ".", "addParameter", "(", "paramName", ",", "params", ".", "get", "(", "paramName", ")", ")", ";", "}", "return", "uriBuilder", ".", "build", "(", ")", ".", "toURL", "(", ")", ";", "}" ]
Helper method to build an {@link URL} from a baseUri and request parameters @param url Base {@link URL} @param params request parameters @return URI
[ "Helper", "method", "to", "build", "an", "{", "@link", "URL", "}", "from", "a", "baseUri", "and", "request", "parameters" ]
train
https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/HttpProxyService.java#L300-L309
jMotif/GI
src/main/java/net/seninp/gi/rulepruner/RulePruningAlgorithm.java
RulePruningAlgorithm.isCompletelyCoveredBy
private boolean isCompletelyCoveredBy(int[] isCovered, List<RuleInterval> intervals) { """ Checks if the cover is complete. @param isCovered the cover. @param intervals set of rule intervals. @return true if the set complete. """ for (RuleInterval i : intervals) { for (int j = i.getStart(); j < i.getEnd(); j++) { if (isCovered[j] == 0) { return false; } } } return true; }
java
private boolean isCompletelyCoveredBy(int[] isCovered, List<RuleInterval> intervals) { for (RuleInterval i : intervals) { for (int j = i.getStart(); j < i.getEnd(); j++) { if (isCovered[j] == 0) { return false; } } } return true; }
[ "private", "boolean", "isCompletelyCoveredBy", "(", "int", "[", "]", "isCovered", ",", "List", "<", "RuleInterval", ">", "intervals", ")", "{", "for", "(", "RuleInterval", "i", ":", "intervals", ")", "{", "for", "(", "int", "j", "=", "i", ".", "getStart", "(", ")", ";", "j", "<", "i", ".", "getEnd", "(", ")", ";", "j", "++", ")", "{", "if", "(", "isCovered", "[", "j", "]", "==", "0", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Checks if the cover is complete. @param isCovered the cover. @param intervals set of rule intervals. @return true if the set complete.
[ "Checks", "if", "the", "cover", "is", "complete", "." ]
train
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/rulepruner/RulePruningAlgorithm.java#L207-L216
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java
Utils.logException
public static void logException( Logger logger, Level logLevel, Throwable t, String message ) { """ Logs an exception with the given logger and the given level. <p> Writing a stack trace may be time-consuming in some environments. To prevent useless computing, this method checks the current log level before trying to log anything. </p> @param logger the logger @param t an exception or a throwable @param logLevel the log level (see {@link Level}) @param message a message to insert before the stack trace """ if( logger.isLoggable( logLevel )) { StringBuilder sb = new StringBuilder(); if( message != null ) { sb.append( message ); sb.append( "\n" ); } sb.append( writeExceptionButDoNotUseItForLogging( t )); logger.log( logLevel, sb.toString()); } }
java
public static void logException( Logger logger, Level logLevel, Throwable t, String message ) { if( logger.isLoggable( logLevel )) { StringBuilder sb = new StringBuilder(); if( message != null ) { sb.append( message ); sb.append( "\n" ); } sb.append( writeExceptionButDoNotUseItForLogging( t )); logger.log( logLevel, sb.toString()); } }
[ "public", "static", "void", "logException", "(", "Logger", "logger", ",", "Level", "logLevel", ",", "Throwable", "t", ",", "String", "message", ")", "{", "if", "(", "logger", ".", "isLoggable", "(", "logLevel", ")", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "message", "!=", "null", ")", "{", "sb", ".", "append", "(", "message", ")", ";", "sb", ".", "append", "(", "\"\\n\"", ")", ";", "}", "sb", ".", "append", "(", "writeExceptionButDoNotUseItForLogging", "(", "t", ")", ")", ";", "logger", ".", "log", "(", "logLevel", ",", "sb", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Logs an exception with the given logger and the given level. <p> Writing a stack trace may be time-consuming in some environments. To prevent useless computing, this method checks the current log level before trying to log anything. </p> @param logger the logger @param t an exception or a throwable @param logLevel the log level (see {@link Level}) @param message a message to insert before the stack trace
[ "Logs", "an", "exception", "with", "the", "given", "logger", "and", "the", "given", "level", ".", "<p", ">", "Writing", "a", "stack", "trace", "may", "be", "time", "-", "consuming", "in", "some", "environments", ".", "To", "prevent", "useless", "computing", "this", "method", "checks", "the", "current", "log", "level", "before", "trying", "to", "log", "anything", ".", "<", "/", "p", ">" ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L1099-L1111
apache/flink
flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java
Configuration.getLong
public long getLong(String name, long defaultValue) { """ Get the value of the <code>name</code> property as a <code>long</code>. If no such property exists, the provided default value is returned, or if the specified value is not a valid <code>long</code>, then an error is thrown. @param name property name. @param defaultValue default value. @throws NumberFormatException when the value is invalid @return property value as a <code>long</code>, or <code>defaultValue</code>. """ String valueString = getTrimmed(name); if (valueString == null) return defaultValue; String hexString = getHexDigits(valueString); if (hexString != null) { return Long.parseLong(hexString, 16); } return Long.parseLong(valueString); }
java
public long getLong(String name, long defaultValue) { String valueString = getTrimmed(name); if (valueString == null) return defaultValue; String hexString = getHexDigits(valueString); if (hexString != null) { return Long.parseLong(hexString, 16); } return Long.parseLong(valueString); }
[ "public", "long", "getLong", "(", "String", "name", ",", "long", "defaultValue", ")", "{", "String", "valueString", "=", "getTrimmed", "(", "name", ")", ";", "if", "(", "valueString", "==", "null", ")", "return", "defaultValue", ";", "String", "hexString", "=", "getHexDigits", "(", "valueString", ")", ";", "if", "(", "hexString", "!=", "null", ")", "{", "return", "Long", ".", "parseLong", "(", "hexString", ",", "16", ")", ";", "}", "return", "Long", ".", "parseLong", "(", "valueString", ")", ";", "}" ]
Get the value of the <code>name</code> property as a <code>long</code>. If no such property exists, the provided default value is returned, or if the specified value is not a valid <code>long</code>, then an error is thrown. @param name property name. @param defaultValue default value. @throws NumberFormatException when the value is invalid @return property value as a <code>long</code>, or <code>defaultValue</code>.
[ "Get", "the", "value", "of", "the", "<code", ">", "name<", "/", "code", ">", "property", "as", "a", "<code", ">", "long<", "/", "code", ">", ".", "If", "no", "such", "property", "exists", "the", "provided", "default", "value", "is", "returned", "or", "if", "the", "specified", "value", "is", "not", "a", "valid", "<code", ">", "long<", "/", "code", ">", "then", "an", "error", "is", "thrown", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java#L1406-L1415
alkacon/opencms-core
src/org/opencms/repository/CmsRepositoryManager.java
CmsRepositoryManager.getRepository
@SuppressWarnings("unchecked") public <REPO extends I_CmsRepository> REPO getRepository(String name, Class<REPO> cls) { """ Gets a repository by name, but only if its class is a subclass of the class passed as a parameter.<p> Otherwise, null will be returned.<p> @param name the repository name @param cls the class used to filter repositories @return the repository with the given name, or null """ I_CmsRepository repo = getRepository(name); if (repo == null) { return null; } if (cls.isInstance(repo)) { return (REPO)repo; } else { return null; } }
java
@SuppressWarnings("unchecked") public <REPO extends I_CmsRepository> REPO getRepository(String name, Class<REPO> cls) { I_CmsRepository repo = getRepository(name); if (repo == null) { return null; } if (cls.isInstance(repo)) { return (REPO)repo; } else { return null; } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "REPO", "extends", "I_CmsRepository", ">", "REPO", "getRepository", "(", "String", "name", ",", "Class", "<", "REPO", ">", "cls", ")", "{", "I_CmsRepository", "repo", "=", "getRepository", "(", "name", ")", ";", "if", "(", "repo", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "cls", ".", "isInstance", "(", "repo", ")", ")", "{", "return", "(", "REPO", ")", "repo", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Gets a repository by name, but only if its class is a subclass of the class passed as a parameter.<p> Otherwise, null will be returned.<p> @param name the repository name @param cls the class used to filter repositories @return the repository with the given name, or null
[ "Gets", "a", "repository", "by", "name", "but", "only", "if", "its", "class", "is", "a", "subclass", "of", "the", "class", "passed", "as", "a", "parameter", ".", "<p", ">", "Otherwise", "null", "will", "be", "returned", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/repository/CmsRepositoryManager.java#L272-L285
moparisthebest/beehive
beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBean.java
ControlBean.lookupControlBeanContextFactory
private ControlBeanContextFactory lookupControlBeanContextFactory (org.apache.beehive.controls.api.context.ControlBeanContext context) { """ Internal method used to lookup a ControlBeanContextFactory. This factory is used to create the ControlBeanContext object for this ControlBean. The factory is discoverable from either the containing ControlBeanContext object or from the environment. If the containing CBC object exposes a contextual service of type {@link ControlBeanContextFactory}, the factory returned from this will be used to create a ControlBeanContext object. @param context @return the ControlBeanContextFactory discovered in the environment or a default one if no factory is configured """ // first, try to find the CBCFactory from the container if(context != null) { ControlBeanContextFactory cbcFactory = context.getService(ControlBeanContextFactory.class, null); if(cbcFactory != null) { return cbcFactory; } } // Create the context that acts as the BeanContextProxy for this bean (the context that this bean _defines_). try { DiscoverClass discoverer = new DiscoverClass(); Class factoryClass = discoverer.find(ControlBeanContextFactory.class, DefaultControlBeanContextFactory.class.getName()); return (ControlBeanContextFactory)factoryClass.newInstance(); } catch (Exception e) { throw new ControlException("Exception creating ControlBeanContext", e); } }
java
private ControlBeanContextFactory lookupControlBeanContextFactory (org.apache.beehive.controls.api.context.ControlBeanContext context) { // first, try to find the CBCFactory from the container if(context != null) { ControlBeanContextFactory cbcFactory = context.getService(ControlBeanContextFactory.class, null); if(cbcFactory != null) { return cbcFactory; } } // Create the context that acts as the BeanContextProxy for this bean (the context that this bean _defines_). try { DiscoverClass discoverer = new DiscoverClass(); Class factoryClass = discoverer.find(ControlBeanContextFactory.class, DefaultControlBeanContextFactory.class.getName()); return (ControlBeanContextFactory)factoryClass.newInstance(); } catch (Exception e) { throw new ControlException("Exception creating ControlBeanContext", e); } }
[ "private", "ControlBeanContextFactory", "lookupControlBeanContextFactory", "(", "org", ".", "apache", ".", "beehive", ".", "controls", ".", "api", ".", "context", ".", "ControlBeanContext", "context", ")", "{", "// first, try to find the CBCFactory from the container", "if", "(", "context", "!=", "null", ")", "{", "ControlBeanContextFactory", "cbcFactory", "=", "context", ".", "getService", "(", "ControlBeanContextFactory", ".", "class", ",", "null", ")", ";", "if", "(", "cbcFactory", "!=", "null", ")", "{", "return", "cbcFactory", ";", "}", "}", "// Create the context that acts as the BeanContextProxy for this bean (the context that this bean _defines_).", "try", "{", "DiscoverClass", "discoverer", "=", "new", "DiscoverClass", "(", ")", ";", "Class", "factoryClass", "=", "discoverer", ".", "find", "(", "ControlBeanContextFactory", ".", "class", ",", "DefaultControlBeanContextFactory", ".", "class", ".", "getName", "(", ")", ")", ";", "return", "(", "ControlBeanContextFactory", ")", "factoryClass", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "ControlException", "(", "\"Exception creating ControlBeanContext\"", ",", "e", ")", ";", "}", "}" ]
Internal method used to lookup a ControlBeanContextFactory. This factory is used to create the ControlBeanContext object for this ControlBean. The factory is discoverable from either the containing ControlBeanContext object or from the environment. If the containing CBC object exposes a contextual service of type {@link ControlBeanContextFactory}, the factory returned from this will be used to create a ControlBeanContext object. @param context @return the ControlBeanContextFactory discovered in the environment or a default one if no factory is configured
[ "Internal", "method", "used", "to", "lookup", "a", "ControlBeanContextFactory", ".", "This", "factory", "is", "used", "to", "create", "the", "ControlBeanContext", "object", "for", "this", "ControlBean", ".", "The", "factory", "is", "discoverable", "from", "either", "the", "containing", "ControlBeanContext", "object", "or", "from", "the", "environment", ".", "If", "the", "containing", "CBC", "object", "exposes", "a", "contextual", "service", "of", "type", "{", "@link", "ControlBeanContextFactory", "}", "the", "factory", "returned", "from", "this", "will", "be", "used", "to", "create", "a", "ControlBeanContext", "object", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBean.java#L934-L958
Wadpam/guja
guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java
GeneratedDContactDaoImpl.queryByTags
public Iterable<DContact> queryByTags(Object parent, java.lang.Object tags) { """ query-by method for field tags @param tags the specified attribute @return an Iterable of DContacts for the specified tags """ return queryByField(parent, DContactMapper.Field.TAGS.getFieldName(), tags); }
java
public Iterable<DContact> queryByTags(Object parent, java.lang.Object tags) { return queryByField(parent, DContactMapper.Field.TAGS.getFieldName(), tags); }
[ "public", "Iterable", "<", "DContact", ">", "queryByTags", "(", "Object", "parent", ",", "java", ".", "lang", ".", "Object", "tags", ")", "{", "return", "queryByField", "(", "parent", ",", "DContactMapper", ".", "Field", ".", "TAGS", ".", "getFieldName", "(", ")", ",", "tags", ")", ";", "}" ]
query-by method for field tags @param tags the specified attribute @return an Iterable of DContacts for the specified tags
[ "query", "-", "by", "method", "for", "field", "tags" ]
train
https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java#L268-L270
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAvailabilityEstimatePersistenceImpl.java
CommerceAvailabilityEstimatePersistenceImpl.findAll
@Override public List<CommerceAvailabilityEstimate> findAll() { """ Returns all the commerce availability estimates. @return the commerce availability estimates """ return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
@Override public List<CommerceAvailabilityEstimate> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
[ "@", "Override", "public", "List", "<", "CommerceAvailabilityEstimate", ">", "findAll", "(", ")", "{", "return", "findAll", "(", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ";", "}" ]
Returns all the commerce availability estimates. @return the commerce availability estimates
[ "Returns", "all", "the", "commerce", "availability", "estimates", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAvailabilityEstimatePersistenceImpl.java#L2678-L2681
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/cp/internal/raft/impl/RaftNodeImpl.java
RaftNodeImpl.runQueryOperation
public void runQueryOperation(Object operation, SimpleCompletableFuture resultFuture) { """ Executes query operation sets execution result to the future. """ long commitIndex = state.commitIndex(); Object result = raftIntegration.runOperation(operation, commitIndex); resultFuture.setResult(result); }
java
public void runQueryOperation(Object operation, SimpleCompletableFuture resultFuture) { long commitIndex = state.commitIndex(); Object result = raftIntegration.runOperation(operation, commitIndex); resultFuture.setResult(result); }
[ "public", "void", "runQueryOperation", "(", "Object", "operation", ",", "SimpleCompletableFuture", "resultFuture", ")", "{", "long", "commitIndex", "=", "state", ".", "commitIndex", "(", ")", ";", "Object", "result", "=", "raftIntegration", ".", "runOperation", "(", "operation", ",", "commitIndex", ")", ";", "resultFuture", ".", "setResult", "(", "result", ")", ";", "}" ]
Executes query operation sets execution result to the future.
[ "Executes", "query", "operation", "sets", "execution", "result", "to", "the", "future", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cp/internal/raft/impl/RaftNodeImpl.java#L639-L643
apereo/cas
support/cas-server-support-ws-sts-api/src/main/java/org/apereo/cas/authentication/SecurityTokenServiceClient.java
SecurityTokenServiceClient.requestSecurityTokenResponse
public Element requestSecurityTokenResponse(final String appliesTo) throws Exception { """ Request security token response element. @param appliesTo the applies to @return the element @throws Exception the exception """ val action = isSecureConv ? namespace + "/RST/SCT" : null; return requestSecurityTokenResponse(appliesTo, action, "/Issue", null); }
java
public Element requestSecurityTokenResponse(final String appliesTo) throws Exception { val action = isSecureConv ? namespace + "/RST/SCT" : null; return requestSecurityTokenResponse(appliesTo, action, "/Issue", null); }
[ "public", "Element", "requestSecurityTokenResponse", "(", "final", "String", "appliesTo", ")", "throws", "Exception", "{", "val", "action", "=", "isSecureConv", "?", "namespace", "+", "\"/RST/SCT\"", ":", "null", ";", "return", "requestSecurityTokenResponse", "(", "appliesTo", ",", "action", ",", "\"/Issue\"", ",", "null", ")", ";", "}" ]
Request security token response element. @param appliesTo the applies to @return the element @throws Exception the exception
[ "Request", "security", "token", "response", "element", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-ws-sts-api/src/main/java/org/apereo/cas/authentication/SecurityTokenServiceClient.java#L27-L30
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/ExecArgList.java
ExecArgList.fromStrings
public static ExecArgList fromStrings(Predicate quoteDetect, String... args) { """ @return an ExecArgList from a list of strings, and a predicate to determine whether the argument needs to be quoted @param quoteDetect predicate @param args args """ return builder().args(args, quoteDetect).build(); }
java
public static ExecArgList fromStrings(Predicate quoteDetect, String... args) { return builder().args(args, quoteDetect).build(); }
[ "public", "static", "ExecArgList", "fromStrings", "(", "Predicate", "quoteDetect", ",", "String", "...", "args", ")", "{", "return", "builder", "(", ")", ".", "args", "(", "args", ",", "quoteDetect", ")", ".", "build", "(", ")", ";", "}" ]
@return an ExecArgList from a list of strings, and a predicate to determine whether the argument needs to be quoted @param quoteDetect predicate @param args args
[ "@return", "an", "ExecArgList", "from", "a", "list", "of", "strings", "and", "a", "predicate", "to", "determine", "whether", "the", "argument", "needs", "to", "be", "quoted" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/ExecArgList.java#L66-L68
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/util/Validate.java
Validate.noNullElements
public static void noNullElements(Collection<?> collection, String message) { """ <p>Validate that the specified argument collection is neither <code>null</code> nor contains any elements that are <code>null</code>; otherwise throwing an exception with the specified message. <pre>Validate.noNullElements(myCollection, "The collection contains null elements");</pre> <p>If the collection is <code>null</code>, then the message in the exception is &quot;The validated object is null&quot;.</p> @param collection the collection to check @param message the exception message if the collection has @throws IllegalArgumentException if the collection is <code>null</code> or an element in the collection is <code>null</code> """ Validate.notNull(collection); for (Object element : collection) { if (element == null) { throw new IllegalArgumentException(message); } } }
java
public static void noNullElements(Collection<?> collection, String message) { Validate.notNull(collection); for (Object element : collection) { if (element == null) { throw new IllegalArgumentException(message); } } }
[ "public", "static", "void", "noNullElements", "(", "Collection", "<", "?", ">", "collection", ",", "String", "message", ")", "{", "Validate", ".", "notNull", "(", "collection", ")", ";", "for", "(", "Object", "element", ":", "collection", ")", "{", "if", "(", "element", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "message", ")", ";", "}", "}", "}" ]
<p>Validate that the specified argument collection is neither <code>null</code> nor contains any elements that are <code>null</code>; otherwise throwing an exception with the specified message. <pre>Validate.noNullElements(myCollection, "The collection contains null elements");</pre> <p>If the collection is <code>null</code>, then the message in the exception is &quot;The validated object is null&quot;.</p> @param collection the collection to check @param message the exception message if the collection has @throws IllegalArgumentException if the collection is <code>null</code> or an element in the collection is <code>null</code>
[ "<p", ">", "Validate", "that", "the", "specified", "argument", "collection", "is", "neither", "<code", ">", "null<", "/", "code", ">", "nor", "contains", "any", "elements", "that", "are", "<code", ">", "null<", "/", "code", ">", ";", "otherwise", "throwing", "an", "exception", "with", "the", "specified", "message", "." ]
train
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/util/Validate.java#L415-L422
Quickhull3d/quickhull3d
src/main/java/com/github/quickhull3d/QuickHull3D.java
QuickHull3D.build
public void build(Point3d[] points, int nump) throws IllegalArgumentException { """ Constructs the convex hull of a set of points. @param points input points @param nump number of input points @throws IllegalArgumentException the number of input points is less than four or greater then the length of <code>points</code>, or the points appear to be coincident, colinear, or coplanar. """ if (nump < 4) { throw new IllegalArgumentException("Less than four input points specified"); } if (points.length < nump) { throw new IllegalArgumentException("Point array too small for specified number of points"); } initBuffers(nump); setPoints(points, nump); buildHull(); }
java
public void build(Point3d[] points, int nump) throws IllegalArgumentException { if (nump < 4) { throw new IllegalArgumentException("Less than four input points specified"); } if (points.length < nump) { throw new IllegalArgumentException("Point array too small for specified number of points"); } initBuffers(nump); setPoints(points, nump); buildHull(); }
[ "public", "void", "build", "(", "Point3d", "[", "]", "points", ",", "int", "nump", ")", "throws", "IllegalArgumentException", "{", "if", "(", "nump", "<", "4", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Less than four input points specified\"", ")", ";", "}", "if", "(", "points", ".", "length", "<", "nump", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Point array too small for specified number of points\"", ")", ";", "}", "initBuffers", "(", "nump", ")", ";", "setPoints", "(", "points", ",", "nump", ")", ";", "buildHull", "(", ")", ";", "}" ]
Constructs the convex hull of a set of points. @param points input points @param nump number of input points @throws IllegalArgumentException the number of input points is less than four or greater then the length of <code>points</code>, or the points appear to be coincident, colinear, or coplanar.
[ "Constructs", "the", "convex", "hull", "of", "a", "set", "of", "points", "." ]
train
https://github.com/Quickhull3d/quickhull3d/blob/3f80953b86c46385e84730e5d2a1745cbfa12703/src/main/java/com/github/quickhull3d/QuickHull3D.java#L499-L509
FXMisc/Flowless
src/main/java/org/fxmisc/flowless/CellPositioner.java
CellPositioner.placeStartAt
public C placeStartAt(int itemIndex, double startOffStart) { """ Properly resizes the cell's node, and sets its "layoutY" value, so that is the first visible node in the viewport, and further offsets this value by {@code startOffStart}, so that the node's <em>top</em> edge appears (if negative) "above," (if 0) "at," or (if negative) "below" the viewport's "top" edge. See {@link OrientationHelper}'s javadoc for more explanation on what quoted terms mean. <pre><code> --------- top of cell's node if startOffStart is negative __________ "top edge" of viewport / top of cell's node if startOffStart = 0 | | |--------- top of cell's node if startOffStart is positive | </code></pre> @param itemIndex the index of the item in the list of all (not currently visible) cells @param startOffStart the amount by which to offset the "layoutY" value of the cell's node """ C cell = getSizedCell(itemIndex); relocate(cell, 0, startOffStart); cell.getNode().setVisible(true); return cell; }
java
public C placeStartAt(int itemIndex, double startOffStart) { C cell = getSizedCell(itemIndex); relocate(cell, 0, startOffStart); cell.getNode().setVisible(true); return cell; }
[ "public", "C", "placeStartAt", "(", "int", "itemIndex", ",", "double", "startOffStart", ")", "{", "C", "cell", "=", "getSizedCell", "(", "itemIndex", ")", ";", "relocate", "(", "cell", ",", "0", ",", "startOffStart", ")", ";", "cell", ".", "getNode", "(", ")", ".", "setVisible", "(", "true", ")", ";", "return", "cell", ";", "}" ]
Properly resizes the cell's node, and sets its "layoutY" value, so that is the first visible node in the viewport, and further offsets this value by {@code startOffStart}, so that the node's <em>top</em> edge appears (if negative) "above," (if 0) "at," or (if negative) "below" the viewport's "top" edge. See {@link OrientationHelper}'s javadoc for more explanation on what quoted terms mean. <pre><code> --------- top of cell's node if startOffStart is negative __________ "top edge" of viewport / top of cell's node if startOffStart = 0 | | |--------- top of cell's node if startOffStart is positive | </code></pre> @param itemIndex the index of the item in the list of all (not currently visible) cells @param startOffStart the amount by which to offset the "layoutY" value of the cell's node
[ "Properly", "resizes", "the", "cell", "s", "node", "and", "sets", "its", "layoutY", "value", "so", "that", "is", "the", "first", "visible", "node", "in", "the", "viewport", "and", "further", "offsets", "this", "value", "by", "{", "@code", "startOffStart", "}", "so", "that", "the", "node", "s", "<em", ">", "top<", "/", "em", ">", "edge", "appears", "(", "if", "negative", ")", "above", "(", "if", "0", ")", "at", "or", "(", "if", "negative", ")", "below", "the", "viewport", "s", "top", "edge", ".", "See", "{", "@link", "OrientationHelper", "}", "s", "javadoc", "for", "more", "explanation", "on", "what", "quoted", "terms", "mean", "." ]
train
https://github.com/FXMisc/Flowless/blob/dce2269ebafed8f79203d00085af41f06f3083bc/src/main/java/org/fxmisc/flowless/CellPositioner.java#L126-L131
querydsl/querydsl
querydsl-sql/src/main/java/com/querydsl/sql/mysql/MySQLQueryFactory.java
MySQLQueryFactory.insertOnDuplicateKeyUpdate
public SQLInsertClause insertOnDuplicateKeyUpdate(RelationalPath<?> entity, Expression<?> clause) { """ Create a INSERT ... ON DUPLICATE KEY UPDATE clause @param entity table to insert to @param clause clause @return insert clause """ SQLInsertClause insert = insert(entity); insert.addFlag(Position.END, ExpressionUtils.template(String.class, " on duplicate key update {0}", clause)); return insert; }
java
public SQLInsertClause insertOnDuplicateKeyUpdate(RelationalPath<?> entity, Expression<?> clause) { SQLInsertClause insert = insert(entity); insert.addFlag(Position.END, ExpressionUtils.template(String.class, " on duplicate key update {0}", clause)); return insert; }
[ "public", "SQLInsertClause", "insertOnDuplicateKeyUpdate", "(", "RelationalPath", "<", "?", ">", "entity", ",", "Expression", "<", "?", ">", "clause", ")", "{", "SQLInsertClause", "insert", "=", "insert", "(", "entity", ")", ";", "insert", ".", "addFlag", "(", "Position", ".", "END", ",", "ExpressionUtils", ".", "template", "(", "String", ".", "class", ",", "\" on duplicate key update {0}\"", ",", "clause", ")", ")", ";", "return", "insert", ";", "}" ]
Create a INSERT ... ON DUPLICATE KEY UPDATE clause @param entity table to insert to @param clause clause @return insert clause
[ "Create", "a", "INSERT", "...", "ON", "DUPLICATE", "KEY", "UPDATE", "clause" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-sql/src/main/java/com/querydsl/sql/mysql/MySQLQueryFactory.java#L80-L84
nguillaumin/slick2d-maven
slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/DataSet.java
DataSet.toAngelCodeText
public void toAngelCodeText(PrintStream out, String imageName) { """ Output this data set as an angel code data file @param imageName The name of the image to reference @param out The output stream to write to """ out.println("info face=\""+fontName+"\" size="+size+" bold=0 italic=0 charset=\""+setName+"\" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1"); out.println("common lineHeight="+lineHeight+" base=26 scaleW="+width+" scaleH="+height+" pages=1 packed=0"); out.println("page id=0 file=\""+imageName+"\""); out.println("chars count="+chars.size()); for (int i=0;i<chars.size();i++) { CharData c = (CharData) chars.get(i); out.println("char id="+c.getID()+" x="+c.getX()+" y="+c.getY()+" width="+c.getWidth()+" height="+c.getHeight()+" xoffset=0 yoffset="+c.getYOffset()+" xadvance="+c.getXAdvance()+" page=0 chnl=0 "); } out.println("kernings count="+kerning.size()); for (int i=0;i<kerning.size();i++) { KerningData k = (KerningData) kerning.get(i); out.println("kerning first="+k.first+" second="+k.second+" amount="+k.offset); } }
java
public void toAngelCodeText(PrintStream out, String imageName) { out.println("info face=\""+fontName+"\" size="+size+" bold=0 italic=0 charset=\""+setName+"\" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1"); out.println("common lineHeight="+lineHeight+" base=26 scaleW="+width+" scaleH="+height+" pages=1 packed=0"); out.println("page id=0 file=\""+imageName+"\""); out.println("chars count="+chars.size()); for (int i=0;i<chars.size();i++) { CharData c = (CharData) chars.get(i); out.println("char id="+c.getID()+" x="+c.getX()+" y="+c.getY()+" width="+c.getWidth()+" height="+c.getHeight()+" xoffset=0 yoffset="+c.getYOffset()+" xadvance="+c.getXAdvance()+" page=0 chnl=0 "); } out.println("kernings count="+kerning.size()); for (int i=0;i<kerning.size();i++) { KerningData k = (KerningData) kerning.get(i); out.println("kerning first="+k.first+" second="+k.second+" amount="+k.offset); } }
[ "public", "void", "toAngelCodeText", "(", "PrintStream", "out", ",", "String", "imageName", ")", "{", "out", ".", "println", "(", "\"info face=\\\"\"", "+", "fontName", "+", "\"\\\" size=\"", "+", "size", "+", "\" bold=0 italic=0 charset=\\\"\"", "+", "setName", "+", "\"\\\" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1\"", ")", ";", "out", ".", "println", "(", "\"common lineHeight=\"", "+", "lineHeight", "+", "\" base=26 scaleW=\"", "+", "width", "+", "\" scaleH=\"", "+", "height", "+", "\" pages=1 packed=0\"", ")", ";", "out", ".", "println", "(", "\"page id=0 file=\\\"\"", "+", "imageName", "+", "\"\\\"\"", ")", ";", "out", ".", "println", "(", "\"chars count=\"", "+", "chars", ".", "size", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "chars", ".", "size", "(", ")", ";", "i", "++", ")", "{", "CharData", "c", "=", "(", "CharData", ")", "chars", ".", "get", "(", "i", ")", ";", "out", ".", "println", "(", "\"char id=\"", "+", "c", ".", "getID", "(", ")", "+", "\" x=\"", "+", "c", ".", "getX", "(", ")", "+", "\" y=\"", "+", "c", ".", "getY", "(", ")", "+", "\" width=\"", "+", "c", ".", "getWidth", "(", ")", "+", "\" height=\"", "+", "c", ".", "getHeight", "(", ")", "+", "\" xoffset=0 yoffset=\"", "+", "c", ".", "getYOffset", "(", ")", "+", "\" xadvance=\"", "+", "c", ".", "getXAdvance", "(", ")", "+", "\" page=0 chnl=0 \"", ")", ";", "}", "out", ".", "println", "(", "\"kernings count=\"", "+", "kerning", ".", "size", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "kerning", ".", "size", "(", ")", ";", "i", "++", ")", "{", "KerningData", "k", "=", "(", "KerningData", ")", "kerning", ".", "get", "(", "i", ")", ";", "out", ".", "println", "(", "\"kerning first=\"", "+", "k", ".", "first", "+", "\" second=\"", "+", "k", ".", "second", "+", "\" amount=\"", "+", "k", ".", "offset", ")", ";", "}", "}" ]
Output this data set as an angel code data file @param imageName The name of the image to reference @param out The output stream to write to
[ "Output", "this", "data", "set", "as", "an", "angel", "code", "data", "file" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/DataSet.java#L93-L108
apache/groovy
subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java
DateTimeExtensions.downto
public static void downto(Temporal from, Temporal to, Closure closure) { """ Iterates from this to the {@code to} {@link java.time.temporal.Temporal}, inclusive, decrementing by one unit each iteration, calling the closure once per iteration. The closure may accept a single {@link java.time.temporal.Temporal} argument. <p> The particular unit decremented by depends on the specific sub-type of {@link java.time.temporal.Temporal}. Most sub-types use a unit of {@link java.time.temporal.ChronoUnit#SECONDS} except for <ul> <li>{@link java.time.chrono.ChronoLocalDate} and its sub-types use {@link java.time.temporal.ChronoUnit#DAYS}. <li>{@link java.time.YearMonth} uses {@link java.time.temporal.ChronoUnit#MONTHS}. <li>{@link java.time.Year} uses {@link java.time.temporal.ChronoUnit#YEARS}. </ul> @param from the starting Temporal @param to the ending Temporal @param closure the zero or one-argument closure to call @throws GroovyRuntimeException if this value is earlier than {@code to} @throws GroovyRuntimeException if {@code to} is a different type than this @since 2.5.0 """ downto(from, to, defaultUnitFor(from), closure); }
java
public static void downto(Temporal from, Temporal to, Closure closure) { downto(from, to, defaultUnitFor(from), closure); }
[ "public", "static", "void", "downto", "(", "Temporal", "from", ",", "Temporal", "to", ",", "Closure", "closure", ")", "{", "downto", "(", "from", ",", "to", ",", "defaultUnitFor", "(", "from", ")", ",", "closure", ")", ";", "}" ]
Iterates from this to the {@code to} {@link java.time.temporal.Temporal}, inclusive, decrementing by one unit each iteration, calling the closure once per iteration. The closure may accept a single {@link java.time.temporal.Temporal} argument. <p> The particular unit decremented by depends on the specific sub-type of {@link java.time.temporal.Temporal}. Most sub-types use a unit of {@link java.time.temporal.ChronoUnit#SECONDS} except for <ul> <li>{@link java.time.chrono.ChronoLocalDate} and its sub-types use {@link java.time.temporal.ChronoUnit#DAYS}. <li>{@link java.time.YearMonth} uses {@link java.time.temporal.ChronoUnit#MONTHS}. <li>{@link java.time.Year} uses {@link java.time.temporal.ChronoUnit#YEARS}. </ul> @param from the starting Temporal @param to the ending Temporal @param closure the zero or one-argument closure to call @throws GroovyRuntimeException if this value is earlier than {@code to} @throws GroovyRuntimeException if {@code to} is a different type than this @since 2.5.0
[ "Iterates", "from", "this", "to", "the", "{", "@code", "to", "}", "{", "@link", "java", ".", "time", ".", "temporal", ".", "Temporal", "}", "inclusive", "decrementing", "by", "one", "unit", "each", "iteration", "calling", "the", "closure", "once", "per", "iteration", ".", "The", "closure", "may", "accept", "a", "single", "{", "@link", "java", ".", "time", ".", "temporal", ".", "Temporal", "}", "argument", ".", "<p", ">", "The", "particular", "unit", "decremented", "by", "depends", "on", "the", "specific", "sub", "-", "type", "of", "{", "@link", "java", ".", "time", ".", "temporal", ".", "Temporal", "}", ".", "Most", "sub", "-", "types", "use", "a", "unit", "of", "{", "@link", "java", ".", "time", ".", "temporal", ".", "ChronoUnit#SECONDS", "}", "except", "for", "<ul", ">", "<li", ">", "{", "@link", "java", ".", "time", ".", "chrono", ".", "ChronoLocalDate", "}", "and", "its", "sub", "-", "types", "use", "{", "@link", "java", ".", "time", ".", "temporal", ".", "ChronoUnit#DAYS", "}", ".", "<li", ">", "{", "@link", "java", ".", "time", ".", "YearMonth", "}", "uses", "{", "@link", "java", ".", "time", ".", "temporal", ".", "ChronoUnit#MONTHS", "}", ".", "<li", ">", "{", "@link", "java", ".", "time", ".", "Year", "}", "uses", "{", "@link", "java", ".", "time", ".", "temporal", ".", "ChronoUnit#YEARS", "}", ".", "<", "/", "ul", ">" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java#L201-L203
alkacon/opencms-core
src/org/opencms/jsp/search/result/CmsSearchStateParameters.java
CmsSearchStateParameters.paramMapToString
public static String paramMapToString(final Map<String, String[]> parameters) { """ Converts a parameter map to the parameter string. @param parameters the parameter map. @return the parameter string. """ final StringBuffer result = new StringBuffer(); for (final String key : parameters.keySet()) { String[] values = parameters.get(key); if (null == values) { result.append(key).append('&'); } else { for (final String value : parameters.get(key)) { result.append(key).append('=').append(CmsEncoder.encode(value)).append('&'); } } } // remove last '&' if (result.length() > 0) { result.setLength(result.length() - 1); } return result.toString(); }
java
public static String paramMapToString(final Map<String, String[]> parameters) { final StringBuffer result = new StringBuffer(); for (final String key : parameters.keySet()) { String[] values = parameters.get(key); if (null == values) { result.append(key).append('&'); } else { for (final String value : parameters.get(key)) { result.append(key).append('=').append(CmsEncoder.encode(value)).append('&'); } } } // remove last '&' if (result.length() > 0) { result.setLength(result.length() - 1); } return result.toString(); }
[ "public", "static", "String", "paramMapToString", "(", "final", "Map", "<", "String", ",", "String", "[", "]", ">", "parameters", ")", "{", "final", "StringBuffer", "result", "=", "new", "StringBuffer", "(", ")", ";", "for", "(", "final", "String", "key", ":", "parameters", ".", "keySet", "(", ")", ")", "{", "String", "[", "]", "values", "=", "parameters", ".", "get", "(", "key", ")", ";", "if", "(", "null", "==", "values", ")", "{", "result", ".", "append", "(", "key", ")", ".", "append", "(", "'", "'", ")", ";", "}", "else", "{", "for", "(", "final", "String", "value", ":", "parameters", ".", "get", "(", "key", ")", ")", "{", "result", ".", "append", "(", "key", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "CmsEncoder", ".", "encode", "(", "value", ")", ")", ".", "append", "(", "'", "'", ")", ";", "}", "}", "}", "// remove last '&'", "if", "(", "result", ".", "length", "(", ")", ">", "0", ")", "{", "result", ".", "setLength", "(", "result", ".", "length", "(", ")", "-", "1", ")", ";", "}", "return", "result", ".", "toString", "(", ")", ";", "}" ]
Converts a parameter map to the parameter string. @param parameters the parameter map. @return the parameter string.
[ "Converts", "a", "parameter", "map", "to", "the", "parameter", "string", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/search/result/CmsSearchStateParameters.java#L91-L109
mapsforge/mapsforge
mapsforge-map/src/main/java/org/mapsforge/map/util/LayerUtil.java
LayerUtil.getUpperLeft
public static Tile getUpperLeft(BoundingBox boundingBox, byte zoomLevel, int tileSize) { """ Upper left tile for an area. @param boundingBox the area boundingBox @param zoomLevel the zoom level. @param tileSize the tile size. @return the tile at the upper left of the bbox. """ int tileLeft = MercatorProjection.longitudeToTileX(boundingBox.minLongitude, zoomLevel); int tileTop = MercatorProjection.latitudeToTileY(boundingBox.maxLatitude, zoomLevel); return new Tile(tileLeft, tileTop, zoomLevel, tileSize); }
java
public static Tile getUpperLeft(BoundingBox boundingBox, byte zoomLevel, int tileSize) { int tileLeft = MercatorProjection.longitudeToTileX(boundingBox.minLongitude, zoomLevel); int tileTop = MercatorProjection.latitudeToTileY(boundingBox.maxLatitude, zoomLevel); return new Tile(tileLeft, tileTop, zoomLevel, tileSize); }
[ "public", "static", "Tile", "getUpperLeft", "(", "BoundingBox", "boundingBox", ",", "byte", "zoomLevel", ",", "int", "tileSize", ")", "{", "int", "tileLeft", "=", "MercatorProjection", ".", "longitudeToTileX", "(", "boundingBox", ".", "minLongitude", ",", "zoomLevel", ")", ";", "int", "tileTop", "=", "MercatorProjection", ".", "latitudeToTileY", "(", "boundingBox", ".", "maxLatitude", ",", "zoomLevel", ")", ";", "return", "new", "Tile", "(", "tileLeft", ",", "tileTop", ",", "zoomLevel", ",", "tileSize", ")", ";", "}" ]
Upper left tile for an area. @param boundingBox the area boundingBox @param zoomLevel the zoom level. @param tileSize the tile size. @return the tile at the upper left of the bbox.
[ "Upper", "left", "tile", "for", "an", "area", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/util/LayerUtil.java#L64-L68
rwl/CSparseJ
src/main/java/edu/emory/mathcs/csparsej/tdcomplex/DZcs_fkeep.java
DZcs_fkeep.cs_fkeep
public static int cs_fkeep(DZcs A, DZcs_ifkeep fkeep, Object other) { """ Drops entries from a sparse matrix; @param A column-compressed matrix @param fkeep drop aij if fkeep.fkeep(i,j,aij,other) is false @param other optional parameter to fkeep @return nz, new number of entries in A, -1 on error """ int j, p, nz = 0, n, Ap[], Ai[] ; DZcsa Ax = new DZcsa() ; if (!CS_CSC (A)) return (-1) ; /* check inputs */ n = A.n ; Ap = A.p ; Ai = A.i ; Ax.x = A.x ; for (j = 0 ; j < n ; j++) { p = Ap [j] ; /* get current location of col j */ Ap [j] = nz ; /* record new location of col j */ for ( ; p < Ap [j+1] ; p++) { if (fkeep.fkeep(Ai [p], j, Ax.x != null ? Ax.get(p) : cs_cone(), other)) { if (Ax.x != null) Ax.set(nz, Ax.get(p)); /* keep A(i,j) */ Ai [nz++] = Ai [p] ; } } } Ap [n] = nz ; /* finalize A */ cs_sprealloc (A, 0) ; /* remove extra space from A */ return (nz) ; }
java
public static int cs_fkeep(DZcs A, DZcs_ifkeep fkeep, Object other) { int j, p, nz = 0, n, Ap[], Ai[] ; DZcsa Ax = new DZcsa() ; if (!CS_CSC (A)) return (-1) ; /* check inputs */ n = A.n ; Ap = A.p ; Ai = A.i ; Ax.x = A.x ; for (j = 0 ; j < n ; j++) { p = Ap [j] ; /* get current location of col j */ Ap [j] = nz ; /* record new location of col j */ for ( ; p < Ap [j+1] ; p++) { if (fkeep.fkeep(Ai [p], j, Ax.x != null ? Ax.get(p) : cs_cone(), other)) { if (Ax.x != null) Ax.set(nz, Ax.get(p)); /* keep A(i,j) */ Ai [nz++] = Ai [p] ; } } } Ap [n] = nz ; /* finalize A */ cs_sprealloc (A, 0) ; /* remove extra space from A */ return (nz) ; }
[ "public", "static", "int", "cs_fkeep", "(", "DZcs", "A", ",", "DZcs_ifkeep", "fkeep", ",", "Object", "other", ")", "{", "int", "j", ",", "p", ",", "nz", "=", "0", ",", "n", ",", "Ap", "[", "]", ",", "Ai", "[", "]", ";", "DZcsa", "Ax", "=", "new", "DZcsa", "(", ")", ";", "if", "(", "!", "CS_CSC", "(", "A", ")", ")", "return", "(", "-", "1", ")", ";", "/* check inputs */", "n", "=", "A", ".", "n", ";", "Ap", "=", "A", ".", "p", ";", "Ai", "=", "A", ".", "i", ";", "Ax", ".", "x", "=", "A", ".", "x", ";", "for", "(", "j", "=", "0", ";", "j", "<", "n", ";", "j", "++", ")", "{", "p", "=", "Ap", "[", "j", "]", ";", "/* get current location of col j */", "Ap", "[", "j", "]", "=", "nz", ";", "/* record new location of col j */", "for", "(", ";", "p", "<", "Ap", "[", "j", "+", "1", "]", ";", "p", "++", ")", "{", "if", "(", "fkeep", ".", "fkeep", "(", "Ai", "[", "p", "]", ",", "j", ",", "Ax", ".", "x", "!=", "null", "?", "Ax", ".", "get", "(", "p", ")", ":", "cs_cone", "(", ")", ",", "other", ")", ")", "{", "if", "(", "Ax", ".", "x", "!=", "null", ")", "Ax", ".", "set", "(", "nz", ",", "Ax", ".", "get", "(", "p", ")", ")", ";", "/* keep A(i,j) */", "Ai", "[", "nz", "++", "]", "=", "Ai", "[", "p", "]", ";", "}", "}", "}", "Ap", "[", "n", "]", "=", "nz", ";", "/* finalize A */", "cs_sprealloc", "(", "A", ",", "0", ")", ";", "/* remove extra space from A */", "return", "(", "nz", ")", ";", "}" ]
Drops entries from a sparse matrix; @param A column-compressed matrix @param fkeep drop aij if fkeep.fkeep(i,j,aij,other) is false @param other optional parameter to fkeep @return nz, new number of entries in A, -1 on error
[ "Drops", "entries", "from", "a", "sparse", "matrix", ";" ]
train
https://github.com/rwl/CSparseJ/blob/6a6f66bccce1558156a961494358952603b0ac84/src/main/java/edu/emory/mathcs/csparsej/tdcomplex/DZcs_fkeep.java#L55-L77
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.readPropertyObject
public CmsProperty readPropertyObject( CmsDbContext dbc, CmsResource resource, String key, boolean search, Locale locale) throws CmsException { """ Reads a property object from a resource specified by a property name.<p> Returns <code>{@link CmsProperty#getNullProperty()}</code> if the property is not found.<p> @param dbc the current database context @param resource the resource where the property is read from @param key the property key name @param search if <code>true</code>, the property is searched on all parent folders of the resource. if it's not found attached directly to the resource. @param locale the locale for which the property should be read. @return the required property, or <code>{@link CmsProperty#getNullProperty()}</code> if the property was not found @throws CmsException if something goes wrong """ // use the list reading method to obtain all properties for the resource List<CmsProperty> properties = readPropertyObjects(dbc, resource, search); // create a lookup property object and look this up in the result map CmsProperty result = null; // handle the case without locale separately to improve performance for (String localizedKey : CmsLocaleManager.getLocaleVariants(key, locale, true, false)) { int i = properties.indexOf(new CmsProperty(localizedKey, null, null)); if (i >= 0) { // property has been found in the map result = properties.get(i); // ensure the result value is not frozen return result.cloneAsProperty(); } } return CmsProperty.getNullProperty(); }
java
public CmsProperty readPropertyObject( CmsDbContext dbc, CmsResource resource, String key, boolean search, Locale locale) throws CmsException { // use the list reading method to obtain all properties for the resource List<CmsProperty> properties = readPropertyObjects(dbc, resource, search); // create a lookup property object and look this up in the result map CmsProperty result = null; // handle the case without locale separately to improve performance for (String localizedKey : CmsLocaleManager.getLocaleVariants(key, locale, true, false)) { int i = properties.indexOf(new CmsProperty(localizedKey, null, null)); if (i >= 0) { // property has been found in the map result = properties.get(i); // ensure the result value is not frozen return result.cloneAsProperty(); } } return CmsProperty.getNullProperty(); }
[ "public", "CmsProperty", "readPropertyObject", "(", "CmsDbContext", "dbc", ",", "CmsResource", "resource", ",", "String", "key", ",", "boolean", "search", ",", "Locale", "locale", ")", "throws", "CmsException", "{", "// use the list reading method to obtain all properties for the resource", "List", "<", "CmsProperty", ">", "properties", "=", "readPropertyObjects", "(", "dbc", ",", "resource", ",", "search", ")", ";", "// create a lookup property object and look this up in the result map", "CmsProperty", "result", "=", "null", ";", "// handle the case without locale separately to improve performance", "for", "(", "String", "localizedKey", ":", "CmsLocaleManager", ".", "getLocaleVariants", "(", "key", ",", "locale", ",", "true", ",", "false", ")", ")", "{", "int", "i", "=", "properties", ".", "indexOf", "(", "new", "CmsProperty", "(", "localizedKey", ",", "null", ",", "null", ")", ")", ";", "if", "(", "i", ">=", "0", ")", "{", "// property has been found in the map", "result", "=", "properties", ".", "get", "(", "i", ")", ";", "// ensure the result value is not frozen", "return", "result", ".", "cloneAsProperty", "(", ")", ";", "}", "}", "return", "CmsProperty", ".", "getNullProperty", "(", ")", ";", "}" ]
Reads a property object from a resource specified by a property name.<p> Returns <code>{@link CmsProperty#getNullProperty()}</code> if the property is not found.<p> @param dbc the current database context @param resource the resource where the property is read from @param key the property key name @param search if <code>true</code>, the property is searched on all parent folders of the resource. if it's not found attached directly to the resource. @param locale the locale for which the property should be read. @return the required property, or <code>{@link CmsProperty#getNullProperty()}</code> if the property was not found @throws CmsException if something goes wrong
[ "Reads", "a", "property", "object", "from", "a", "resource", "specified", "by", "a", "property", "name", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L7418-L7441
taskadapter/redmine-java-api
src/main/java/com/taskadapter/redmineapi/AttachmentManager.java
AttachmentManager.uploadAttachment
public Attachment uploadAttachment(String contentType, File content) throws RedmineException, IOException { """ Uploads an attachment. @param contentType content type of the attachment. @param content attachment content stream. @return attachment content. @throws RedmineException if something goes wrong. @throws IOException if input cannot be read. """ try (InputStream is = new FileInputStream(content)) { return uploadAttachment(content.getName(), contentType, is, content.length()); } }
java
public Attachment uploadAttachment(String contentType, File content) throws RedmineException, IOException { try (InputStream is = new FileInputStream(content)) { return uploadAttachment(content.getName(), contentType, is, content.length()); } }
[ "public", "Attachment", "uploadAttachment", "(", "String", "contentType", ",", "File", "content", ")", "throws", "RedmineException", ",", "IOException", "{", "try", "(", "InputStream", "is", "=", "new", "FileInputStream", "(", "content", ")", ")", "{", "return", "uploadAttachment", "(", "content", ".", "getName", "(", ")", ",", "contentType", ",", "is", ",", "content", ".", "length", "(", ")", ")", ";", "}", "}" ]
Uploads an attachment. @param contentType content type of the attachment. @param content attachment content stream. @return attachment content. @throws RedmineException if something goes wrong. @throws IOException if input cannot be read.
[ "Uploads", "an", "attachment", "." ]
train
https://github.com/taskadapter/redmine-java-api/blob/0bb65f27ee806ec3bd4007e1641f3e996261a04e/src/main/java/com/taskadapter/redmineapi/AttachmentManager.java#L102-L107
google/jimfs
jimfs/src/main/java/com/google/common/jimfs/FileSystemView.java
FileSystemView.newDirectoryStream
public DirectoryStream<Path> newDirectoryStream( JimfsPath dir, DirectoryStream.Filter<? super Path> filter, Set<? super LinkOption> options, JimfsPath basePathForStream) throws IOException { """ Creates a new directory stream for the directory located by the given path. The given {@code basePathForStream} is that base path that the returned stream will use. This will be the same as {@code dir} except for streams created relative to another secure stream. """ Directory file = (Directory) lookUpWithLock(dir, options).requireDirectory(dir).file(); FileSystemView view = new FileSystemView(store, file, basePathForStream); JimfsSecureDirectoryStream stream = new JimfsSecureDirectoryStream(view, filter, state()); return store.supportsFeature(Feature.SECURE_DIRECTORY_STREAM) ? stream : new DowngradedDirectoryStream(stream); }
java
public DirectoryStream<Path> newDirectoryStream( JimfsPath dir, DirectoryStream.Filter<? super Path> filter, Set<? super LinkOption> options, JimfsPath basePathForStream) throws IOException { Directory file = (Directory) lookUpWithLock(dir, options).requireDirectory(dir).file(); FileSystemView view = new FileSystemView(store, file, basePathForStream); JimfsSecureDirectoryStream stream = new JimfsSecureDirectoryStream(view, filter, state()); return store.supportsFeature(Feature.SECURE_DIRECTORY_STREAM) ? stream : new DowngradedDirectoryStream(stream); }
[ "public", "DirectoryStream", "<", "Path", ">", "newDirectoryStream", "(", "JimfsPath", "dir", ",", "DirectoryStream", ".", "Filter", "<", "?", "super", "Path", ">", "filter", ",", "Set", "<", "?", "super", "LinkOption", ">", "options", ",", "JimfsPath", "basePathForStream", ")", "throws", "IOException", "{", "Directory", "file", "=", "(", "Directory", ")", "lookUpWithLock", "(", "dir", ",", "options", ")", ".", "requireDirectory", "(", "dir", ")", ".", "file", "(", ")", ";", "FileSystemView", "view", "=", "new", "FileSystemView", "(", "store", ",", "file", ",", "basePathForStream", ")", ";", "JimfsSecureDirectoryStream", "stream", "=", "new", "JimfsSecureDirectoryStream", "(", "view", ",", "filter", ",", "state", "(", ")", ")", ";", "return", "store", ".", "supportsFeature", "(", "Feature", ".", "SECURE_DIRECTORY_STREAM", ")", "?", "stream", ":", "new", "DowngradedDirectoryStream", "(", "stream", ")", ";", "}" ]
Creates a new directory stream for the directory located by the given path. The given {@code basePathForStream} is that base path that the returned stream will use. This will be the same as {@code dir} except for streams created relative to another secure stream.
[ "Creates", "a", "new", "directory", "stream", "for", "the", "directory", "located", "by", "the", "given", "path", ".", "The", "given", "{" ]
train
https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/FileSystemView.java#L119-L131
mgormley/pacaya
src/main/java/edu/jhu/pacaya/gm/eval/MseMarginalEvaluator.java
MseMarginalEvaluator.evaluate
public double evaluate(VarConfig goldConfig, FgInferencer inf) { """ Computes the mean squared error between the true marginals (as represented by the goldConfig) and the predicted marginals (as represented by an inferencer). @param goldConfig The gold configuration of the variables. @param inf The (already run) inferencer storing the predicted marginals. @return The UNORMALIZED mean squared error. """ Algebra s = RealAlgebra.getInstance(); double sum = s.zero(); for (Var v : goldConfig.getVars()) { if (v.getType() == VarType.PREDICTED) { VarTensor marg = inf.getMarginals(v); int goldState = goldConfig.getState(v); for (int c=0; c<marg.size(); c++) { double goldMarg = (c == goldState) ? s.one() : s.zero(); double predMarg = marg.getValue(c); double diff = s.minus(Math.max(goldMarg, predMarg), Math.min(goldMarg, predMarg)); sum = s.plus(sum, s.times(diff, diff)); } } } return s.toReal(sum); }
java
public double evaluate(VarConfig goldConfig, FgInferencer inf) { Algebra s = RealAlgebra.getInstance(); double sum = s.zero(); for (Var v : goldConfig.getVars()) { if (v.getType() == VarType.PREDICTED) { VarTensor marg = inf.getMarginals(v); int goldState = goldConfig.getState(v); for (int c=0; c<marg.size(); c++) { double goldMarg = (c == goldState) ? s.one() : s.zero(); double predMarg = marg.getValue(c); double diff = s.minus(Math.max(goldMarg, predMarg), Math.min(goldMarg, predMarg)); sum = s.plus(sum, s.times(diff, diff)); } } } return s.toReal(sum); }
[ "public", "double", "evaluate", "(", "VarConfig", "goldConfig", ",", "FgInferencer", "inf", ")", "{", "Algebra", "s", "=", "RealAlgebra", ".", "getInstance", "(", ")", ";", "double", "sum", "=", "s", ".", "zero", "(", ")", ";", "for", "(", "Var", "v", ":", "goldConfig", ".", "getVars", "(", ")", ")", "{", "if", "(", "v", ".", "getType", "(", ")", "==", "VarType", ".", "PREDICTED", ")", "{", "VarTensor", "marg", "=", "inf", ".", "getMarginals", "(", "v", ")", ";", "int", "goldState", "=", "goldConfig", ".", "getState", "(", "v", ")", ";", "for", "(", "int", "c", "=", "0", ";", "c", "<", "marg", ".", "size", "(", ")", ";", "c", "++", ")", "{", "double", "goldMarg", "=", "(", "c", "==", "goldState", ")", "?", "s", ".", "one", "(", ")", ":", "s", ".", "zero", "(", ")", ";", "double", "predMarg", "=", "marg", ".", "getValue", "(", "c", ")", ";", "double", "diff", "=", "s", ".", "minus", "(", "Math", ".", "max", "(", "goldMarg", ",", "predMarg", ")", ",", "Math", ".", "min", "(", "goldMarg", ",", "predMarg", ")", ")", ";", "sum", "=", "s", ".", "plus", "(", "sum", ",", "s", ".", "times", "(", "diff", ",", "diff", ")", ")", ";", "}", "}", "}", "return", "s", ".", "toReal", "(", "sum", ")", ";", "}" ]
Computes the mean squared error between the true marginals (as represented by the goldConfig) and the predicted marginals (as represented by an inferencer). @param goldConfig The gold configuration of the variables. @param inf The (already run) inferencer storing the predicted marginals. @return The UNORMALIZED mean squared error.
[ "Computes", "the", "mean", "squared", "error", "between", "the", "true", "marginals", "(", "as", "represented", "by", "the", "goldConfig", ")", "and", "the", "predicted", "marginals", "(", "as", "represented", "by", "an", "inferencer", ")", "." ]
train
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/gm/eval/MseMarginalEvaluator.java#L22-L39
spockframework/spock
spock-core/src/main/java/spock/util/environment/OperatingSystem.java
OperatingSystem.getCurrent
public static OperatingSystem getCurrent() { """ Returns the current operating system. @return the current operating system """ String name = System.getProperty("os.name"); String version = System.getProperty("os.version"); String lowerName = name.toLowerCase(); if (lowerName.contains("linux")) return new OperatingSystem(name, version, Family.LINUX); if (lowerName.contains("mac os") || lowerName.contains("darwin")) return new OperatingSystem(name, version, Family.MAC_OS); if (lowerName.contains("windows")) return new OperatingSystem(name, version, Family.WINDOWS); if (lowerName.contains("sunos")) return new OperatingSystem(name, version, Family.SOLARIS); return new OperatingSystem(name, version, Family.OTHER); }
java
public static OperatingSystem getCurrent() { String name = System.getProperty("os.name"); String version = System.getProperty("os.version"); String lowerName = name.toLowerCase(); if (lowerName.contains("linux")) return new OperatingSystem(name, version, Family.LINUX); if (lowerName.contains("mac os") || lowerName.contains("darwin")) return new OperatingSystem(name, version, Family.MAC_OS); if (lowerName.contains("windows")) return new OperatingSystem(name, version, Family.WINDOWS); if (lowerName.contains("sunos")) return new OperatingSystem(name, version, Family.SOLARIS); return new OperatingSystem(name, version, Family.OTHER); }
[ "public", "static", "OperatingSystem", "getCurrent", "(", ")", "{", "String", "name", "=", "System", ".", "getProperty", "(", "\"os.name\"", ")", ";", "String", "version", "=", "System", ".", "getProperty", "(", "\"os.version\"", ")", ";", "String", "lowerName", "=", "name", ".", "toLowerCase", "(", ")", ";", "if", "(", "lowerName", ".", "contains", "(", "\"linux\"", ")", ")", "return", "new", "OperatingSystem", "(", "name", ",", "version", ",", "Family", ".", "LINUX", ")", ";", "if", "(", "lowerName", ".", "contains", "(", "\"mac os\"", ")", "||", "lowerName", ".", "contains", "(", "\"darwin\"", ")", ")", "return", "new", "OperatingSystem", "(", "name", ",", "version", ",", "Family", ".", "MAC_OS", ")", ";", "if", "(", "lowerName", ".", "contains", "(", "\"windows\"", ")", ")", "return", "new", "OperatingSystem", "(", "name", ",", "version", ",", "Family", ".", "WINDOWS", ")", ";", "if", "(", "lowerName", ".", "contains", "(", "\"sunos\"", ")", ")", "return", "new", "OperatingSystem", "(", "name", ",", "version", ",", "Family", ".", "SOLARIS", ")", ";", "return", "new", "OperatingSystem", "(", "name", ",", "version", ",", "Family", ".", "OTHER", ")", ";", "}" ]
Returns the current operating system. @return the current operating system
[ "Returns", "the", "current", "operating", "system", "." ]
train
https://github.com/spockframework/spock/blob/d751a0abd8d5a2ec5338aa10bc2d19371b3b3ad9/spock-core/src/main/java/spock/util/environment/OperatingSystem.java#L140-L149
elki-project/elki
elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java
DBIDUtil.randomShuffle
public static void randomShuffle(ArrayModifiableDBIDs ids, Random random) { """ Produce a random shuffling of the given DBID array. @param ids Original DBIDs, no duplicates allowed @param random Random generator """ randomShuffle(ids, random, ids.size()); }
java
public static void randomShuffle(ArrayModifiableDBIDs ids, Random random) { randomShuffle(ids, random, ids.size()); }
[ "public", "static", "void", "randomShuffle", "(", "ArrayModifiableDBIDs", "ids", ",", "Random", "random", ")", "{", "randomShuffle", "(", "ids", ",", "random", ",", "ids", ".", "size", "(", ")", ")", ";", "}" ]
Produce a random shuffling of the given DBID array. @param ids Original DBIDs, no duplicates allowed @param random Random generator
[ "Produce", "a", "random", "shuffling", "of", "the", "given", "DBID", "array", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java#L520-L522
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_vserver_appflow_config.java
ns_vserver_appflow_config.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ ns_vserver_appflow_config_responses result = (ns_vserver_appflow_config_responses) service.get_payload_formatter().string_to_resource(ns_vserver_appflow_config_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_vserver_appflow_config_response_array); } ns_vserver_appflow_config[] result_ns_vserver_appflow_config = new ns_vserver_appflow_config[result.ns_vserver_appflow_config_response_array.length]; for(int i = 0; i < result.ns_vserver_appflow_config_response_array.length; i++) { result_ns_vserver_appflow_config[i] = result.ns_vserver_appflow_config_response_array[i].ns_vserver_appflow_config[0]; } return result_ns_vserver_appflow_config; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ns_vserver_appflow_config_responses result = (ns_vserver_appflow_config_responses) service.get_payload_formatter().string_to_resource(ns_vserver_appflow_config_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_vserver_appflow_config_response_array); } ns_vserver_appflow_config[] result_ns_vserver_appflow_config = new ns_vserver_appflow_config[result.ns_vserver_appflow_config_response_array.length]; for(int i = 0; i < result.ns_vserver_appflow_config_response_array.length; i++) { result_ns_vserver_appflow_config[i] = result.ns_vserver_appflow_config_response_array[i].ns_vserver_appflow_config[0]; } return result_ns_vserver_appflow_config; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "ns_vserver_appflow_config_responses", "result", "=", "(", "ns_vserver_appflow_config_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "ns_vserver_appflow_config_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "ns_vserver_appflow_config_response_array", ")", ";", "}", "ns_vserver_appflow_config", "[", "]", "result_ns_vserver_appflow_config", "=", "new", "ns_vserver_appflow_config", "[", "result", ".", "ns_vserver_appflow_config_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "ns_vserver_appflow_config_response_array", ".", "length", ";", "i", "++", ")", "{", "result_ns_vserver_appflow_config", "[", "i", "]", "=", "result", ".", "ns_vserver_appflow_config_response_array", "[", "i", "]", ".", "ns_vserver_appflow_config", "[", "0", "]", ";", "}", "return", "result_ns_vserver_appflow_config", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_vserver_appflow_config.java#L470-L487
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/module/ManifestClassPathProcessor.java
ManifestClassPathProcessor.createResourceRoot
private synchronized ResourceRoot createResourceRoot(final VirtualFile file, final DeploymentUnit deploymentUnit, final VirtualFile deploymentRoot) throws DeploymentUnitProcessingException { """ Creates a {@link ResourceRoot} for the passed {@link VirtualFile file} and adds it to the list of {@link ResourceRoot}s in the {@link DeploymentUnit deploymentUnit} @param file The file for which the resource root will be created @return Returns the created {@link ResourceRoot} @throws java.io.IOException """ try { Map<String, MountedDeploymentOverlay> overlays = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_OVERLAY_LOCATIONS); String relativeName = file.getPathNameRelativeTo(deploymentRoot); MountedDeploymentOverlay overlay = overlays.get(relativeName); Closeable closable = null; if(overlay != null) { overlay.remountAsZip(false); } else if(file.isFile()) { closable = VFS.mountZip(file, file, TempFileProviderService.provider()); } final MountHandle mountHandle = MountHandle.create(closable); final ResourceRoot resourceRoot = new ResourceRoot(file, mountHandle); ModuleRootMarker.mark(resourceRoot); ResourceRootIndexer.indexResourceRoot(resourceRoot); return resourceRoot; } catch (IOException e) { throw new RuntimeException(e); } }
java
private synchronized ResourceRoot createResourceRoot(final VirtualFile file, final DeploymentUnit deploymentUnit, final VirtualFile deploymentRoot) throws DeploymentUnitProcessingException { try { Map<String, MountedDeploymentOverlay> overlays = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_OVERLAY_LOCATIONS); String relativeName = file.getPathNameRelativeTo(deploymentRoot); MountedDeploymentOverlay overlay = overlays.get(relativeName); Closeable closable = null; if(overlay != null) { overlay.remountAsZip(false); } else if(file.isFile()) { closable = VFS.mountZip(file, file, TempFileProviderService.provider()); } final MountHandle mountHandle = MountHandle.create(closable); final ResourceRoot resourceRoot = new ResourceRoot(file, mountHandle); ModuleRootMarker.mark(resourceRoot); ResourceRootIndexer.indexResourceRoot(resourceRoot); return resourceRoot; } catch (IOException e) { throw new RuntimeException(e); } }
[ "private", "synchronized", "ResourceRoot", "createResourceRoot", "(", "final", "VirtualFile", "file", ",", "final", "DeploymentUnit", "deploymentUnit", ",", "final", "VirtualFile", "deploymentRoot", ")", "throws", "DeploymentUnitProcessingException", "{", "try", "{", "Map", "<", "String", ",", "MountedDeploymentOverlay", ">", "overlays", "=", "deploymentUnit", ".", "getAttachment", "(", "Attachments", ".", "DEPLOYMENT_OVERLAY_LOCATIONS", ")", ";", "String", "relativeName", "=", "file", ".", "getPathNameRelativeTo", "(", "deploymentRoot", ")", ";", "MountedDeploymentOverlay", "overlay", "=", "overlays", ".", "get", "(", "relativeName", ")", ";", "Closeable", "closable", "=", "null", ";", "if", "(", "overlay", "!=", "null", ")", "{", "overlay", ".", "remountAsZip", "(", "false", ")", ";", "}", "else", "if", "(", "file", ".", "isFile", "(", ")", ")", "{", "closable", "=", "VFS", ".", "mountZip", "(", "file", ",", "file", ",", "TempFileProviderService", ".", "provider", "(", ")", ")", ";", "}", "final", "MountHandle", "mountHandle", "=", "MountHandle", ".", "create", "(", "closable", ")", ";", "final", "ResourceRoot", "resourceRoot", "=", "new", "ResourceRoot", "(", "file", ",", "mountHandle", ")", ";", "ModuleRootMarker", ".", "mark", "(", "resourceRoot", ")", ";", "ResourceRootIndexer", ".", "indexResourceRoot", "(", "resourceRoot", ")", ";", "return", "resourceRoot", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Creates a {@link ResourceRoot} for the passed {@link VirtualFile file} and adds it to the list of {@link ResourceRoot}s in the {@link DeploymentUnit deploymentUnit} @param file The file for which the resource root will be created @return Returns the created {@link ResourceRoot} @throws java.io.IOException
[ "Creates", "a", "{", "@link", "ResourceRoot", "}", "for", "the", "passed", "{", "@link", "VirtualFile", "file", "}", "and", "adds", "it", "to", "the", "list", "of", "{", "@link", "ResourceRoot", "}", "s", "in", "the", "{", "@link", "DeploymentUnit", "deploymentUnit", "}" ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/module/ManifestClassPathProcessor.java#L265-L285
Netflix/conductor
client/src/main/java/com/netflix/conductor/client/http/TaskClient.java
TaskClient.getPendingTasksByType
public List<Task> getPendingTasksByType(String taskType, String startKey, Integer count) { """ Retrieve pending tasks by type @param taskType Type of task @param startKey id of the task from where to return the results. NULL to start from the beginning. @param count number of tasks to retrieve @return Returns the list of PENDING tasks by type, starting with a given task Id. """ Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank"); Object[] params = new Object[]{"startKey", startKey, "count", count}; return getForEntity("tasks/in_progress/{taskType}", params, taskList, taskType); }
java
public List<Task> getPendingTasksByType(String taskType, String startKey, Integer count) { Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank"); Object[] params = new Object[]{"startKey", startKey, "count", count}; return getForEntity("tasks/in_progress/{taskType}", params, taskList, taskType); }
[ "public", "List", "<", "Task", ">", "getPendingTasksByType", "(", "String", "taskType", ",", "String", "startKey", ",", "Integer", "count", ")", "{", "Preconditions", ".", "checkArgument", "(", "StringUtils", ".", "isNotBlank", "(", "taskType", ")", ",", "\"Task type cannot be blank\"", ")", ";", "Object", "[", "]", "params", "=", "new", "Object", "[", "]", "{", "\"startKey\"", ",", "startKey", ",", "\"count\"", ",", "count", "}", ";", "return", "getForEntity", "(", "\"tasks/in_progress/{taskType}\"", ",", "params", ",", "taskList", ",", "taskType", ")", ";", "}" ]
Retrieve pending tasks by type @param taskType Type of task @param startKey id of the task from where to return the results. NULL to start from the beginning. @param count number of tasks to retrieve @return Returns the list of PENDING tasks by type, starting with a given task Id.
[ "Retrieve", "pending", "tasks", "by", "type" ]
train
https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/client/src/main/java/com/netflix/conductor/client/http/TaskClient.java#L194-L199
protostuff/protostuff
protostuff-core/src/main/java/io/protostuff/IOUtil.java
IOUtil.mergeFrom
static <T> void mergeFrom(byte[] data, int offset, int length, T message, Schema<T> schema, boolean decodeNestedMessageAsGroup) { """ Merges the {@code message} with the byte array using the given {@code schema}. """ try { final ByteArrayInput input = new ByteArrayInput(data, offset, length, decodeNestedMessageAsGroup); schema.mergeFrom(input, message); input.checkLastTagWas(0); } catch (ArrayIndexOutOfBoundsException ae) { throw new RuntimeException("Truncated.", ProtobufException.truncatedMessage(ae)); } catch (IOException e) { throw new RuntimeException("Reading from a byte array threw an IOException (should " + "never happen).", e); } }
java
static <T> void mergeFrom(byte[] data, int offset, int length, T message, Schema<T> schema, boolean decodeNestedMessageAsGroup) { try { final ByteArrayInput input = new ByteArrayInput(data, offset, length, decodeNestedMessageAsGroup); schema.mergeFrom(input, message); input.checkLastTagWas(0); } catch (ArrayIndexOutOfBoundsException ae) { throw new RuntimeException("Truncated.", ProtobufException.truncatedMessage(ae)); } catch (IOException e) { throw new RuntimeException("Reading from a byte array threw an IOException (should " + "never happen).", e); } }
[ "static", "<", "T", ">", "void", "mergeFrom", "(", "byte", "[", "]", "data", ",", "int", "offset", ",", "int", "length", ",", "T", "message", ",", "Schema", "<", "T", ">", "schema", ",", "boolean", "decodeNestedMessageAsGroup", ")", "{", "try", "{", "final", "ByteArrayInput", "input", "=", "new", "ByteArrayInput", "(", "data", ",", "offset", ",", "length", ",", "decodeNestedMessageAsGroup", ")", ";", "schema", ".", "mergeFrom", "(", "input", ",", "message", ")", ";", "input", ".", "checkLastTagWas", "(", "0", ")", ";", "}", "catch", "(", "ArrayIndexOutOfBoundsException", "ae", ")", "{", "throw", "new", "RuntimeException", "(", "\"Truncated.\"", ",", "ProtobufException", ".", "truncatedMessage", "(", "ae", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Reading from a byte array threw an IOException (should \"", "+", "\"never happen).\"", ",", "e", ")", ";", "}", "}" ]
Merges the {@code message} with the byte array using the given {@code schema}.
[ "Merges", "the", "{" ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-core/src/main/java/io/protostuff/IOUtil.java#L38-L57
matthewhorridge/binaryowl
src/main/java/org/semanticweb/binaryowl/BinaryOWLMetadata.java
BinaryOWLMetadata.getBooleanAttribute
public Boolean getBooleanAttribute(String name, Boolean defaultValue) { """ Gets the boolean value of an attribute. @param name The name of the attribute. Not null. @param defaultValue The default value for the attribute. May be null. This value will be returned if this metadata object does not contain a boolean value for the specified attribute name. @return Either the boolean value of the attribute with the specified name, or the value specified by the defaultValue object if this metadata object does not contain a boolean value for the specified attribute name. @throws NullPointerException if name is null. """ return getValue(booleanAttributes, name, defaultValue); }
java
public Boolean getBooleanAttribute(String name, Boolean defaultValue) { return getValue(booleanAttributes, name, defaultValue); }
[ "public", "Boolean", "getBooleanAttribute", "(", "String", "name", ",", "Boolean", "defaultValue", ")", "{", "return", "getValue", "(", "booleanAttributes", ",", "name", ",", "defaultValue", ")", ";", "}" ]
Gets the boolean value of an attribute. @param name The name of the attribute. Not null. @param defaultValue The default value for the attribute. May be null. This value will be returned if this metadata object does not contain a boolean value for the specified attribute name. @return Either the boolean value of the attribute with the specified name, or the value specified by the defaultValue object if this metadata object does not contain a boolean value for the specified attribute name. @throws NullPointerException if name is null.
[ "Gets", "the", "boolean", "value", "of", "an", "attribute", "." ]
train
https://github.com/matthewhorridge/binaryowl/blob/7fccfe804120f86b38ca855ddbb569a81a042257/src/main/java/org/semanticweb/binaryowl/BinaryOWLMetadata.java#L356-L358
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/Monitor.java
Monitor.isInstanceRunning
public static boolean isInstanceRunning(String clusterName, int httpPort) { """ Check whether the cluster with the given name exists in the ES running on the given port. <br><br> This is an expensive method, for it initializes a new ES client. @param clusterName the ES cluster name @param httpPort the HTTP port to connect to ES @return true if the instance is running, false otherwise """ Log log = Mockito.mock(Log.class); try (ElasticsearchClient client = new ElasticsearchClient.Builder() .withLog(log) .withHostname("localhost") .withPort(httpPort) .withSocketTimeout(5000) .build()) { return new Monitor(client, log).isInstanceRunning(clusterName); } }
java
public static boolean isInstanceRunning(String clusterName, int httpPort) { Log log = Mockito.mock(Log.class); try (ElasticsearchClient client = new ElasticsearchClient.Builder() .withLog(log) .withHostname("localhost") .withPort(httpPort) .withSocketTimeout(5000) .build()) { return new Monitor(client, log).isInstanceRunning(clusterName); } }
[ "public", "static", "boolean", "isInstanceRunning", "(", "String", "clusterName", ",", "int", "httpPort", ")", "{", "Log", "log", "=", "Mockito", ".", "mock", "(", "Log", ".", "class", ")", ";", "try", "(", "ElasticsearchClient", "client", "=", "new", "ElasticsearchClient", ".", "Builder", "(", ")", ".", "withLog", "(", "log", ")", ".", "withHostname", "(", "\"localhost\"", ")", ".", "withPort", "(", "httpPort", ")", ".", "withSocketTimeout", "(", "5000", ")", ".", "build", "(", ")", ")", "{", "return", "new", "Monitor", "(", "client", ",", "log", ")", ".", "isInstanceRunning", "(", "clusterName", ")", ";", "}", "}" ]
Check whether the cluster with the given name exists in the ES running on the given port. <br><br> This is an expensive method, for it initializes a new ES client. @param clusterName the ES cluster name @param httpPort the HTTP port to connect to ES @return true if the instance is running, false otherwise
[ "Check", "whether", "the", "cluster", "with", "the", "given", "name", "exists", "in", "the", "ES", "running", "on", "the", "given", "port", ".", "<br", ">", "<br", ">", "This", "is", "an", "expensive", "method", "for", "it", "initializes", "a", "new", "ES", "client", "." ]
train
https://github.com/alexcojocaru/elasticsearch-maven-plugin/blob/c283053cf99dc6b6d411b58629364b6aae62b7f8/src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/Monitor.java#L94-L107
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericMultiBoJdbcDao.java
GenericMultiBoJdbcDao.addDelegateDao
@SuppressWarnings("unchecked") public <T> GenericMultiBoJdbcDao addDelegateDao(String className, IGenericBoDao<T> dao) throws ClassNotFoundException { """ Add a delegate dao to mapping list. @param className @param dao @return @throws ClassNotFoundException """ Class<T> clazz = (Class<T>) Class.forName(className); return addDelegateDao(clazz, dao); }
java
@SuppressWarnings("unchecked") public <T> GenericMultiBoJdbcDao addDelegateDao(String className, IGenericBoDao<T> dao) throws ClassNotFoundException { Class<T> clazz = (Class<T>) Class.forName(className); return addDelegateDao(clazz, dao); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "GenericMultiBoJdbcDao", "addDelegateDao", "(", "String", "className", ",", "IGenericBoDao", "<", "T", ">", "dao", ")", "throws", "ClassNotFoundException", "{", "Class", "<", "T", ">", "clazz", "=", "(", "Class", "<", "T", ">", ")", "Class", ".", "forName", "(", "className", ")", ";", "return", "addDelegateDao", "(", "clazz", ",", "dao", ")", ";", "}" ]
Add a delegate dao to mapping list. @param className @param dao @return @throws ClassNotFoundException
[ "Add", "a", "delegate", "dao", "to", "mapping", "list", "." ]
train
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericMultiBoJdbcDao.java#L88-L93
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureByFactorization.java
ProjectiveStructureByFactorization.setPixels
public void setPixels(int view , List<Point2D_F64> pixelsInView ) { """ Sets pixel observations for a paricular view @param view the view @param pixelsInView list of 2D pixel observations """ if( pixelsInView.size() != pixels.numCols ) throw new IllegalArgumentException("Pixel count must be constant and match "+pixels.numCols); int row = view*2; for (int i = 0; i < pixelsInView.size(); i++) { Point2D_F64 p = pixelsInView.get(i); pixels.set(row,i,p.x); pixels.set(row+1,i,p.y); pixelScale = Math.max(Math.abs(p.x),Math.abs(p.y)); } }
java
public void setPixels(int view , List<Point2D_F64> pixelsInView ) { if( pixelsInView.size() != pixels.numCols ) throw new IllegalArgumentException("Pixel count must be constant and match "+pixels.numCols); int row = view*2; for (int i = 0; i < pixelsInView.size(); i++) { Point2D_F64 p = pixelsInView.get(i); pixels.set(row,i,p.x); pixels.set(row+1,i,p.y); pixelScale = Math.max(Math.abs(p.x),Math.abs(p.y)); } }
[ "public", "void", "setPixels", "(", "int", "view", ",", "List", "<", "Point2D_F64", ">", "pixelsInView", ")", "{", "if", "(", "pixelsInView", ".", "size", "(", ")", "!=", "pixels", ".", "numCols", ")", "throw", "new", "IllegalArgumentException", "(", "\"Pixel count must be constant and match \"", "+", "pixels", ".", "numCols", ")", ";", "int", "row", "=", "view", "*", "2", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "pixelsInView", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Point2D_F64", "p", "=", "pixelsInView", ".", "get", "(", "i", ")", ";", "pixels", ".", "set", "(", "row", ",", "i", ",", "p", ".", "x", ")", ";", "pixels", ".", "set", "(", "row", "+", "1", ",", "i", ",", "p", ".", "y", ")", ";", "pixelScale", "=", "Math", ".", "max", "(", "Math", ".", "abs", "(", "p", ".", "x", ")", ",", "Math", ".", "abs", "(", "p", ".", "y", ")", ")", ";", "}", "}" ]
Sets pixel observations for a paricular view @param view the view @param pixelsInView list of 2D pixel observations
[ "Sets", "pixel", "observations", "for", "a", "paricular", "view" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureByFactorization.java#L109-L120
code4everything/util
src/main/java/com/zhazhapan/util/encryption/SimpleEncrypt.java
SimpleEncrypt.xor
public static String xor(String string, int key) { """ 异或加密 @param string {@link String} @param key {@link Integer} @return {@link String} """ char[] encrypt = string.toCharArray(); for (int i = 0; i < encrypt.length; i++) { encrypt[i] = (char) (encrypt[i] ^ key); } return new String(encrypt); }
java
public static String xor(String string, int key) { char[] encrypt = string.toCharArray(); for (int i = 0; i < encrypt.length; i++) { encrypt[i] = (char) (encrypt[i] ^ key); } return new String(encrypt); }
[ "public", "static", "String", "xor", "(", "String", "string", ",", "int", "key", ")", "{", "char", "[", "]", "encrypt", "=", "string", ".", "toCharArray", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "encrypt", ".", "length", ";", "i", "++", ")", "{", "encrypt", "[", "i", "]", "=", "(", "char", ")", "(", "encrypt", "[", "i", "]", "^", "key", ")", ";", "}", "return", "new", "String", "(", "encrypt", ")", ";", "}" ]
异或加密 @param string {@link String} @param key {@link Integer} @return {@link String}
[ "异或加密" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/encryption/SimpleEncrypt.java#L32-L38
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/JUnitXMLReporter.java
JUnitXMLReporter.generateReport
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectoryName) { """ Generates a set of XML files (JUnit format) that contain data about the outcome of the specified test suites. @param suites Data about the test runs. @param outputDirectoryName The directory in which to create the report. """ removeEmptyDirectories(new File(outputDirectoryName)); File outputDirectory = new File(outputDirectoryName, REPORT_DIRECTORY); outputDirectory.mkdirs(); Collection<TestClassResults> flattenedResults = flattenResults(suites); for (TestClassResults results : flattenedResults) { VelocityContext context = createContext(); context.put(RESULTS_KEY, results); try { generateFile(new File(outputDirectory, results.getTestClass().getName() + '_' + RESULTS_FILE), RESULTS_FILE + TEMPLATE_EXTENSION, context); } catch (Exception ex) { throw new ReportNGException("Failed generating JUnit XML report.", ex); } } }
java
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectoryName) { removeEmptyDirectories(new File(outputDirectoryName)); File outputDirectory = new File(outputDirectoryName, REPORT_DIRECTORY); outputDirectory.mkdirs(); Collection<TestClassResults> flattenedResults = flattenResults(suites); for (TestClassResults results : flattenedResults) { VelocityContext context = createContext(); context.put(RESULTS_KEY, results); try { generateFile(new File(outputDirectory, results.getTestClass().getName() + '_' + RESULTS_FILE), RESULTS_FILE + TEMPLATE_EXTENSION, context); } catch (Exception ex) { throw new ReportNGException("Failed generating JUnit XML report.", ex); } } }
[ "public", "void", "generateReport", "(", "List", "<", "XmlSuite", ">", "xmlSuites", ",", "List", "<", "ISuite", ">", "suites", ",", "String", "outputDirectoryName", ")", "{", "removeEmptyDirectories", "(", "new", "File", "(", "outputDirectoryName", ")", ")", ";", "File", "outputDirectory", "=", "new", "File", "(", "outputDirectoryName", ",", "REPORT_DIRECTORY", ")", ";", "outputDirectory", ".", "mkdirs", "(", ")", ";", "Collection", "<", "TestClassResults", ">", "flattenedResults", "=", "flattenResults", "(", "suites", ")", ";", "for", "(", "TestClassResults", "results", ":", "flattenedResults", ")", "{", "VelocityContext", "context", "=", "createContext", "(", ")", ";", "context", ".", "put", "(", "RESULTS_KEY", ",", "results", ")", ";", "try", "{", "generateFile", "(", "new", "File", "(", "outputDirectory", ",", "results", ".", "getTestClass", "(", ")", ".", "getName", "(", ")", "+", "'", "'", "+", "RESULTS_FILE", ")", ",", "RESULTS_FILE", "+", "TEMPLATE_EXTENSION", ",", "context", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "ReportNGException", "(", "\"Failed generating JUnit XML report.\"", ",", "ex", ")", ";", "}", "}", "}" ]
Generates a set of XML files (JUnit format) that contain data about the outcome of the specified test suites. @param suites Data about the test runs. @param outputDirectoryName The directory in which to create the report.
[ "Generates", "a", "set", "of", "XML", "files", "(", "JUnit", "format", ")", "that", "contain", "data", "about", "the", "outcome", "of", "the", "specified", "test", "suites", "." ]
train
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/JUnitXMLReporter.java#L59-L86
netty/netty
resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java
DnsNameResolver.resolveAll
public final Future<List<DnsRecord>> resolveAll(DnsQuestion question) { """ Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike {@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers. If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured {@link HostsFileEntries} before sending a query to the name servers. If a match is found in the {@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned. @param question the question @return the list of the {@link DnsRecord}s as the result of the resolution """ return resolveAll(question, EMPTY_ADDITIONALS, executor().<List<DnsRecord>>newPromise()); }
java
public final Future<List<DnsRecord>> resolveAll(DnsQuestion question) { return resolveAll(question, EMPTY_ADDITIONALS, executor().<List<DnsRecord>>newPromise()); }
[ "public", "final", "Future", "<", "List", "<", "DnsRecord", ">", ">", "resolveAll", "(", "DnsQuestion", "question", ")", "{", "return", "resolveAll", "(", "question", ",", "EMPTY_ADDITIONALS", ",", "executor", "(", ")", ".", "<", "List", "<", "DnsRecord", ">", ">", "newPromise", "(", ")", ")", ";", "}" ]
Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike {@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers. If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured {@link HostsFileEntries} before sending a query to the name servers. If a match is found in the {@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned. @param question the question @return the list of the {@link DnsRecord}s as the result of the resolution
[ "Resolves", "the", "{", "@link", "DnsRecord", "}", "s", "that", "are", "matched", "by", "the", "specified", "{", "@link", "DnsQuestion", "}", ".", "Unlike", "{", "@link", "#query", "(", "DnsQuestion", ")", "}", "this", "method", "handles", "redirection", "CNAMEs", "and", "multiple", "name", "servers", ".", "If", "the", "specified", "{", "@link", "DnsQuestion", "}", "is", "{", "@code", "A", "}", "or", "{", "@code", "AAAA", "}", "this", "method", "looks", "up", "the", "configured", "{", "@link", "HostsFileEntries", "}", "before", "sending", "a", "query", "to", "the", "name", "servers", ".", "If", "a", "match", "is", "found", "in", "the", "{", "@link", "HostsFileEntries", "}", "a", "synthetic", "{", "@code", "A", "}", "or", "{", "@code", "AAAA", "}", "record", "will", "be", "returned", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java#L711-L713
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGCheckbox.java
SVGCheckbox.renderCheckBox
public Element renderCheckBox(SVGPlot svgp, double x, double y, double size) { """ Render the SVG checkbox to a plot @param svgp Plot to draw to @param x X offset @param y Y offset @param size Size factor @return Container element """ // create check final Element checkmark = SVGEffects.makeCheckmark(svgp); checkmark.setAttribute(SVGConstants.SVG_TRANSFORM_ATTRIBUTE, "scale(" + (size / 12) + ") translate(" + x + " " + y + ")"); if(!checked) { checkmark.setAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE, SVGConstants.CSS_DISPLAY_PROPERTY + ":" + SVGConstants.CSS_NONE_VALUE); } // create box Element checkbox_box = SVGUtil.svgRect(svgp.getDocument(), x, y, size, size); checkbox_box.setAttribute(SVGConstants.SVG_FILL_ATTRIBUTE, "#d4e4f1"); checkbox_box.setAttribute(SVGConstants.SVG_STROKE_ATTRIBUTE, "#a0a0a0"); checkbox_box.setAttribute(SVGConstants.SVG_STROKE_WIDTH_ATTRIBUTE, "0.5"); // create checkbox final Element checkbox = svgp.svgElement(SVGConstants.SVG_G_TAG); checkbox.appendChild(checkbox_box); checkbox.appendChild(checkmark); // create Label if(label != null) { Element labele = svgp.svgText(x + 2 * size, y + size, label); // TODO: font size! checkbox.appendChild(labele); } // add click event listener EventTarget targ = (EventTarget) checkbox; targ.addEventListener(SVGConstants.SVG_CLICK_EVENT_TYPE, new EventListener() { @Override public void handleEvent(Event evt) { if(checked ^= true) { checkmark.removeAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE); } else { checkmark.setAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE, SVGConstants.CSS_DISPLAY_PROPERTY + ":" + SVGConstants.CSS_NONE_VALUE); } fireSwitchEvent(new ChangeEvent(SVGCheckbox.this)); } }, false); return checkbox; }
java
public Element renderCheckBox(SVGPlot svgp, double x, double y, double size) { // create check final Element checkmark = SVGEffects.makeCheckmark(svgp); checkmark.setAttribute(SVGConstants.SVG_TRANSFORM_ATTRIBUTE, "scale(" + (size / 12) + ") translate(" + x + " " + y + ")"); if(!checked) { checkmark.setAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE, SVGConstants.CSS_DISPLAY_PROPERTY + ":" + SVGConstants.CSS_NONE_VALUE); } // create box Element checkbox_box = SVGUtil.svgRect(svgp.getDocument(), x, y, size, size); checkbox_box.setAttribute(SVGConstants.SVG_FILL_ATTRIBUTE, "#d4e4f1"); checkbox_box.setAttribute(SVGConstants.SVG_STROKE_ATTRIBUTE, "#a0a0a0"); checkbox_box.setAttribute(SVGConstants.SVG_STROKE_WIDTH_ATTRIBUTE, "0.5"); // create checkbox final Element checkbox = svgp.svgElement(SVGConstants.SVG_G_TAG); checkbox.appendChild(checkbox_box); checkbox.appendChild(checkmark); // create Label if(label != null) { Element labele = svgp.svgText(x + 2 * size, y + size, label); // TODO: font size! checkbox.appendChild(labele); } // add click event listener EventTarget targ = (EventTarget) checkbox; targ.addEventListener(SVGConstants.SVG_CLICK_EVENT_TYPE, new EventListener() { @Override public void handleEvent(Event evt) { if(checked ^= true) { checkmark.removeAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE); } else { checkmark.setAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE, SVGConstants.CSS_DISPLAY_PROPERTY + ":" + SVGConstants.CSS_NONE_VALUE); } fireSwitchEvent(new ChangeEvent(SVGCheckbox.this)); } }, false); return checkbox; }
[ "public", "Element", "renderCheckBox", "(", "SVGPlot", "svgp", ",", "double", "x", ",", "double", "y", ",", "double", "size", ")", "{", "// create check", "final", "Element", "checkmark", "=", "SVGEffects", ".", "makeCheckmark", "(", "svgp", ")", ";", "checkmark", ".", "setAttribute", "(", "SVGConstants", ".", "SVG_TRANSFORM_ATTRIBUTE", ",", "\"scale(\"", "+", "(", "size", "/", "12", ")", "+", "\") translate(\"", "+", "x", "+", "\" \"", "+", "y", "+", "\")\"", ")", ";", "if", "(", "!", "checked", ")", "{", "checkmark", ".", "setAttribute", "(", "SVGConstants", ".", "SVG_STYLE_ATTRIBUTE", ",", "SVGConstants", ".", "CSS_DISPLAY_PROPERTY", "+", "\":\"", "+", "SVGConstants", ".", "CSS_NONE_VALUE", ")", ";", "}", "// create box", "Element", "checkbox_box", "=", "SVGUtil", ".", "svgRect", "(", "svgp", ".", "getDocument", "(", ")", ",", "x", ",", "y", ",", "size", ",", "size", ")", ";", "checkbox_box", ".", "setAttribute", "(", "SVGConstants", ".", "SVG_FILL_ATTRIBUTE", ",", "\"#d4e4f1\"", ")", ";", "checkbox_box", ".", "setAttribute", "(", "SVGConstants", ".", "SVG_STROKE_ATTRIBUTE", ",", "\"#a0a0a0\"", ")", ";", "checkbox_box", ".", "setAttribute", "(", "SVGConstants", ".", "SVG_STROKE_WIDTH_ATTRIBUTE", ",", "\"0.5\"", ")", ";", "// create checkbox", "final", "Element", "checkbox", "=", "svgp", ".", "svgElement", "(", "SVGConstants", ".", "SVG_G_TAG", ")", ";", "checkbox", ".", "appendChild", "(", "checkbox_box", ")", ";", "checkbox", ".", "appendChild", "(", "checkmark", ")", ";", "// create Label", "if", "(", "label", "!=", "null", ")", "{", "Element", "labele", "=", "svgp", ".", "svgText", "(", "x", "+", "2", "*", "size", ",", "y", "+", "size", ",", "label", ")", ";", "// TODO: font size!", "checkbox", ".", "appendChild", "(", "labele", ")", ";", "}", "// add click event listener", "EventTarget", "targ", "=", "(", "EventTarget", ")", "checkbox", ";", "targ", ".", "addEventListener", "(", "SVGConstants", ".", "SVG_CLICK_EVENT_TYPE", ",", "new", "EventListener", "(", ")", "{", "@", "Override", "public", "void", "handleEvent", "(", "Event", "evt", ")", "{", "if", "(", "checked", "^=", "true", ")", "{", "checkmark", ".", "removeAttribute", "(", "SVGConstants", ".", "SVG_STYLE_ATTRIBUTE", ")", ";", "}", "else", "{", "checkmark", ".", "setAttribute", "(", "SVGConstants", ".", "SVG_STYLE_ATTRIBUTE", ",", "SVGConstants", ".", "CSS_DISPLAY_PROPERTY", "+", "\":\"", "+", "SVGConstants", ".", "CSS_NONE_VALUE", ")", ";", "}", "fireSwitchEvent", "(", "new", "ChangeEvent", "(", "SVGCheckbox", ".", "this", ")", ")", ";", "}", "}", ",", "false", ")", ";", "return", "checkbox", ";", "}" ]
Render the SVG checkbox to a plot @param svgp Plot to draw to @param x X offset @param y Y offset @param size Size factor @return Container element
[ "Render", "the", "SVG", "checkbox", "to", "a", "plot" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGCheckbox.java#L84-L125
citrusframework/citrus
modules/citrus-jms/src/main/java/com/consol/citrus/jms/actions/PurgeJmsQueuesAction.java
PurgeJmsQueuesAction.purgeQueue
private void purgeQueue(Queue queue, Session session) throws JMSException { """ Purges a queue destination. @param queue @param session @throws JMSException """ purgeDestination(queue, session, queue.getQueueName()); }
java
private void purgeQueue(Queue queue, Session session) throws JMSException { purgeDestination(queue, session, queue.getQueueName()); }
[ "private", "void", "purgeQueue", "(", "Queue", "queue", ",", "Session", "session", ")", "throws", "JMSException", "{", "purgeDestination", "(", "queue", ",", "session", ",", "queue", ".", "getQueueName", "(", ")", ")", ";", "}" ]
Purges a queue destination. @param queue @param session @throws JMSException
[ "Purges", "a", "queue", "destination", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jms/src/main/java/com/consol/citrus/jms/actions/PurgeJmsQueuesAction.java#L117-L119
bazaarvoice/emodb
auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java
ApiKeyRealm.hasPermissionsById
public boolean hasPermissionsById(String id, Permission... permissions) { """ Test for whether an API key has specific permissions using its ID. """ return hasPermissionsById(id, Arrays.asList(permissions)); }
java
public boolean hasPermissionsById(String id, Permission... permissions) { return hasPermissionsById(id, Arrays.asList(permissions)); }
[ "public", "boolean", "hasPermissionsById", "(", "String", "id", ",", "Permission", "...", "permissions", ")", "{", "return", "hasPermissionsById", "(", "id", ",", "Arrays", ".", "asList", "(", "permissions", ")", ")", ";", "}" ]
Test for whether an API key has specific permissions using its ID.
[ "Test", "for", "whether", "an", "API", "key", "has", "specific", "permissions", "using", "its", "ID", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L458-L460
liferay/com-liferay-commerce
commerce-notification-api/src/main/java/com/liferay/commerce/notification/model/CommerceNotificationTemplateWrapper.java
CommerceNotificationTemplateWrapper.setFromNameMap
@Override public void setFromNameMap(Map<java.util.Locale, String> fromNameMap) { """ Sets the localized from names of this commerce notification template from the map of locales and localized from names. @param fromNameMap the locales and localized from names of this commerce notification template """ _commerceNotificationTemplate.setFromNameMap(fromNameMap); }
java
@Override public void setFromNameMap(Map<java.util.Locale, String> fromNameMap) { _commerceNotificationTemplate.setFromNameMap(fromNameMap); }
[ "@", "Override", "public", "void", "setFromNameMap", "(", "Map", "<", "java", ".", "util", ".", "Locale", ",", "String", ">", "fromNameMap", ")", "{", "_commerceNotificationTemplate", ".", "setFromNameMap", "(", "fromNameMap", ")", ";", "}" ]
Sets the localized from names of this commerce notification template from the map of locales and localized from names. @param fromNameMap the locales and localized from names of this commerce notification template
[ "Sets", "the", "localized", "from", "names", "of", "this", "commerce", "notification", "template", "from", "the", "map", "of", "locales", "and", "localized", "from", "names", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-notification-api/src/main/java/com/liferay/commerce/notification/model/CommerceNotificationTemplateWrapper.java#L885-L888
EdwardRaff/JSAT
JSAT/src/jsat/math/integration/Trapezoidal.java
Trapezoidal.trapz
static public double trapz(Function1D f, double a, double b, int N) { """ Numerically computes the integral of the given function @param f the function to integrate @param a the lower limit of the integral @param b the upper limit of the integral @param N the number of points in the integral to take, must be &ge; 2. @return an approximation of the integral of &int;<sub>a</sub><sup>b</sup>f(x) , dx """ if(a == b) return 0; else if(a > b) throw new RuntimeException("Integral upper limit (" + b+") must be larger than the lower-limit (" + a + ")"); else if(N < 1) throw new RuntimeException("At least two integration parts must be used, not " + N); /* * b / N - 1 \ * / | ===== | * | b - a |f(a) + f(b) \ / k (b - a)\| * | f(x) dx = ----- |----------- + > f|a + ---------|| * | N | 2 / \ N /| * / | ===== | * a \ k = 1 / */ double sum =0; for(int k = 1; k < N; k++) sum += f.f(a+k*(b-a)/N); sum+= (f.f(a)+f.f(b))/2; return (b-a)/N*sum; }
java
static public double trapz(Function1D f, double a, double b, int N) { if(a == b) return 0; else if(a > b) throw new RuntimeException("Integral upper limit (" + b+") must be larger than the lower-limit (" + a + ")"); else if(N < 1) throw new RuntimeException("At least two integration parts must be used, not " + N); /* * b / N - 1 \ * / | ===== | * | b - a |f(a) + f(b) \ / k (b - a)\| * | f(x) dx = ----- |----------- + > f|a + ---------|| * | N | 2 / \ N /| * / | ===== | * a \ k = 1 / */ double sum =0; for(int k = 1; k < N; k++) sum += f.f(a+k*(b-a)/N); sum+= (f.f(a)+f.f(b))/2; return (b-a)/N*sum; }
[ "static", "public", "double", "trapz", "(", "Function1D", "f", ",", "double", "a", ",", "double", "b", ",", "int", "N", ")", "{", "if", "(", "a", "==", "b", ")", "return", "0", ";", "else", "if", "(", "a", ">", "b", ")", "throw", "new", "RuntimeException", "(", "\"Integral upper limit (\"", "+", "b", "+", "\") must be larger than the lower-limit (\"", "+", "a", "+", "\")\"", ")", ";", "else", "if", "(", "N", "<", "1", ")", "throw", "new", "RuntimeException", "(", "\"At least two integration parts must be used, not \"", "+", "N", ")", ";", "/*\r\n * b / N - 1 \\\r\n * / | ===== |\r\n * | b - a |f(a) + f(b) \\ / k (b - a)\\|\r\n * | f(x) dx = ----- |----------- + > f|a + ---------||\r\n * | N | 2 / \\ N /|\r\n * / | ===== |\r\n * a \\ k = 1 /\r\n */", "double", "sum", "=", "0", ";", "for", "(", "int", "k", "=", "1", ";", "k", "<", "N", ";", "k", "++", ")", "sum", "+=", ".", "(", "a", "+", "k", "*", "(", "b", "-", "a", ")", "/", "N", ")", ";", "sum", "+=", "(", "f", ".", "f", "(", "a", ")", "+", "f", ".", "f", "(", "b", ")", ")", "/", "2", ";", "return", "(", "b", "-", "a", ")", "/", "N", "*", "sum", ";", "}" ]
Numerically computes the integral of the given function @param f the function to integrate @param a the lower limit of the integral @param b the upper limit of the integral @param N the number of points in the integral to take, must be &ge; 2. @return an approximation of the integral of &int;<sub>a</sub><sup>b</sup>f(x) , dx
[ "Numerically", "computes", "the", "integral", "of", "the", "given", "function" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/math/integration/Trapezoidal.java#L24-L48
jMotif/GI
src/main/java/net/seninp/gi/sequitur/SAXSymbol.java
SAXSymbol.join
public static void join(SAXSymbol left, SAXSymbol right) { """ Links left and right symbols together, i.e. removes this symbol from the string, also removing any old digram from the hash table. @param left the left symbol. @param right the right symbol. """ // System.out.println(" performing the join of " + getPayload(left) + " and " // + getPayload(right)); // check for an OLD digram existence - i.e. left must have a next symbol // if .n exists then we are joining TERMINAL symbols within the string, and must clean-up the // old digram if (left.n != null) { // System.out.println(" " + getPayload(left) // + " use to be in the digram table, cleaning up"); left.deleteDigram(); } // re-link left and right left.n = right; right.p = left; }
java
public static void join(SAXSymbol left, SAXSymbol right) { // System.out.println(" performing the join of " + getPayload(left) + " and " // + getPayload(right)); // check for an OLD digram existence - i.e. left must have a next symbol // if .n exists then we are joining TERMINAL symbols within the string, and must clean-up the // old digram if (left.n != null) { // System.out.println(" " + getPayload(left) // + " use to be in the digram table, cleaning up"); left.deleteDigram(); } // re-link left and right left.n = right; right.p = left; }
[ "public", "static", "void", "join", "(", "SAXSymbol", "left", ",", "SAXSymbol", "right", ")", "{", "// System.out.println(\" performing the join of \" + getPayload(left) + \" and \"\r", "// + getPayload(right));\r", "// check for an OLD digram existence - i.e. left must have a next symbol\r", "// if .n exists then we are joining TERMINAL symbols within the string, and must clean-up the\r", "// old digram\r", "if", "(", "left", ".", "n", "!=", "null", ")", "{", "// System.out.println(\" \" + getPayload(left)\r", "// + \" use to be in the digram table, cleaning up\");\r", "left", ".", "deleteDigram", "(", ")", ";", "}", "// re-link left and right\r", "left", ".", "n", "=", "right", ";", "right", ".", "p", "=", "left", ";", "}" ]
Links left and right symbols together, i.e. removes this symbol from the string, also removing any old digram from the hash table. @param left the left symbol. @param right the right symbol.
[ "Links", "left", "and", "right", "symbols", "together", "i", ".", "e", ".", "removes", "this", "symbol", "from", "the", "string", "also", "removing", "any", "old", "digram", "from", "the", "hash", "table", "." ]
train
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/sequitur/SAXSymbol.java#L66-L83
UrielCh/ovh-java-sdk
ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java
ApiOvhIpLoadbalancing.serviceName_tcp_route_routeId_rule_ruleId_GET
public OvhRouteRule serviceName_tcp_route_routeId_rule_ruleId_GET(String serviceName, Long routeId, Long ruleId) throws IOException { """ Get this object properties REST: GET /ipLoadbalancing/{serviceName}/tcp/route/{routeId}/rule/{ruleId} @param serviceName [required] The internal name of your IP load balancing @param routeId [required] Id of your route @param ruleId [required] Id of your rule """ String qPath = "/ipLoadbalancing/{serviceName}/tcp/route/{routeId}/rule/{ruleId}"; StringBuilder sb = path(qPath, serviceName, routeId, ruleId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhRouteRule.class); }
java
public OvhRouteRule serviceName_tcp_route_routeId_rule_ruleId_GET(String serviceName, Long routeId, Long ruleId) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/tcp/route/{routeId}/rule/{ruleId}"; StringBuilder sb = path(qPath, serviceName, routeId, ruleId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhRouteRule.class); }
[ "public", "OvhRouteRule", "serviceName_tcp_route_routeId_rule_ruleId_GET", "(", "String", "serviceName", ",", "Long", "routeId", ",", "Long", "ruleId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/ipLoadbalancing/{serviceName}/tcp/route/{routeId}/rule/{ruleId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "routeId", ",", "ruleId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhRouteRule", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /ipLoadbalancing/{serviceName}/tcp/route/{routeId}/rule/{ruleId} @param serviceName [required] The internal name of your IP load balancing @param routeId [required] Id of your route @param ruleId [required] Id of your rule
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java#L1389-L1394
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_fax_serviceName_campaigns_id_detail_GET
public OvhFaxCampaignDetail billingAccount_fax_serviceName_campaigns_id_detail_GET(String billingAccount, String serviceName, Long id) throws IOException { """ Detail of the fax recipients by status REST: GET /telephony/{billingAccount}/fax/{serviceName}/campaigns/{id}/detail @param billingAccount [required] The name of your billingAccount @param serviceName [required] @param id [required] Id of the object """ String qPath = "/telephony/{billingAccount}/fax/{serviceName}/campaigns/{id}/detail"; StringBuilder sb = path(qPath, billingAccount, serviceName, id); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhFaxCampaignDetail.class); }
java
public OvhFaxCampaignDetail billingAccount_fax_serviceName_campaigns_id_detail_GET(String billingAccount, String serviceName, Long id) throws IOException { String qPath = "/telephony/{billingAccount}/fax/{serviceName}/campaigns/{id}/detail"; StringBuilder sb = path(qPath, billingAccount, serviceName, id); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhFaxCampaignDetail.class); }
[ "public", "OvhFaxCampaignDetail", "billingAccount_fax_serviceName_campaigns_id_detail_GET", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "Long", "id", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/fax/{serviceName}/campaigns/{id}/detail\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "billingAccount", ",", "serviceName", ",", "id", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhFaxCampaignDetail", ".", "class", ")", ";", "}" ]
Detail of the fax recipients by status REST: GET /telephony/{billingAccount}/fax/{serviceName}/campaigns/{id}/detail @param billingAccount [required] The name of your billingAccount @param serviceName [required] @param id [required] Id of the object
[ "Detail", "of", "the", "fax", "recipients", "by", "status" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L4335-L4340
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/classfile/ConstantNameAndTypeInfo.java
ConstantNameAndTypeInfo.make
static ConstantNameAndTypeInfo make(ConstantPool cp, String name, Descriptor type) { """ Will return either a new ConstantNameAndTypeInfo object or one already in the constant pool. If it is a new ConstantNameAndTypeInfo, it will be inserted into the pool. """ ConstantInfo ci = new ConstantNameAndTypeInfo(cp, name, type); return (ConstantNameAndTypeInfo)cp.addConstant(ci); }
java
static ConstantNameAndTypeInfo make(ConstantPool cp, String name, Descriptor type) { ConstantInfo ci = new ConstantNameAndTypeInfo(cp, name, type); return (ConstantNameAndTypeInfo)cp.addConstant(ci); }
[ "static", "ConstantNameAndTypeInfo", "make", "(", "ConstantPool", "cp", ",", "String", "name", ",", "Descriptor", "type", ")", "{", "ConstantInfo", "ci", "=", "new", "ConstantNameAndTypeInfo", "(", "cp", ",", "name", ",", "type", ")", ";", "return", "(", "ConstantNameAndTypeInfo", ")", "cp", ".", "addConstant", "(", "ci", ")", ";", "}" ]
Will return either a new ConstantNameAndTypeInfo object or one already in the constant pool. If it is a new ConstantNameAndTypeInfo, it will be inserted into the pool.
[ "Will", "return", "either", "a", "new", "ConstantNameAndTypeInfo", "object", "or", "one", "already", "in", "the", "constant", "pool", ".", "If", "it", "is", "a", "new", "ConstantNameAndTypeInfo", "it", "will", "be", "inserted", "into", "the", "pool", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/ConstantNameAndTypeInfo.java#L40-L45
UrielCh/ovh-java-sdk
ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java
ApiOvhEmailexchange.organizationName_service_exchangeService_protocol_activeSyncMailNotification_POST
public OvhTask organizationName_service_exchangeService_protocol_activeSyncMailNotification_POST(String organizationName, String exchangeService, Long notifiedAccountId) throws IOException { """ Subscribe new address to ActiveSync quarantine notifications REST: POST /email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification @param notifiedAccountId [required] Exchange Account Id @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service """ String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification"; StringBuilder sb = path(qPath, organizationName, exchangeService); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "notifiedAccountId", notifiedAccountId); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask organizationName_service_exchangeService_protocol_activeSyncMailNotification_POST(String organizationName, String exchangeService, Long notifiedAccountId) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification"; StringBuilder sb = path(qPath, organizationName, exchangeService); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "notifiedAccountId", notifiedAccountId); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "organizationName_service_exchangeService_protocol_activeSyncMailNotification_POST", "(", "String", "organizationName", ",", "String", "exchangeService", ",", "Long", "notifiedAccountId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "organizationName", ",", "exchangeService", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"notifiedAccountId\"", ",", "notifiedAccountId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhTask", ".", "class", ")", ";", "}" ]
Subscribe new address to ActiveSync quarantine notifications REST: POST /email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification @param notifiedAccountId [required] Exchange Account Id @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service
[ "Subscribe", "new", "address", "to", "ActiveSync", "quarantine", "notifications" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L2355-L2362
percolate/caffeine
caffeine/src/main/java/com/percolate/caffeine/IntentUtils.java
IntentUtils.launchCameraIntent
public static void launchCameraIntent(final Activity context, final Uri outputDestination, final int requestCode) { """ Launch camera on the device using android's ACTION_IMAGE_CAPTURE intent. @param outputDestination Save image to this location. """ final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputDestination); if (intent.resolveActivity(context.getPackageManager()) != null) { grantUriPermissionsForIntent(context, outputDestination, intent); context.startActivityForResult(intent, requestCode); } }
java
public static void launchCameraIntent(final Activity context, final Uri outputDestination, final int requestCode){ final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputDestination); if (intent.resolveActivity(context.getPackageManager()) != null) { grantUriPermissionsForIntent(context, outputDestination, intent); context.startActivityForResult(intent, requestCode); } }
[ "public", "static", "void", "launchCameraIntent", "(", "final", "Activity", "context", ",", "final", "Uri", "outputDestination", ",", "final", "int", "requestCode", ")", "{", "final", "Intent", "intent", "=", "new", "Intent", "(", "MediaStore", ".", "ACTION_IMAGE_CAPTURE", ")", ";", "intent", ".", "putExtra", "(", "MediaStore", ".", "EXTRA_OUTPUT", ",", "outputDestination", ")", ";", "if", "(", "intent", ".", "resolveActivity", "(", "context", ".", "getPackageManager", "(", ")", ")", "!=", "null", ")", "{", "grantUriPermissionsForIntent", "(", "context", ",", "outputDestination", ",", "intent", ")", ";", "context", ".", "startActivityForResult", "(", "intent", ",", "requestCode", ")", ";", "}", "}" ]
Launch camera on the device using android's ACTION_IMAGE_CAPTURE intent. @param outputDestination Save image to this location.
[ "Launch", "camera", "on", "the", "device", "using", "android", "s", "ACTION_IMAGE_CAPTURE", "intent", "." ]
train
https://github.com/percolate/caffeine/blob/e2265cab474a6397f4d75b1ed928c356a7b9672e/caffeine/src/main/java/com/percolate/caffeine/IntentUtils.java#L67-L74
Squarespace/cldr
runtime/src/main/java/com/squarespace/cldr/MessageArgsUnitParser.java
MessageArgsUnitParser.selectFactorSet
protected static UnitFactorSet selectFactorSet(String compact, UnitConverter converter) { """ Select a factor set based on a name, used to format compact units. For example, if compact="bytes" we return a factor set DIGITAL_BYTES. This set is then used to produce the most compact form for a given value, e.g. "1.2MB", "37TB", etc. """ if (compact != null) { switch (compact) { case "angle": case "angles": return UnitFactorSets.ANGLE; case "area": return converter.areaFactors(); case "bit": case "bits": return UnitFactorSets.DIGITAL_BITS; case "byte": case "bytes": return UnitFactorSets.DIGITAL_BYTES; case "duration": return UnitFactorSets.DURATION; case "duration-large": return UnitFactorSets.DURATION_LARGE; case "duration-small": return UnitFactorSets.DURATION_SMALL; case "electric": return UnitFactorSets.ELECTRIC; case "energy": return UnitFactorSets.ENERGY; case "frequency": return UnitFactorSets.FREQUENCY; case "length": return converter.lengthFactors(); case "mass": return converter.massFactors(); case "power": return UnitFactorSets.POWER; case "volume": return converter.volumeFactors(); case "liquid": return converter.volumeLiquidFactors(); default: break; } } return null; }
java
protected static UnitFactorSet selectFactorSet(String compact, UnitConverter converter) { if (compact != null) { switch (compact) { case "angle": case "angles": return UnitFactorSets.ANGLE; case "area": return converter.areaFactors(); case "bit": case "bits": return UnitFactorSets.DIGITAL_BITS; case "byte": case "bytes": return UnitFactorSets.DIGITAL_BYTES; case "duration": return UnitFactorSets.DURATION; case "duration-large": return UnitFactorSets.DURATION_LARGE; case "duration-small": return UnitFactorSets.DURATION_SMALL; case "electric": return UnitFactorSets.ELECTRIC; case "energy": return UnitFactorSets.ENERGY; case "frequency": return UnitFactorSets.FREQUENCY; case "length": return converter.lengthFactors(); case "mass": return converter.massFactors(); case "power": return UnitFactorSets.POWER; case "volume": return converter.volumeFactors(); case "liquid": return converter.volumeLiquidFactors(); default: break; } } return null; }
[ "protected", "static", "UnitFactorSet", "selectFactorSet", "(", "String", "compact", ",", "UnitConverter", "converter", ")", "{", "if", "(", "compact", "!=", "null", ")", "{", "switch", "(", "compact", ")", "{", "case", "\"angle\"", ":", "case", "\"angles\"", ":", "return", "UnitFactorSets", ".", "ANGLE", ";", "case", "\"area\"", ":", "return", "converter", ".", "areaFactors", "(", ")", ";", "case", "\"bit\"", ":", "case", "\"bits\"", ":", "return", "UnitFactorSets", ".", "DIGITAL_BITS", ";", "case", "\"byte\"", ":", "case", "\"bytes\"", ":", "return", "UnitFactorSets", ".", "DIGITAL_BYTES", ";", "case", "\"duration\"", ":", "return", "UnitFactorSets", ".", "DURATION", ";", "case", "\"duration-large\"", ":", "return", "UnitFactorSets", ".", "DURATION_LARGE", ";", "case", "\"duration-small\"", ":", "return", "UnitFactorSets", ".", "DURATION_SMALL", ";", "case", "\"electric\"", ":", "return", "UnitFactorSets", ".", "ELECTRIC", ";", "case", "\"energy\"", ":", "return", "UnitFactorSets", ".", "ENERGY", ";", "case", "\"frequency\"", ":", "return", "UnitFactorSets", ".", "FREQUENCY", ";", "case", "\"length\"", ":", "return", "converter", ".", "lengthFactors", "(", ")", ";", "case", "\"mass\"", ":", "return", "converter", ".", "massFactors", "(", ")", ";", "case", "\"power\"", ":", "return", "UnitFactorSets", ".", "POWER", ";", "case", "\"volume\"", ":", "return", "converter", ".", "volumeFactors", "(", ")", ";", "case", "\"liquid\"", ":", "return", "converter", ".", "volumeLiquidFactors", "(", ")", ";", "default", ":", "break", ";", "}", "}", "return", "null", ";", "}" ]
Select a factor set based on a name, used to format compact units. For example, if compact="bytes" we return a factor set DIGITAL_BYTES. This set is then used to produce the most compact form for a given value, e.g. "1.2MB", "37TB", etc.
[ "Select", "a", "factor", "set", "based", "on", "a", "name", "used", "to", "format", "compact", "units", ".", "For", "example", "if", "compact", "=", "bytes", "we", "return", "a", "factor", "set", "DIGITAL_BYTES", ".", "This", "set", "is", "then", "used", "to", "produce", "the", "most", "compact", "form", "for", "a", "given", "value", "e", ".", "g", ".", "1", ".", "2MB", "37TB", "etc", "." ]
train
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/MessageArgsUnitParser.java#L117-L158
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/StatementManager.java
StatementManager.registerStatement
private long registerStatement(long csid, Statement cs) { """ Registers a compiled statement to be managed. The only caller should be a Session that is attempting to prepare a statement for the first time or process a statement that has been invalidated due to DDL changes. @param csid existing id or negative if the statement is not yet managed @param cs The CompiledStatement to add @return The compiled statement id assigned to the CompiledStatement object """ if (csid < 0) { csid = nextID(); int schemaid = cs.getSchemaName().hashCode(); LongValueHashMap sqlMap = (LongValueHashMap) schemaMap.get(schemaid); if (sqlMap == null) { sqlMap = new LongValueHashMap(); schemaMap.put(schemaid, sqlMap); } sqlMap.put(cs.getSQL(), csid); sqlLookup.put(csid, cs.getSQL()); } cs.setID(csid); csidMap.put(csid, cs); return csid; }
java
private long registerStatement(long csid, Statement cs) { if (csid < 0) { csid = nextID(); int schemaid = cs.getSchemaName().hashCode(); LongValueHashMap sqlMap = (LongValueHashMap) schemaMap.get(schemaid); if (sqlMap == null) { sqlMap = new LongValueHashMap(); schemaMap.put(schemaid, sqlMap); } sqlMap.put(cs.getSQL(), csid); sqlLookup.put(csid, cs.getSQL()); } cs.setID(csid); csidMap.put(csid, cs); return csid; }
[ "private", "long", "registerStatement", "(", "long", "csid", ",", "Statement", "cs", ")", "{", "if", "(", "csid", "<", "0", ")", "{", "csid", "=", "nextID", "(", ")", ";", "int", "schemaid", "=", "cs", ".", "getSchemaName", "(", ")", ".", "hashCode", "(", ")", ";", "LongValueHashMap", "sqlMap", "=", "(", "LongValueHashMap", ")", "schemaMap", ".", "get", "(", "schemaid", ")", ";", "if", "(", "sqlMap", "==", "null", ")", "{", "sqlMap", "=", "new", "LongValueHashMap", "(", ")", ";", "schemaMap", ".", "put", "(", "schemaid", ",", "sqlMap", ")", ";", "}", "sqlMap", ".", "put", "(", "cs", ".", "getSQL", "(", ")", ",", "csid", ")", ";", "sqlLookup", ".", "put", "(", "csid", ",", "cs", ".", "getSQL", "(", ")", ")", ";", "}", "cs", ".", "setID", "(", "csid", ")", ";", "csidMap", ".", "put", "(", "csid", ",", "cs", ")", ";", "return", "csid", ";", "}" ]
Registers a compiled statement to be managed. The only caller should be a Session that is attempting to prepare a statement for the first time or process a statement that has been invalidated due to DDL changes. @param csid existing id or negative if the statement is not yet managed @param cs The CompiledStatement to add @return The compiled statement id assigned to the CompiledStatement object
[ "Registers", "a", "compiled", "statement", "to", "be", "managed", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/StatementManager.java#L269-L292
liyiorg/weixin-popular
src/main/java/weixin/popular/api/UserAPI.java
UserAPI.userInfo
public static User userInfo(String access_token,String openid,int emoji) { """ 获取用户基本信息 @since 2.7.1 @param access_token access_token @param openid openid @param emoji 表情解析方式<br> 0 不设置 <br> 1 HtmlHex 格式<br> 2 HtmlTag 格式<br> 3 Alias 格式<br> 4 HtmlDec 格式<br> 5 PureText 纯文本<br> @return User """ HttpUriRequest httpUriRequest = RequestBuilder.get() .setUri(BASE_URI+"/cgi-bin/user/info") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .addParameter("openid",openid) .addParameter("lang","zh_CN") .build(); User user = LocalHttpClient.executeJsonResult(httpUriRequest,User.class); if(emoji != 0 && user != null && user.getNickname() != null){ user.setNickname_emoji(EmojiUtil.parse(user.getNickname(), emoji)); } return user; }
java
public static User userInfo(String access_token,String openid,int emoji){ HttpUriRequest httpUriRequest = RequestBuilder.get() .setUri(BASE_URI+"/cgi-bin/user/info") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .addParameter("openid",openid) .addParameter("lang","zh_CN") .build(); User user = LocalHttpClient.executeJsonResult(httpUriRequest,User.class); if(emoji != 0 && user != null && user.getNickname() != null){ user.setNickname_emoji(EmojiUtil.parse(user.getNickname(), emoji)); } return user; }
[ "public", "static", "User", "userInfo", "(", "String", "access_token", ",", "String", "openid", ",", "int", "emoji", ")", "{", "HttpUriRequest", "httpUriRequest", "=", "RequestBuilder", ".", "get", "(", ")", ".", "setUri", "(", "BASE_URI", "+", "\"/cgi-bin/user/info\"", ")", ".", "addParameter", "(", "PARAM_ACCESS_TOKEN", ",", "API", ".", "accessToken", "(", "access_token", ")", ")", ".", "addParameter", "(", "\"openid\"", ",", "openid", ")", ".", "addParameter", "(", "\"lang\"", ",", "\"zh_CN\"", ")", ".", "build", "(", ")", ";", "User", "user", "=", "LocalHttpClient", ".", "executeJsonResult", "(", "httpUriRequest", ",", "User", ".", "class", ")", ";", "if", "(", "emoji", "!=", "0", "&&", "user", "!=", "null", "&&", "user", ".", "getNickname", "(", ")", "!=", "null", ")", "{", "user", ".", "setNickname_emoji", "(", "EmojiUtil", ".", "parse", "(", "user", ".", "getNickname", "(", ")", ",", "emoji", ")", ")", ";", "}", "return", "user", ";", "}" ]
获取用户基本信息 @since 2.7.1 @param access_token access_token @param openid openid @param emoji 表情解析方式<br> 0 不设置 <br> 1 HtmlHex 格式<br> 2 HtmlTag 格式<br> 3 Alias 格式<br> 4 HtmlDec 格式<br> 5 PureText 纯文本<br> @return User
[ "获取用户基本信息" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/UserAPI.java#L45-L57
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/Expression.java
Expression.replaceAliasInOrderBy
Expression replaceAliasInOrderBy(Expression[] columns, int length) { """ return the expression for an alias used in an ORDER BY clause """ for (int i = 0; i < nodes.length; i++) { if (nodes[i] == null) { continue; } nodes[i] = nodes[i].replaceAliasInOrderBy(columns, length); } return this; }
java
Expression replaceAliasInOrderBy(Expression[] columns, int length) { for (int i = 0; i < nodes.length; i++) { if (nodes[i] == null) { continue; } nodes[i] = nodes[i].replaceAliasInOrderBy(columns, length); } return this; }
[ "Expression", "replaceAliasInOrderBy", "(", "Expression", "[", "]", "columns", ",", "int", "length", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nodes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "nodes", "[", "i", "]", "==", "null", ")", "{", "continue", ";", "}", "nodes", "[", "i", "]", "=", "nodes", "[", "i", "]", ".", "replaceAliasInOrderBy", "(", "columns", ",", "length", ")", ";", "}", "return", "this", ";", "}" ]
return the expression for an alias used in an ORDER BY clause
[ "return", "the", "expression", "for", "an", "alias", "used", "in", "an", "ORDER", "BY", "clause" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/Expression.java#L804-L815
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.feature.cmdline/src/com/ibm/ws/kernel/feature/internal/generator/ManifestFileProcessor.java
ManifestFileProcessor.getCoreFeatureDir
public File getCoreFeatureDir() { """ Retrieves the Liberty core features directory. @return The Liberty core features directory """ File featureDir = null; File installDir = Utils.getInstallDir(); if (installDir != null) { featureDir = new File(installDir, FEATURE_DIR); } if (featureDir == null) { throw new RuntimeException("Feature Directory not found"); } return featureDir; }
java
public File getCoreFeatureDir() { File featureDir = null; File installDir = Utils.getInstallDir(); if (installDir != null) { featureDir = new File(installDir, FEATURE_DIR); } if (featureDir == null) { throw new RuntimeException("Feature Directory not found"); } return featureDir; }
[ "public", "File", "getCoreFeatureDir", "(", ")", "{", "File", "featureDir", "=", "null", ";", "File", "installDir", "=", "Utils", ".", "getInstallDir", "(", ")", ";", "if", "(", "installDir", "!=", "null", ")", "{", "featureDir", "=", "new", "File", "(", "installDir", ",", "FEATURE_DIR", ")", ";", "}", "if", "(", "featureDir", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"Feature Directory not found\"", ")", ";", "}", "return", "featureDir", ";", "}" ]
Retrieves the Liberty core features directory. @return The Liberty core features directory
[ "Retrieves", "the", "Liberty", "core", "features", "directory", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.feature.cmdline/src/com/ibm/ws/kernel/feature/internal/generator/ManifestFileProcessor.java#L439-L452
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/TileSheetsConfig.java
TileSheetsConfig.exportSheets
private static void exportSheets(Xml nodeSheets, Collection<String> sheets) { """ Export the defined sheets. @param nodeSheets Sheets node (must not be <code>null</code>). @param sheets Sheets defined (must not be <code>null</code>). """ for (final String sheet : sheets) { final Xml nodeSheet = nodeSheets.createChild(NODE_TILE_SHEET); nodeSheet.setText(sheet); } }
java
private static void exportSheets(Xml nodeSheets, Collection<String> sheets) { for (final String sheet : sheets) { final Xml nodeSheet = nodeSheets.createChild(NODE_TILE_SHEET); nodeSheet.setText(sheet); } }
[ "private", "static", "void", "exportSheets", "(", "Xml", "nodeSheets", ",", "Collection", "<", "String", ">", "sheets", ")", "{", "for", "(", "final", "String", "sheet", ":", "sheets", ")", "{", "final", "Xml", "nodeSheet", "=", "nodeSheets", ".", "createChild", "(", "NODE_TILE_SHEET", ")", ";", "nodeSheet", ".", "setText", "(", "sheet", ")", ";", "}", "}" ]
Export the defined sheets. @param nodeSheets Sheets node (must not be <code>null</code>). @param sheets Sheets defined (must not be <code>null</code>).
[ "Export", "the", "defined", "sheets", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/TileSheetsConfig.java#L123-L130
unbescape/unbescape
src/main/java/org/unbescape/xml/XmlEscape.java
XmlEscape.escapeXml11
public static void escapeXml11(final String text, final Writer writer, final XmlEscapeType type, final XmlEscapeLevel level) throws IOException { """ <p> Perform a (configurable) XML 1.1 <strong>escape</strong> operation on a <tt>String</tt> input, writing results to a <tt>Writer</tt>. </p> <p> This method will perform an escape operation according to the specified {@link org.unbescape.xml.XmlEscapeType} and {@link org.unbescape.xml.XmlEscapeLevel} argument values. </p> <p> All other <tt>String</tt>/<tt>Writer</tt>-based <tt>escapeXml11*(...)</tt> methods call this one with preconfigured <tt>type</tt> and <tt>level</tt> values. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>String</tt> to be escaped. @param type the type of escape operation to be performed, see {@link org.unbescape.xml.XmlEscapeType}. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @param level the escape level to be applied, see {@link org.unbescape.xml.XmlEscapeLevel}. @throws IOException if an input/output exception occurs @since 1.1.2 """ escapeXml(text, writer, XmlEscapeSymbols.XML11_SYMBOLS, type, level); }
java
public static void escapeXml11(final String text, final Writer writer, final XmlEscapeType type, final XmlEscapeLevel level) throws IOException { escapeXml(text, writer, XmlEscapeSymbols.XML11_SYMBOLS, type, level); }
[ "public", "static", "void", "escapeXml11", "(", "final", "String", "text", ",", "final", "Writer", "writer", ",", "final", "XmlEscapeType", "type", ",", "final", "XmlEscapeLevel", "level", ")", "throws", "IOException", "{", "escapeXml", "(", "text", ",", "writer", ",", "XmlEscapeSymbols", ".", "XML11_SYMBOLS", ",", "type", ",", "level", ")", ";", "}" ]
<p> Perform a (configurable) XML 1.1 <strong>escape</strong> operation on a <tt>String</tt> input, writing results to a <tt>Writer</tt>. </p> <p> This method will perform an escape operation according to the specified {@link org.unbescape.xml.XmlEscapeType} and {@link org.unbescape.xml.XmlEscapeLevel} argument values. </p> <p> All other <tt>String</tt>/<tt>Writer</tt>-based <tt>escapeXml11*(...)</tt> methods call this one with preconfigured <tt>type</tt> and <tt>level</tt> values. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>String</tt> to be escaped. @param type the type of escape operation to be performed, see {@link org.unbescape.xml.XmlEscapeType}. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @param level the escape level to be applied, see {@link org.unbescape.xml.XmlEscapeLevel}. @throws IOException if an input/output exception occurs @since 1.1.2
[ "<p", ">", "Perform", "a", "(", "configurable", ")", "XML", "1", ".", "1", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "String<", "/", "tt", ">", "input", "writing", "results", "to", "a", "<tt", ">", "Writer<", "/", "tt", ">", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "will", "perform", "an", "escape", "operation", "according", "to", "the", "specified", "{", "@link", "org", ".", "unbescape", ".", "xml", ".", "XmlEscapeType", "}", "and", "{", "@link", "org", ".", "unbescape", ".", "xml", ".", "XmlEscapeLevel", "}", "argument", "values", ".", "<", "/", "p", ">", "<p", ">", "All", "other", "<tt", ">", "String<", "/", "tt", ">", "/", "<tt", ">", "Writer<", "/", "tt", ">", "-", "based", "<tt", ">", "escapeXml11", "*", "(", "...", ")", "<", "/", "tt", ">", "methods", "call", "this", "one", "with", "preconfigured", "<tt", ">", "type<", "/", "tt", ">", "and", "<tt", ">", "level<", "/", "tt", ">", "values", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "is", "<strong", ">", "thread", "-", "safe<", "/", "strong", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/xml/XmlEscape.java#L1088-L1091
OpenTSDB/opentsdb
src/tsd/RpcHandler.java
RpcHandler.createQueryInstance
private AbstractHttpQuery createQueryInstance(final TSDB tsdb, final HttpRequest request, final Channel chan) throws BadRequestException { """ Using the request URI, creates a query instance capable of handling the given request. @param tsdb the TSDB instance we are running within @param request the incoming HTTP request @param chan the {@link Channel} the request came in on. @return a subclass of {@link AbstractHttpQuery} @throws BadRequestException if the request is invalid in a way that can be detected early, here. """ final String uri = request.getUri(); if (Strings.isNullOrEmpty(uri)) { throw new BadRequestException("Request URI is empty"); } else if (uri.charAt(0) != '/') { throw new BadRequestException("Request URI doesn't start with a slash"); } else if (rpc_manager.isHttpRpcPluginPath(uri)) { http_plugin_rpcs_received.incrementAndGet(); return new HttpRpcPluginQuery(tsdb, request, chan); } else { http_rpcs_received.incrementAndGet(); HttpQuery builtinQuery = new HttpQuery(tsdb, request, chan); return builtinQuery; } }
java
private AbstractHttpQuery createQueryInstance(final TSDB tsdb, final HttpRequest request, final Channel chan) throws BadRequestException { final String uri = request.getUri(); if (Strings.isNullOrEmpty(uri)) { throw new BadRequestException("Request URI is empty"); } else if (uri.charAt(0) != '/') { throw new BadRequestException("Request URI doesn't start with a slash"); } else if (rpc_manager.isHttpRpcPluginPath(uri)) { http_plugin_rpcs_received.incrementAndGet(); return new HttpRpcPluginQuery(tsdb, request, chan); } else { http_rpcs_received.incrementAndGet(); HttpQuery builtinQuery = new HttpQuery(tsdb, request, chan); return builtinQuery; } }
[ "private", "AbstractHttpQuery", "createQueryInstance", "(", "final", "TSDB", "tsdb", ",", "final", "HttpRequest", "request", ",", "final", "Channel", "chan", ")", "throws", "BadRequestException", "{", "final", "String", "uri", "=", "request", ".", "getUri", "(", ")", ";", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "uri", ")", ")", "{", "throw", "new", "BadRequestException", "(", "\"Request URI is empty\"", ")", ";", "}", "else", "if", "(", "uri", ".", "charAt", "(", "0", ")", "!=", "'", "'", ")", "{", "throw", "new", "BadRequestException", "(", "\"Request URI doesn't start with a slash\"", ")", ";", "}", "else", "if", "(", "rpc_manager", ".", "isHttpRpcPluginPath", "(", "uri", ")", ")", "{", "http_plugin_rpcs_received", ".", "incrementAndGet", "(", ")", ";", "return", "new", "HttpRpcPluginQuery", "(", "tsdb", ",", "request", ",", "chan", ")", ";", "}", "else", "{", "http_rpcs_received", ".", "incrementAndGet", "(", ")", ";", "HttpQuery", "builtinQuery", "=", "new", "HttpQuery", "(", "tsdb", ",", "request", ",", "chan", ")", ";", "return", "builtinQuery", ";", "}", "}" ]
Using the request URI, creates a query instance capable of handling the given request. @param tsdb the TSDB instance we are running within @param request the incoming HTTP request @param chan the {@link Channel} the request came in on. @return a subclass of {@link AbstractHttpQuery} @throws BadRequestException if the request is invalid in a way that can be detected early, here.
[ "Using", "the", "request", "URI", "creates", "a", "query", "instance", "capable", "of", "handling", "the", "given", "request", "." ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tsd/RpcHandler.java#L174-L191
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/square/BaseDetectFiducialSquare.java
BaseDetectFiducialSquare.prepareForOutput
private void prepareForOutput(Polygon2D_F64 imageShape, Result result) { """ Takes the found quadrilateral and the computed 3D information and prepares it for output """ // the rotation estimate, apply in counter clockwise direction // since result.rotation is a clockwise rotation in the visual sense, which // is CCW on the grid int rotationCCW = (4-result.rotation)%4; for (int j = 0; j < rotationCCW; j++) { UtilPolygons2D_F64.shiftUp(imageShape); } // save the results for output FoundFiducial f = found.grow(); f.id = result.which; for (int i = 0; i < 4; i++) { Point2D_F64 a = imageShape.get(i); undistToDist.compute(a.x, a.y, f.distortedPixels.get(i)); } }
java
private void prepareForOutput(Polygon2D_F64 imageShape, Result result) { // the rotation estimate, apply in counter clockwise direction // since result.rotation is a clockwise rotation in the visual sense, which // is CCW on the grid int rotationCCW = (4-result.rotation)%4; for (int j = 0; j < rotationCCW; j++) { UtilPolygons2D_F64.shiftUp(imageShape); } // save the results for output FoundFiducial f = found.grow(); f.id = result.which; for (int i = 0; i < 4; i++) { Point2D_F64 a = imageShape.get(i); undistToDist.compute(a.x, a.y, f.distortedPixels.get(i)); } }
[ "private", "void", "prepareForOutput", "(", "Polygon2D_F64", "imageShape", ",", "Result", "result", ")", "{", "// the rotation estimate, apply in counter clockwise direction", "// since result.rotation is a clockwise rotation in the visual sense, which", "// is CCW on the grid", "int", "rotationCCW", "=", "(", "4", "-", "result", ".", "rotation", ")", "%", "4", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "rotationCCW", ";", "j", "++", ")", "{", "UtilPolygons2D_F64", ".", "shiftUp", "(", "imageShape", ")", ";", "}", "// save the results for output", "FoundFiducial", "f", "=", "found", ".", "grow", "(", ")", ";", "f", ".", "id", "=", "result", ".", "which", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "Point2D_F64", "a", "=", "imageShape", ".", "get", "(", "i", ")", ";", "undistToDist", ".", "compute", "(", "a", ".", "x", ",", "a", ".", "y", ",", "f", ".", "distortedPixels", ".", "get", "(", "i", ")", ")", ";", "}", "}" ]
Takes the found quadrilateral and the computed 3D information and prepares it for output
[ "Takes", "the", "found", "quadrilateral", "and", "the", "computed", "3D", "information", "and", "prepares", "it", "for", "output" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/square/BaseDetectFiducialSquare.java#L397-L414
algolia/algoliasearch-client-java
src/main/java/com/algolia/search/saas/Index.java
Index.deleteObjects
public JSONObject deleteObjects(List<String> objects, RequestOptions requestOptions) throws AlgoliaException { """ Delete several objects @param objects the array of objectIDs to delete @param requestOptions Options to pass to this request """ try { JSONArray array = new JSONArray(); for (String id : objects) { JSONObject obj = new JSONObject(); obj.put("objectID", id); JSONObject action = new JSONObject(); action.put("action", "deleteObject"); action.put("body", obj); array.put(action); } return batch(array, requestOptions); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } }
java
public JSONObject deleteObjects(List<String> objects, RequestOptions requestOptions) throws AlgoliaException { try { JSONArray array = new JSONArray(); for (String id : objects) { JSONObject obj = new JSONObject(); obj.put("objectID", id); JSONObject action = new JSONObject(); action.put("action", "deleteObject"); action.put("body", obj); array.put(action); } return batch(array, requestOptions); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } }
[ "public", "JSONObject", "deleteObjects", "(", "List", "<", "String", ">", "objects", ",", "RequestOptions", "requestOptions", ")", "throws", "AlgoliaException", "{", "try", "{", "JSONArray", "array", "=", "new", "JSONArray", "(", ")", ";", "for", "(", "String", "id", ":", "objects", ")", "{", "JSONObject", "obj", "=", "new", "JSONObject", "(", ")", ";", "obj", ".", "put", "(", "\"objectID\"", ",", "id", ")", ";", "JSONObject", "action", "=", "new", "JSONObject", "(", ")", ";", "action", ".", "put", "(", "\"action\"", ",", "\"deleteObject\"", ")", ";", "action", ".", "put", "(", "\"body\"", ",", "obj", ")", ";", "array", ".", "put", "(", "action", ")", ";", "}", "return", "batch", "(", "array", ",", "requestOptions", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "throw", "new", "AlgoliaException", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Delete several objects @param objects the array of objectIDs to delete @param requestOptions Options to pass to this request
[ "Delete", "several", "objects" ]
train
https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L746-L761
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/exception/ContextedRuntimeException.java
ContextedRuntimeException.setContextValue
@Override public ContextedRuntimeException setContextValue(final String label, final Object value) { """ Sets information helpful to a developer in diagnosing and correcting the problem. For the information to be meaningful, the value passed should have a reasonable toString() implementation. Any existing values with the same labels are removed before the new one is added. <p> Note: This exception is only serializable if the object added as value is serializable. </p> @param label a textual label associated with information, {@code null} not recommended @param value information needed to understand exception, may be {@code null} @return {@code this}, for method chaining, not {@code null} """ exceptionContext.setContextValue(label, value); return this; }
java
@Override public ContextedRuntimeException setContextValue(final String label, final Object value) { exceptionContext.setContextValue(label, value); return this; }
[ "@", "Override", "public", "ContextedRuntimeException", "setContextValue", "(", "final", "String", "label", ",", "final", "Object", "value", ")", "{", "exceptionContext", ".", "setContextValue", "(", "label", ",", "value", ")", ";", "return", "this", ";", "}" ]
Sets information helpful to a developer in diagnosing and correcting the problem. For the information to be meaningful, the value passed should have a reasonable toString() implementation. Any existing values with the same labels are removed before the new one is added. <p> Note: This exception is only serializable if the object added as value is serializable. </p> @param label a textual label associated with information, {@code null} not recommended @param value information needed to understand exception, may be {@code null} @return {@code this}, for method chaining, not {@code null}
[ "Sets", "information", "helpful", "to", "a", "developer", "in", "diagnosing", "and", "correcting", "the", "problem", ".", "For", "the", "information", "to", "be", "meaningful", "the", "value", "passed", "should", "have", "a", "reasonable", "toString", "()", "implementation", ".", "Any", "existing", "values", "with", "the", "same", "labels", "are", "removed", "before", "the", "new", "one", "is", "added", ".", "<p", ">", "Note", ":", "This", "exception", "is", "only", "serializable", "if", "the", "object", "added", "as", "value", "is", "serializable", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/exception/ContextedRuntimeException.java#L191-L195
tvesalainen/util
ham/src/main/java/org/vesalainen/ham/itshfbc/GeoDB.java
GeoDB.isUnique
public static boolean isUnique(List<GeoLocation> list, double delta) { """ Returns true if greatest distance of any location from their center is less than given delta in nm. @param list @param delta @return """ Location[] array = new Location[list.size()]; int index = 0; for (GeoLocation gl : list) { array[index++] = gl.getLocation(); } return (Location.radius(array) <= delta); }
java
public static boolean isUnique(List<GeoLocation> list, double delta) { Location[] array = new Location[list.size()]; int index = 0; for (GeoLocation gl : list) { array[index++] = gl.getLocation(); } return (Location.radius(array) <= delta); }
[ "public", "static", "boolean", "isUnique", "(", "List", "<", "GeoLocation", ">", "list", ",", "double", "delta", ")", "{", "Location", "[", "]", "array", "=", "new", "Location", "[", "list", ".", "size", "(", ")", "]", ";", "int", "index", "=", "0", ";", "for", "(", "GeoLocation", "gl", ":", "list", ")", "{", "array", "[", "index", "++", "]", "=", "gl", ".", "getLocation", "(", ")", ";", "}", "return", "(", "Location", ".", "radius", "(", "array", ")", "<=", "delta", ")", ";", "}" ]
Returns true if greatest distance of any location from their center is less than given delta in nm. @param list @param delta @return
[ "Returns", "true", "if", "greatest", "distance", "of", "any", "location", "from", "their", "center", "is", "less", "than", "given", "delta", "in", "nm", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/ham/src/main/java/org/vesalainen/ham/itshfbc/GeoDB.java#L101-L110
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/ie/crf/CRFClassifier.java
CRFClassifier.loadClassifier
@Override @SuppressWarnings( { """ Loads a classifier from the specified InputStream. This version works quietly (unless VERBOSE is true). If props is non-null then any properties it specifies override those in the serialized file. However, only some properties are sensible to change (you shouldn't change how features are defined). <p> <i>Note:</i> This method does not close the ObjectInputStream. (But earlier versions of the code used to, so beware....) """ "unchecked" }) // can't have right types in deserialization public void loadClassifier(ObjectInputStream ois, Properties props) throws ClassCastException, IOException, ClassNotFoundException { labelIndices = (Index<CRFLabel>[]) ois.readObject(); classIndex = (Index<String>) ois.readObject(); featureIndex = (Index<String>) ois.readObject(); flags = (SeqClassifierFlags) ois.readObject(); featureFactory = (edu.stanford.nlp.sequences.FeatureFactory) ois.readObject(); if (props != null) { flags.setProperties(props, false); } reinit(); windowSize = ois.readInt(); weights = (double[][]) ois.readObject(); // WordShapeClassifier.setKnownLowerCaseWords((Set) ois.readObject()); knownLCWords = (Set<String>) ois.readObject(); if (VERBOSE) { System.err.println("windowSize=" + windowSize); System.err.println("flags=\n" + flags); } }
java
@Override @SuppressWarnings( { "unchecked" }) // can't have right types in deserialization public void loadClassifier(ObjectInputStream ois, Properties props) throws ClassCastException, IOException, ClassNotFoundException { labelIndices = (Index<CRFLabel>[]) ois.readObject(); classIndex = (Index<String>) ois.readObject(); featureIndex = (Index<String>) ois.readObject(); flags = (SeqClassifierFlags) ois.readObject(); featureFactory = (edu.stanford.nlp.sequences.FeatureFactory) ois.readObject(); if (props != null) { flags.setProperties(props, false); } reinit(); windowSize = ois.readInt(); weights = (double[][]) ois.readObject(); // WordShapeClassifier.setKnownLowerCaseWords((Set) ois.readObject()); knownLCWords = (Set<String>) ois.readObject(); if (VERBOSE) { System.err.println("windowSize=" + windowSize); System.err.println("flags=\n" + flags); } }
[ "@", "Override", "@", "SuppressWarnings", "(", "{", "\"unchecked\"", "}", ")", "// can't have right types in deserialization\r", "public", "void", "loadClassifier", "(", "ObjectInputStream", "ois", ",", "Properties", "props", ")", "throws", "ClassCastException", ",", "IOException", ",", "ClassNotFoundException", "{", "labelIndices", "=", "(", "Index", "<", "CRFLabel", ">", "[", "]", ")", "ois", ".", "readObject", "(", ")", ";", "classIndex", "=", "(", "Index", "<", "String", ">", ")", "ois", ".", "readObject", "(", ")", ";", "featureIndex", "=", "(", "Index", "<", "String", ">", ")", "ois", ".", "readObject", "(", ")", ";", "flags", "=", "(", "SeqClassifierFlags", ")", "ois", ".", "readObject", "(", ")", ";", "featureFactory", "=", "(", "edu", ".", "stanford", ".", "nlp", ".", "sequences", ".", "FeatureFactory", ")", "ois", ".", "readObject", "(", ")", ";", "if", "(", "props", "!=", "null", ")", "{", "flags", ".", "setProperties", "(", "props", ",", "false", ")", ";", "}", "reinit", "(", ")", ";", "windowSize", "=", "ois", ".", "readInt", "(", ")", ";", "weights", "=", "(", "double", "[", "]", "[", "]", ")", "ois", ".", "readObject", "(", ")", ";", "// WordShapeClassifier.setKnownLowerCaseWords((Set) ois.readObject());\r", "knownLCWords", "=", "(", "Set", "<", "String", ">", ")", "ois", ".", "readObject", "(", ")", ";", "if", "(", "VERBOSE", ")", "{", "System", ".", "err", ".", "println", "(", "\"windowSize=\"", "+", "windowSize", ")", ";", "System", ".", "err", ".", "println", "(", "\"flags=\\n\"", "+", "flags", ")", ";", "}", "}" ]
Loads a classifier from the specified InputStream. This version works quietly (unless VERBOSE is true). If props is non-null then any properties it specifies override those in the serialized file. However, only some properties are sensible to change (you shouldn't change how features are defined). <p> <i>Note:</i> This method does not close the ObjectInputStream. (But earlier versions of the code used to, so beware....)
[ "Loads", "a", "classifier", "from", "the", "specified", "InputStream", ".", "This", "version", "works", "quietly", "(", "unless", "VERBOSE", "is", "true", ")", ".", "If", "props", "is", "non", "-", "null", "then", "any", "properties", "it", "specifies", "override", "those", "in", "the", "serialized", "file", ".", "However", "only", "some", "properties", "are", "sensible", "to", "change", "(", "you", "shouldn", "t", "change", "how", "features", "are", "defined", ")", ".", "<p", ">", "<i", ">", "Note", ":", "<", "/", "i", ">", "This", "method", "does", "not", "close", "the", "ObjectInputStream", ".", "(", "But", "earlier", "versions", "of", "the", "code", "used", "to", "so", "beware", "....", ")" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/ie/crf/CRFClassifier.java#L2246-L2272
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/StreamTokenizer.java
StreamTokenizer.ordinaryChars
public void ordinaryChars(int low, int hi) { """ Specifies that the characters in the range from {@code low} to {@code hi} shall be treated as an ordinary character by this tokenizer. That is, they have no special meaning as a comment character, word component, white space, string delimiter or number. @param low the first character in the range of ordinary characters. @param hi the last character in the range of ordinary characters. """ if (low < 0) { low = 0; } if (hi > tokenTypes.length) { hi = tokenTypes.length - 1; } for (int i = low; i <= hi; i++) { tokenTypes[i] = 0; } }
java
public void ordinaryChars(int low, int hi) { if (low < 0) { low = 0; } if (hi > tokenTypes.length) { hi = tokenTypes.length - 1; } for (int i = low; i <= hi; i++) { tokenTypes[i] = 0; } }
[ "public", "void", "ordinaryChars", "(", "int", "low", ",", "int", "hi", ")", "{", "if", "(", "low", "<", "0", ")", "{", "low", "=", "0", ";", "}", "if", "(", "hi", ">", "tokenTypes", ".", "length", ")", "{", "hi", "=", "tokenTypes", ".", "length", "-", "1", ";", "}", "for", "(", "int", "i", "=", "low", ";", "i", "<=", "hi", ";", "i", "++", ")", "{", "tokenTypes", "[", "i", "]", "=", "0", ";", "}", "}" ]
Specifies that the characters in the range from {@code low} to {@code hi} shall be treated as an ordinary character by this tokenizer. That is, they have no special meaning as a comment character, word component, white space, string delimiter or number. @param low the first character in the range of ordinary characters. @param hi the last character in the range of ordinary characters.
[ "Specifies", "that", "the", "characters", "in", "the", "range", "from", "{", "@code", "low", "}", "to", "{", "@code", "hi", "}", "shall", "be", "treated", "as", "an", "ordinary", "character", "by", "this", "tokenizer", ".", "That", "is", "they", "have", "no", "special", "meaning", "as", "a", "comment", "character", "word", "component", "white", "space", "string", "delimiter", "or", "number", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/StreamTokenizer.java#L509-L519