repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
196
func_name
stringlengths
7
107
whole_func_string
stringlengths
76
3.82k
language
stringclasses
1 value
func_code_string
stringlengths
76
3.82k
func_code_tokens
listlengths
22
717
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
508
split_name
stringclasses
1 value
func_code_url
stringlengths
111
310
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.deleteLabel
public void deleteLabel(Serializable projectId, String name) throws IOException { Query query = new Query(); query.append("name", name); String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabLabel.URL + query.toString(); retrieve().method(DELETE).to(tailUrl, Void.class); }
java
public void deleteLabel(Serializable projectId, String name) throws IOException { Query query = new Query(); query.append("name", name); String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabLabel.URL + query.toString(); retrieve().method(DELETE).to(tailUrl, Void.class); }
[ "public", "void", "deleteLabel", "(", "Serializable", "projectId", ",", "String", "name", ")", "throws", "IOException", "{", "Query", "query", "=", "new", "Query", "(", ")", ";", "query", ".", "append", "(", "\"name\"", ",", "name", ")", ";", "String", "...
Deletes an existing label. @param projectId The ID of the project containing the label. @param name The name of the label to delete. @throws IOException on gitlab api call error
[ "Deletes", "an", "existing", "label", "." ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2817-L2826
jhunters/jprotobuf
android/src/main/java/com/baidu/bjf/remoting/protobuf/utils/FieldUtils.java
FieldUtils.setField
public static void setField(Object t, String name, Object value) { Field field = findField(t.getClass(), name); setField(t, field, value); }
java
public static void setField(Object t, String name, Object value) { Field field = findField(t.getClass(), name); setField(t, field, value); }
[ "public", "static", "void", "setField", "(", "Object", "t", ",", "String", "name", ",", "Object", "value", ")", "{", "Field", "field", "=", "findField", "(", "t", ".", "getClass", "(", ")", ",", "name", ")", ";", "setField", "(", "t", ",", "field", ...
Set the field represented by the supplied {@link Field field object} on the specified {@link Object target object} to the specified <code>value</code>. In accordance with {@link Field#set(Object, Object)} semantics, the new value is automatically unwrapped if the underlying field has a primitive type. <p> Thrown exceptions are handled via a call to @param t the target object on which to set the field @param name the field to set @param value the value to set; may be <code>null</code>
[ "Set", "the", "field", "represented", "by", "the", "supplied", "{", "@link", "Field", "field", "object", "}", "on", "the", "specified", "{", "@link", "Object", "target", "object", "}", "to", "the", "specified", "<code", ">", "value<", "/", "code", ">", "...
train
https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/android/src/main/java/com/baidu/bjf/remoting/protobuf/utils/FieldUtils.java#L133-L136
wisdom-framework/wisdom
framework/resource-controller/src/main/java/org/wisdom/resources/CacheUtils.java
CacheUtils.addLastModified
public static void addLastModified(Result result, long lastModified) { result.with(HeaderNames.LAST_MODIFIED, DateUtil.formatForHttpHeader(lastModified)); }
java
public static void addLastModified(Result result, long lastModified) { result.with(HeaderNames.LAST_MODIFIED, DateUtil.formatForHttpHeader(lastModified)); }
[ "public", "static", "void", "addLastModified", "(", "Result", "result", ",", "long", "lastModified", ")", "{", "result", ".", "with", "(", "HeaderNames", ".", "LAST_MODIFIED", ",", "DateUtil", ".", "formatForHttpHeader", "(", "lastModified", ")", ")", ";", "}"...
Add the last modified header to the given result. This method handle the HTTP Date format. @param result the result @param lastModified the date
[ "Add", "the", "last", "modified", "header", "to", "the", "given", "result", ".", "This", "method", "handle", "the", "HTTP", "Date", "format", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/resource-controller/src/main/java/org/wisdom/resources/CacheUtils.java#L61-L63
phax/ph-commons
ph-xml/src/main/java/com/helger/xml/serialize/write/AbstractXMLSerializer.java
AbstractXMLSerializer.handlePutNamespaceContextPrefixInRoot
protected final void handlePutNamespaceContextPrefixInRoot (@Nonnull final Map <QName, String> aAttrMap) { if (m_aSettings.isEmitNamespaces () && m_aNSStack.size () == 1 && m_aSettings.isPutNamespaceContextPrefixesInRoot ()) { // The only place where the namespace context prefixes are added to the // root element for (final Map.Entry <String, String> aEntry : m_aRootNSMap.entrySet ()) { aAttrMap.put (XMLHelper.getXMLNSAttrQName (aEntry.getKey ()), aEntry.getValue ()); m_aNSStack.addNamespaceMapping (aEntry.getKey (), aEntry.getValue ()); } } }
java
protected final void handlePutNamespaceContextPrefixInRoot (@Nonnull final Map <QName, String> aAttrMap) { if (m_aSettings.isEmitNamespaces () && m_aNSStack.size () == 1 && m_aSettings.isPutNamespaceContextPrefixesInRoot ()) { // The only place where the namespace context prefixes are added to the // root element for (final Map.Entry <String, String> aEntry : m_aRootNSMap.entrySet ()) { aAttrMap.put (XMLHelper.getXMLNSAttrQName (aEntry.getKey ()), aEntry.getValue ()); m_aNSStack.addNamespaceMapping (aEntry.getKey (), aEntry.getValue ()); } } }
[ "protected", "final", "void", "handlePutNamespaceContextPrefixInRoot", "(", "@", "Nonnull", "final", "Map", "<", "QName", ",", "String", ">", "aAttrMap", ")", "{", "if", "(", "m_aSettings", ".", "isEmitNamespaces", "(", ")", "&&", "m_aNSStack", ".", "size", "(...
This method handles the case, if all namespace context entries should be emitted on the root element. @param aAttrMap
[ "This", "method", "handles", "the", "case", "if", "all", "namespace", "context", "entries", "should", "be", "emitted", "on", "the", "root", "element", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/serialize/write/AbstractXMLSerializer.java#L498-L512
OpenLiberty/open-liberty
dev/com.ibm.ws.request.probes/src/com/ibm/wsspi/request/probe/bci/TransformDescriptorHelper.java
TransformDescriptorHelper.contextInfoRequired
public boolean contextInfoRequired(String eventType, long requestNumber) { boolean needContextInfo = false; List<ProbeExtension> probeExtnList = RequestProbeService .getProbeExtensions(); for (int i = 0; i < probeExtnList.size(); i++) { ProbeExtension probeExtension = probeExtnList.get(i); if (requestNumber % probeExtension.getRequestSampleRate() == 0) { if (probeExtension.getContextInfoRequirement() == ContextInfoRequirement.ALL_EVENTS) { needContextInfo = true; break; } else if (probeExtension.getContextInfoRequirement() == ContextInfoRequirement.EVENTS_MATCHING_SPECIFIED_EVENT_TYPES && (probeExtension.invokeForEventTypes() == null || probeExtension .invokeForEventTypes().contains(eventType))) { needContextInfo = true; break; } } } return needContextInfo; }
java
public boolean contextInfoRequired(String eventType, long requestNumber) { boolean needContextInfo = false; List<ProbeExtension> probeExtnList = RequestProbeService .getProbeExtensions(); for (int i = 0; i < probeExtnList.size(); i++) { ProbeExtension probeExtension = probeExtnList.get(i); if (requestNumber % probeExtension.getRequestSampleRate() == 0) { if (probeExtension.getContextInfoRequirement() == ContextInfoRequirement.ALL_EVENTS) { needContextInfo = true; break; } else if (probeExtension.getContextInfoRequirement() == ContextInfoRequirement.EVENTS_MATCHING_SPECIFIED_EVENT_TYPES && (probeExtension.invokeForEventTypes() == null || probeExtension .invokeForEventTypes().contains(eventType))) { needContextInfo = true; break; } } } return needContextInfo; }
[ "public", "boolean", "contextInfoRequired", "(", "String", "eventType", ",", "long", "requestNumber", ")", "{", "boolean", "needContextInfo", "=", "false", ";", "List", "<", "ProbeExtension", ">", "probeExtnList", "=", "RequestProbeService", ".", "getProbeExtensions",...
This method will check if context information is required or not by processing through each active ProbeExtensions available in PE List @param eventType @return
[ "This", "method", "will", "check", "if", "context", "information", "is", "required", "or", "not", "by", "processing", "through", "each", "active", "ProbeExtensions", "available", "in", "PE", "List" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.request.probes/src/com/ibm/wsspi/request/probe/bci/TransformDescriptorHelper.java#L45-L68
metamx/java-util
src/main/java/com/metamx/emitter/core/HttpPostEmitter.java
HttpPostEmitter.onSealExclusive
void onSealExclusive(Batch batch, long elapsedTimeMillis) { batchFillingTimeCounter.add((int) Math.max(elapsedTimeMillis, 0)); if (elapsedTimeMillis > 0) { // If elapsedTimeMillis is 0 or negative, it's likely because System.currentTimeMillis() is not monotonic, so not // accounting this time for determining batch sending timeout. lastFillTimeMillis = elapsedTimeMillis; } addBatchToEmitQueue(batch); wakeUpEmittingThread(); if (!isTerminated()) { int nextBatchNumber = EmittedBatchCounter.nextBatchNumber(batch.batchNumber); if (!concurrentBatch.compareAndSet(batch, new Batch(this, acquireBuffer(), nextBatchNumber))) { // If compareAndSet failed, the service is closed concurrently. Preconditions.checkState(isTerminated()); } } }
java
void onSealExclusive(Batch batch, long elapsedTimeMillis) { batchFillingTimeCounter.add((int) Math.max(elapsedTimeMillis, 0)); if (elapsedTimeMillis > 0) { // If elapsedTimeMillis is 0 or negative, it's likely because System.currentTimeMillis() is not monotonic, so not // accounting this time for determining batch sending timeout. lastFillTimeMillis = elapsedTimeMillis; } addBatchToEmitQueue(batch); wakeUpEmittingThread(); if (!isTerminated()) { int nextBatchNumber = EmittedBatchCounter.nextBatchNumber(batch.batchNumber); if (!concurrentBatch.compareAndSet(batch, new Batch(this, acquireBuffer(), nextBatchNumber))) { // If compareAndSet failed, the service is closed concurrently. Preconditions.checkState(isTerminated()); } } }
[ "void", "onSealExclusive", "(", "Batch", "batch", ",", "long", "elapsedTimeMillis", ")", "{", "batchFillingTimeCounter", ".", "add", "(", "(", "int", ")", "Math", ".", "max", "(", "elapsedTimeMillis", ",", "0", ")", ")", ";", "if", "(", "elapsedTimeMillis", ...
Called from {@link Batch} only once for each Batch in existence.
[ "Called", "from", "{" ]
train
https://github.com/metamx/java-util/blob/9d204043da1136e94fb2e2d63e3543a29bf54b4d/src/main/java/com/metamx/emitter/core/HttpPostEmitter.java#L283-L300
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WCheckBoxSelectExample.java
WCheckBoxSelectExample.addSingleColumnSelectExample
private void addSingleColumnSelectExample() { add(new WHeading(HeadingLevel.H3, "WCheckBoxSelect laid out in a single column")); add(new ExplanatoryText("When layout is COLUMN, setting the layoutColumnCount property to one, or forgetting to set it at all (default is " + "one) is a little bit pointless.")); final WCheckBoxSelect select = new WCheckBoxSelect("australian_state"); select.setToolTip("Make a selection"); select.setButtonLayout(WCheckBoxSelect.LAYOUT_COLUMNS); add(select); }
java
private void addSingleColumnSelectExample() { add(new WHeading(HeadingLevel.H3, "WCheckBoxSelect laid out in a single column")); add(new ExplanatoryText("When layout is COLUMN, setting the layoutColumnCount property to one, or forgetting to set it at all (default is " + "one) is a little bit pointless.")); final WCheckBoxSelect select = new WCheckBoxSelect("australian_state"); select.setToolTip("Make a selection"); select.setButtonLayout(WCheckBoxSelect.LAYOUT_COLUMNS); add(select); }
[ "private", "void", "addSingleColumnSelectExample", "(", ")", "{", "add", "(", "new", "WHeading", "(", "HeadingLevel", ".", "H3", ",", "\"WCheckBoxSelect laid out in a single column\"", ")", ")", ";", "add", "(", "new", "ExplanatoryText", "(", "\"When layout is COLUMN,...
adds a WCheckBoxSelect with LAYOUT_COLUMN in 1 column simply by not setting the number of columns. This is superfluous as you should use LAYOUT_STACKED (the default) instead.
[ "adds", "a", "WCheckBoxSelect", "with", "LAYOUT_COLUMN", "in", "1", "column", "simply", "by", "not", "setting", "the", "number", "of", "columns", ".", "This", "is", "superfluous", "as", "you", "should", "use", "LAYOUT_STACKED", "(", "the", "default", ")", "i...
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WCheckBoxSelectExample.java#L263-L271
kochedykov/jlibmodbus
src/com/intelligt/modbus/jlibmodbus/master/ModbusMaster.java
ModbusMaster.writeSingleRegister
final public void writeSingleRegister(int serverAddress, int startAddress, int register) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { processRequest(ModbusRequestBuilder.getInstance().buildWriteSingleRegister(serverAddress, startAddress, register)); }
java
final public void writeSingleRegister(int serverAddress, int startAddress, int register) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { processRequest(ModbusRequestBuilder.getInstance().buildWriteSingleRegister(serverAddress, startAddress, register)); }
[ "final", "public", "void", "writeSingleRegister", "(", "int", "serverAddress", ",", "int", "startAddress", ",", "int", "register", ")", "throws", "ModbusProtocolException", ",", "ModbusNumberException", ",", "ModbusIOException", "{", "processRequest", "(", "ModbusReques...
This function code is used to write a single holding register in a remote device. The Request PDU specifies the address of the register to be written. Registers are addressed starting at zero. Therefore register numbered 1 is addressed as 0. @param serverAddress a slave address @param startAddress the address of the register to be written @param register value @throws ModbusProtocolException if modbus-exception is received @throws ModbusNumberException if response is invalid @throws ModbusIOException if remote slave is unavailable
[ "This", "function", "code", "is", "used", "to", "write", "a", "single", "holding", "register", "in", "a", "remote", "device", ".", "The", "Request", "PDU", "specifies", "the", "address", "of", "the", "register", "to", "be", "written", ".", "Registers", "ar...
train
https://github.com/kochedykov/jlibmodbus/blob/197cb39e2649e61a6fe3cb7dc91a701d847e14be/src/com/intelligt/modbus/jlibmodbus/master/ModbusMaster.java#L300-L303
apache/reef
lang/java/reef-tang/tang/src/main/java/org/apache/reef/tang/formats/ConfigurationModule.java
ConfigurationModule.set
public final <T> ConfigurationModule set(final Impl<List> opt, final List implList) { final ConfigurationModule c = deepCopy(); c.processSet(opt); c.setImplLists.put(opt, implList); return c; }
java
public final <T> ConfigurationModule set(final Impl<List> opt, final List implList) { final ConfigurationModule c = deepCopy(); c.processSet(opt); c.setImplLists.put(opt, implList); return c; }
[ "public", "final", "<", "T", ">", "ConfigurationModule", "set", "(", "final", "Impl", "<", "List", ">", "opt", ",", "final", "List", "implList", ")", "{", "final", "ConfigurationModule", "c", "=", "deepCopy", "(", ")", ";", "c", ".", "processSet", "(", ...
Binds a list to a specific optional/required Impl using ConfigurationModule. @param opt Target optional/required Impl @param implList List object to be injected @param <T> a type @return the configuration module
[ "Binds", "a", "list", "to", "a", "specific", "optional", "/", "required", "Impl", "using", "ConfigurationModule", "." ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-tang/tang/src/main/java/org/apache/reef/tang/formats/ConfigurationModule.java#L126-L131
Netflix/servo
servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java
Monitors.newCounter
public static Counter newCounter(String name, TaggingContext context) { final MonitorConfig config = MonitorConfig.builder(name).build(); return new ContextualCounter(config, context, COUNTER_FUNCTION); }
java
public static Counter newCounter(String name, TaggingContext context) { final MonitorConfig config = MonitorConfig.builder(name).build(); return new ContextualCounter(config, context, COUNTER_FUNCTION); }
[ "public", "static", "Counter", "newCounter", "(", "String", "name", ",", "TaggingContext", "context", ")", "{", "final", "MonitorConfig", "config", "=", "MonitorConfig", ".", "builder", "(", "name", ")", ".", "build", "(", ")", ";", "return", "new", "Context...
Create a new counter with a name and context. The returned counter will maintain separate sub-monitors for each distinct set of tags returned from the context on an update operation.
[ "Create", "a", "new", "counter", "with", "a", "name", "and", "context", ".", "The", "returned", "counter", "will", "maintain", "separate", "sub", "-", "monitors", "for", "each", "distinct", "set", "of", "tags", "returned", "from", "the", "context", "on", "...
train
https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L121-L124
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/AsyncHbaseSchemaService.java
AsyncHbaseSchemaService._getUniqueFastScan
private List<MetricSchemaRecord> _getUniqueFastScan(MetricSchemaRecordQuery query, final RecordType type) { requireNotDisposed(); SystemAssert.requireArgument(RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type), "This method is only for use with metric or scope."); _logger.info("Using FastScan. Will skip rows while scanning."); final Set<MetricSchemaRecord> records = new HashSet<>(); final ScanMetadata metadata = _constructScanMetadata(query); String namespace = SchemaService.convertToRegex(query.getNamespace()); String scope = SchemaService.convertToRegex(query.getScope()); String metric = SchemaService.convertToRegex(query.getMetric()); String tagKey = SchemaService.convertToRegex(query.getTagKey()); String tagValue = SchemaService.convertToRegex(query.getTagValue()); MetricSchemaRecord scanFrom = query.getScanFrom(); String rowKeyRegex = "^" + _constructRowKey(namespace, scope, metric, tagKey, tagValue, metadata.tableName) + "$"; List<ScanFilter> filters = new ArrayList<ScanFilter>(); filters.add(new RowFilter(CompareOp.EQUAL, new RegexStringComparator(rowKeyRegex))); filters.add(new KeyOnlyFilter()); filters.add(new FirstKeyOnlyFilter()); FilterList filterList = new FilterList(filters, FilterList.Operator.MUST_PASS_ALL); String start = scanFrom == null ? Bytes.toString(metadata.startRow) : _plusOneNConstructRowKey(scanFrom, metadata.tableName, type); String end = Bytes.toString(metadata.stopRow); ArrayList<ArrayList<KeyValue>> rows = _getSingleRow(start, end, filterList, metadata.tableName); while(rows != null && !rows.isEmpty()) { String rowKey = Bytes.toString(rows.get(0).get(0).key()); String splits[] = rowKey.split(String.valueOf(ROWKEY_SEPARATOR)); String record = (RecordType.METRIC.equals(type) && metadata.tableName.equals(METRIC_SCHEMA_TABLENAME)) || (RecordType.SCOPE.equals(type) && metadata.tableName.equals(SCOPE_SCHEMA_TABLENAME)) ? splits[0] : splits[1]; MetricSchemaRecord schemaRecord = RecordType.METRIC.equals(type) ? new MetricSchemaRecord(null, record) : new MetricSchemaRecord(record, null); records.add(schemaRecord); if(records.size() == query.getLimit()) { break; } String newScanStart; if(!SchemaService.containsFilter(query.getScope()) || !SchemaService.containsFilter(query.getMetric())) { newScanStart = _plusOne(record); } else { newScanStart = _plusOne(splits[0] + ROWKEY_SEPARATOR + splits[1]); } rows = _getSingleRow(newScanStart, end, filterList, metadata.tableName); } return new ArrayList<>(records); }
java
private List<MetricSchemaRecord> _getUniqueFastScan(MetricSchemaRecordQuery query, final RecordType type) { requireNotDisposed(); SystemAssert.requireArgument(RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type), "This method is only for use with metric or scope."); _logger.info("Using FastScan. Will skip rows while scanning."); final Set<MetricSchemaRecord> records = new HashSet<>(); final ScanMetadata metadata = _constructScanMetadata(query); String namespace = SchemaService.convertToRegex(query.getNamespace()); String scope = SchemaService.convertToRegex(query.getScope()); String metric = SchemaService.convertToRegex(query.getMetric()); String tagKey = SchemaService.convertToRegex(query.getTagKey()); String tagValue = SchemaService.convertToRegex(query.getTagValue()); MetricSchemaRecord scanFrom = query.getScanFrom(); String rowKeyRegex = "^" + _constructRowKey(namespace, scope, metric, tagKey, tagValue, metadata.tableName) + "$"; List<ScanFilter> filters = new ArrayList<ScanFilter>(); filters.add(new RowFilter(CompareOp.EQUAL, new RegexStringComparator(rowKeyRegex))); filters.add(new KeyOnlyFilter()); filters.add(new FirstKeyOnlyFilter()); FilterList filterList = new FilterList(filters, FilterList.Operator.MUST_PASS_ALL); String start = scanFrom == null ? Bytes.toString(metadata.startRow) : _plusOneNConstructRowKey(scanFrom, metadata.tableName, type); String end = Bytes.toString(metadata.stopRow); ArrayList<ArrayList<KeyValue>> rows = _getSingleRow(start, end, filterList, metadata.tableName); while(rows != null && !rows.isEmpty()) { String rowKey = Bytes.toString(rows.get(0).get(0).key()); String splits[] = rowKey.split(String.valueOf(ROWKEY_SEPARATOR)); String record = (RecordType.METRIC.equals(type) && metadata.tableName.equals(METRIC_SCHEMA_TABLENAME)) || (RecordType.SCOPE.equals(type) && metadata.tableName.equals(SCOPE_SCHEMA_TABLENAME)) ? splits[0] : splits[1]; MetricSchemaRecord schemaRecord = RecordType.METRIC.equals(type) ? new MetricSchemaRecord(null, record) : new MetricSchemaRecord(record, null); records.add(schemaRecord); if(records.size() == query.getLimit()) { break; } String newScanStart; if(!SchemaService.containsFilter(query.getScope()) || !SchemaService.containsFilter(query.getMetric())) { newScanStart = _plusOne(record); } else { newScanStart = _plusOne(splits[0] + ROWKEY_SEPARATOR + splits[1]); } rows = _getSingleRow(newScanStart, end, filterList, metadata.tableName); } return new ArrayList<>(records); }
[ "private", "List", "<", "MetricSchemaRecord", ">", "_getUniqueFastScan", "(", "MetricSchemaRecordQuery", "query", ",", "final", "RecordType", "type", ")", "{", "requireNotDisposed", "(", ")", ";", "SystemAssert", ".", "requireArgument", "(", "RecordType", ".", "METR...
Fast scan works when trying to discover either scopes or metrics with all other fields being *. In this case, when the first result is obtained, we skip all other rows starting with that prefix and directly move on to the next possible value which is obtained value incremented by 1 Ascii character. If that value exists, then it is returned, otherwise HBase returns the next possible value in lexicographical order. For e.g. suppose if we have the following rows in HBase: scope\0metric1\0$\0$\0$ scope\0metric2\0$\0$\0$ . . . scope\0metric1000\0$\0$\0$ scopu\0metric1\0$\0$\0$ scopu\0metric2\0$\0$\0$ . . . scopu\0metric1000\0$\0$\0$ And our start row is "sco", then this method would first find "scope" and then jump the next 1000 rows to start from the next possible value of scopf. Since nothing like scopf exists, HBase would directly jump to scopu and return that.
[ "Fast", "scan", "works", "when", "trying", "to", "discover", "either", "scopes", "or", "metrics", "with", "all", "other", "fields", "being", "*", ".", "In", "this", "case", "when", "the", "first", "result", "is", "obtained", "we", "skip", "all", "other", ...
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/AsyncHbaseSchemaService.java#L346-L400
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/application/AbstractApplication.java
AbstractApplication.addCSS
protected void addCSS(final Scene scene, final StyleSheetItem styleSheetItem) { final URL styleSheetURL = styleSheetItem.get(); if (styleSheetURL == null) { LOGGER.error(CSS_LOADING_ERROR, styleSheetItem.toString(), ResourceParameters.STYLE_FOLDER.get()); } else { scene.getStylesheets().add(styleSheetURL.toExternalForm()); } }
java
protected void addCSS(final Scene scene, final StyleSheetItem styleSheetItem) { final URL styleSheetURL = styleSheetItem.get(); if (styleSheetURL == null) { LOGGER.error(CSS_LOADING_ERROR, styleSheetItem.toString(), ResourceParameters.STYLE_FOLDER.get()); } else { scene.getStylesheets().add(styleSheetURL.toExternalForm()); } }
[ "protected", "void", "addCSS", "(", "final", "Scene", "scene", ",", "final", "StyleSheetItem", "styleSheetItem", ")", "{", "final", "URL", "styleSheetURL", "=", "styleSheetItem", ".", "get", "(", ")", ";", "if", "(", "styleSheetURL", "==", "null", ")", "{", ...
Attach a new CSS file to the scene using the default classloader. @param scene the scene that will hold this new CSS file @param styleSheetItem the stylesheet item to add
[ "Attach", "a", "new", "CSS", "file", "to", "the", "scene", "using", "the", "default", "classloader", "." ]
train
https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/application/AbstractApplication.java#L456-L465
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/visualizers/scatterplot/selection/DistanceFunctionVisualization.java
DistanceFunctionVisualization.drawCosine
public static Element drawCosine(SVGPlot svgp, Projection2D proj, NumberVector mid, double angle) { // Project origin double[] pointOfOrigin = proj.fastProjectDataToRenderSpace(new double[proj.getInputDimensionality()]); // direction of the selected Point double[] selPoint = proj.fastProjectDataToRenderSpace(mid); double[] range1, range2; { // Rotation plane: double[] pm = mid.toArray(); // Compute relative vectors double[] p1 = minusEquals(proj.fastProjectRenderToDataSpace(selPoint[0] + 10, selPoint[1]), pm); double[] p2 = minusEquals(proj.fastProjectRenderToDataSpace(selPoint[0], selPoint[1] + 10), pm); // Scale p1 and p2 to unit length: timesEquals(p1, 1. / euclideanLength(p1)); timesEquals(p2, 1. / euclideanLength(p2)); if(Math.abs(scalarProduct(p1, p2)) > 1E-10) { LoggingUtil.warning("Projection does not seem to be orthogonal?"); } // Project onto p1, p2: double l1 = scalarProduct(pm, p1), l2 = scalarProduct(pm, p2); // Rotate projection by + and - angle // Using sin(-x) = -sin(x) and cos(-x)=cos(x) final DoubleWrapper tmp = new DoubleWrapper(); // To return cosine final double sangle = FastMath.sinAndCos(angle, tmp), cangle = tmp.value; double r11 = +cangle * l1 - sangle * l2, r12 = +sangle * l1 + cangle * l2; double r21 = +cangle * l1 + sangle * l2, r22 = -sangle * l1 + cangle * l2; // Build rotated vectors - remove projected component, add rotated // component: double[] r1 = plusTimesEquals(plusTimes(pm, p1, -l1 + r11), p2, -l2 + r12); double[] r2 = plusTimesEquals(plusTimes(pm, p1, -l1 + r21), p2, -l2 + r22); // Project to render space: range1 = proj.fastProjectDataToRenderSpace(r1); range2 = proj.fastProjectDataToRenderSpace(r2); } // Continue lines to viewport. { CanvasSize viewport = proj.estimateViewport(); minusEquals(range1, pointOfOrigin); plusEquals(timesEquals(range1, viewport.continueToMargin(pointOfOrigin, range1)), pointOfOrigin); minusEquals(range2, pointOfOrigin); plusEquals(timesEquals(range2, viewport.continueToMargin(pointOfOrigin, range2)), pointOfOrigin); // Go backwards into the other direction - the origin might not be in the // viewport! double[] start1 = minus(pointOfOrigin, range1); plusEquals(timesEquals(start1, viewport.continueToMargin(range1, start1)), range1); double[] start2 = minus(pointOfOrigin, range2); plusEquals(timesEquals(start2, viewport.continueToMargin(range2, start2)), range2); // TODO: add filled variant? return new SVGPath().moveTo(start1).lineTo(range1).moveTo(start2).lineTo(range2).makeElement(svgp); } }
java
public static Element drawCosine(SVGPlot svgp, Projection2D proj, NumberVector mid, double angle) { // Project origin double[] pointOfOrigin = proj.fastProjectDataToRenderSpace(new double[proj.getInputDimensionality()]); // direction of the selected Point double[] selPoint = proj.fastProjectDataToRenderSpace(mid); double[] range1, range2; { // Rotation plane: double[] pm = mid.toArray(); // Compute relative vectors double[] p1 = minusEquals(proj.fastProjectRenderToDataSpace(selPoint[0] + 10, selPoint[1]), pm); double[] p2 = minusEquals(proj.fastProjectRenderToDataSpace(selPoint[0], selPoint[1] + 10), pm); // Scale p1 and p2 to unit length: timesEquals(p1, 1. / euclideanLength(p1)); timesEquals(p2, 1. / euclideanLength(p2)); if(Math.abs(scalarProduct(p1, p2)) > 1E-10) { LoggingUtil.warning("Projection does not seem to be orthogonal?"); } // Project onto p1, p2: double l1 = scalarProduct(pm, p1), l2 = scalarProduct(pm, p2); // Rotate projection by + and - angle // Using sin(-x) = -sin(x) and cos(-x)=cos(x) final DoubleWrapper tmp = new DoubleWrapper(); // To return cosine final double sangle = FastMath.sinAndCos(angle, tmp), cangle = tmp.value; double r11 = +cangle * l1 - sangle * l2, r12 = +sangle * l1 + cangle * l2; double r21 = +cangle * l1 + sangle * l2, r22 = -sangle * l1 + cangle * l2; // Build rotated vectors - remove projected component, add rotated // component: double[] r1 = plusTimesEquals(plusTimes(pm, p1, -l1 + r11), p2, -l2 + r12); double[] r2 = plusTimesEquals(plusTimes(pm, p1, -l1 + r21), p2, -l2 + r22); // Project to render space: range1 = proj.fastProjectDataToRenderSpace(r1); range2 = proj.fastProjectDataToRenderSpace(r2); } // Continue lines to viewport. { CanvasSize viewport = proj.estimateViewport(); minusEquals(range1, pointOfOrigin); plusEquals(timesEquals(range1, viewport.continueToMargin(pointOfOrigin, range1)), pointOfOrigin); minusEquals(range2, pointOfOrigin); plusEquals(timesEquals(range2, viewport.continueToMargin(pointOfOrigin, range2)), pointOfOrigin); // Go backwards into the other direction - the origin might not be in the // viewport! double[] start1 = minus(pointOfOrigin, range1); plusEquals(timesEquals(start1, viewport.continueToMargin(range1, start1)), range1); double[] start2 = minus(pointOfOrigin, range2); plusEquals(timesEquals(start2, viewport.continueToMargin(range2, start2)), range2); // TODO: add filled variant? return new SVGPath().moveTo(start1).lineTo(range1).moveTo(start2).lineTo(range2).makeElement(svgp); } }
[ "public", "static", "Element", "drawCosine", "(", "SVGPlot", "svgp", ",", "Projection2D", "proj", ",", "NumberVector", "mid", ",", "double", "angle", ")", "{", "// Project origin", "double", "[", "]", "pointOfOrigin", "=", "proj", ".", "fastProjectDataToRenderSpac...
Visualizes Cosine and ArcCosine distance functions @param svgp SVG Plot @param proj Visualization projection @param mid mean vector @param angle Opening angle in radians @return path element
[ "Visualizes", "Cosine", "and", "ArcCosine", "distance", "functions" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/visualizers/scatterplot/selection/DistanceFunctionVisualization.java#L146-L200
ben-manes/caffeine
simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/sketch/feedback/FeedbackWindowTinyLfuPolicy.java
FeedbackWindowTinyLfuPolicy.policies
public static Set<Policy> policies(Config config) { FeedbackWindowTinyLfuSettings settings = new FeedbackWindowTinyLfuSettings(config); return settings.percentMain().stream() .map(percentMain -> new FeedbackWindowTinyLfuPolicy(percentMain, settings)) .collect(toSet()); }
java
public static Set<Policy> policies(Config config) { FeedbackWindowTinyLfuSettings settings = new FeedbackWindowTinyLfuSettings(config); return settings.percentMain().stream() .map(percentMain -> new FeedbackWindowTinyLfuPolicy(percentMain, settings)) .collect(toSet()); }
[ "public", "static", "Set", "<", "Policy", ">", "policies", "(", "Config", "config", ")", "{", "FeedbackWindowTinyLfuSettings", "settings", "=", "new", "FeedbackWindowTinyLfuSettings", "(", "config", ")", ";", "return", "settings", ".", "percentMain", "(", ")", "...
Returns all variations of this policy based on the configuration parameters.
[ "Returns", "all", "variations", "of", "this", "policy", "based", "on", "the", "configuration", "parameters", "." ]
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/sketch/feedback/FeedbackWindowTinyLfuPolicy.java#L106-L111
cloudfoundry/uaa
server/src/main/java/org/cloudfoundry/identity/uaa/client/SocialClientUserDetailsSource.java
SocialClientUserDetailsSource.getPrincipal
@Override public Authentication getPrincipal() { @SuppressWarnings("unchecked") Map<String, String> map = restTemplate.getForObject(userInfoUrl, Map.class); String userName = getUserName(map); String email = null; if (map.containsKey("email")) { email = map.get("email"); } if (userName == null && email != null) { userName = email; } if (userName == null) { userName = map.get("id"); // no user-friendly identifier for linked // in and google } List<UaaAuthority> authorities = UaaAuthority.USER_AUTHORITIES; SocialClientUserDetails user = new SocialClientUserDetails(userName, authorities); user.setSource(Source.classify(userInfoUrl)); user.setExternalId(getUserId(map)); String fullName = getFullName(map); if (fullName != null) { user.setFullName(fullName); } if (email != null) { user.setEmail(email); } return user; }
java
@Override public Authentication getPrincipal() { @SuppressWarnings("unchecked") Map<String, String> map = restTemplate.getForObject(userInfoUrl, Map.class); String userName = getUserName(map); String email = null; if (map.containsKey("email")) { email = map.get("email"); } if (userName == null && email != null) { userName = email; } if (userName == null) { userName = map.get("id"); // no user-friendly identifier for linked // in and google } List<UaaAuthority> authorities = UaaAuthority.USER_AUTHORITIES; SocialClientUserDetails user = new SocialClientUserDetails(userName, authorities); user.setSource(Source.classify(userInfoUrl)); user.setExternalId(getUserId(map)); String fullName = getFullName(map); if (fullName != null) { user.setFullName(fullName); } if (email != null) { user.setEmail(email); } return user; }
[ "@", "Override", "public", "Authentication", "getPrincipal", "(", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Map", "<", "String", ",", "String", ">", "map", "=", "restTemplate", ".", "getForObject", "(", "userInfoUrl", ",", "Map", ".", "c...
Get as much generic information as possible about the current user from the remote endpoint. The aim is to collect as much of the properties of a {@link SocialClientUserDetails} as possible but not to fail if there is an authenticated user. If one of the tested remote providers is used at least a user id will be available, asserting that someone has authenticated and permitted us to see some public information. @return some user details
[ "Get", "as", "much", "generic", "information", "as", "possible", "about", "the", "current", "user", "from", "the", "remote", "endpoint", ".", "The", "aim", "is", "to", "collect", "as", "much", "of", "the", "properties", "of", "a", "{", "@link", "SocialClie...
train
https://github.com/cloudfoundry/uaa/blob/e8df3d7060580c92d33461106399f9e4f36e3cd2/server/src/main/java/org/cloudfoundry/identity/uaa/client/SocialClientUserDetailsSource.java#L96-L124
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/axes/AxesWalker.java
AxesWalker.findClone
static AxesWalker findClone(AxesWalker key, Vector cloneList) { if(null != cloneList) { // First, look for clone on list. int n = cloneList.size(); for (int i = 0; i < n; i+=2) { if(key == cloneList.elementAt(i)) return (AxesWalker)cloneList.elementAt(i+1); } } return null; }
java
static AxesWalker findClone(AxesWalker key, Vector cloneList) { if(null != cloneList) { // First, look for clone on list. int n = cloneList.size(); for (int i = 0; i < n; i+=2) { if(key == cloneList.elementAt(i)) return (AxesWalker)cloneList.elementAt(i+1); } } return null; }
[ "static", "AxesWalker", "findClone", "(", "AxesWalker", "key", ",", "Vector", "cloneList", ")", "{", "if", "(", "null", "!=", "cloneList", ")", "{", "// First, look for clone on list.", "int", "n", "=", "cloneList", ".", "size", "(", ")", ";", "for", "(", ...
Find a clone that corresponds to the key argument. @param key The original AxesWalker for which there may be a clone. @param cloneList vector of sources in odd elements, and the corresponding clones in even vectors, may be null. @return A clone that corresponds to the key, or null if key not found.
[ "Find", "a", "clone", "that", "corresponds", "to", "the", "key", "argument", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/axes/AxesWalker.java#L157-L170
phax/ph-oton
ph-oton-security/src/main/java/com/helger/photon/security/object/StubObject.java
StubObject.createForCurrentUser
@Nonnull public static StubObject createForCurrentUser (@Nullable final Map <String, String> aCustomAttrs) { return createForUser (LoggedInUserManager.getInstance ().getCurrentUserID (), aCustomAttrs); }
java
@Nonnull public static StubObject createForCurrentUser (@Nullable final Map <String, String> aCustomAttrs) { return createForUser (LoggedInUserManager.getInstance ().getCurrentUserID (), aCustomAttrs); }
[ "@", "Nonnull", "public", "static", "StubObject", "createForCurrentUser", "(", "@", "Nullable", "final", "Map", "<", "String", ",", "String", ">", "aCustomAttrs", ")", "{", "return", "createForUser", "(", "LoggedInUserManager", ".", "getInstance", "(", ")", ".",...
Create a {@link StubObject} for the current user creating a new object ID @param aCustomAttrs Custom attributes. May be <code>null</code>. @return Never <code>null</code>.
[ "Create", "a", "{", "@link", "StubObject", "}", "for", "the", "current", "user", "creating", "a", "new", "object", "ID" ]
train
https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-security/src/main/java/com/helger/photon/security/object/StubObject.java#L100-L104
NLPchina/elasticsearch-sql
src/main/java/org/elasticsearch/plugin/nlpcn/ElasticUtils.java
ElasticUtils.hitsAsStringResult
public static String hitsAsStringResult(SearchHits results, MetaSearchResult metaResults) throws IOException { if(results == null) return null; Object[] searchHits; searchHits = new Object[(int) results.getTotalHits()]; int i = 0; for(SearchHit hit : results) { HashMap<String,Object> value = new HashMap<>(); value.put("_id",hit.getId()); value.put("_type", hit.getType()); value.put("_score", hit.getScore()); value.put("_source", hit.getSourceAsMap()); searchHits[i] = value; i++; } HashMap<String,Object> hits = new HashMap<>(); hits.put("total",results.getTotalHits()); hits.put("max_score",results.getMaxScore()); hits.put("hits",searchHits); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint(); builder.startObject(); builder.field("took", metaResults.getTookImMilli()); builder.field("timed_out",metaResults.isTimedOut()); builder.field("_shards", ImmutableMap.of("total", metaResults.getTotalNumOfShards(), "successful", metaResults.getSuccessfulShards() , "failed", metaResults.getFailedShards())); builder.field("hits",hits) ; builder.endObject(); return BytesReference.bytes(builder).utf8ToString(); }
java
public static String hitsAsStringResult(SearchHits results, MetaSearchResult metaResults) throws IOException { if(results == null) return null; Object[] searchHits; searchHits = new Object[(int) results.getTotalHits()]; int i = 0; for(SearchHit hit : results) { HashMap<String,Object> value = new HashMap<>(); value.put("_id",hit.getId()); value.put("_type", hit.getType()); value.put("_score", hit.getScore()); value.put("_source", hit.getSourceAsMap()); searchHits[i] = value; i++; } HashMap<String,Object> hits = new HashMap<>(); hits.put("total",results.getTotalHits()); hits.put("max_score",results.getMaxScore()); hits.put("hits",searchHits); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint(); builder.startObject(); builder.field("took", metaResults.getTookImMilli()); builder.field("timed_out",metaResults.isTimedOut()); builder.field("_shards", ImmutableMap.of("total", metaResults.getTotalNumOfShards(), "successful", metaResults.getSuccessfulShards() , "failed", metaResults.getFailedShards())); builder.field("hits",hits) ; builder.endObject(); return BytesReference.bytes(builder).utf8ToString(); }
[ "public", "static", "String", "hitsAsStringResult", "(", "SearchHits", "results", ",", "MetaSearchResult", "metaResults", ")", "throws", "IOException", "{", "if", "(", "results", "==", "null", ")", "return", "null", ";", "Object", "[", "]", "searchHits", ";", ...
use our deserializer instead of results toXcontent because the source field is differnet from sourceAsMap.
[ "use", "our", "deserializer", "instead", "of", "results", "toXcontent", "because", "the", "source", "field", "is", "differnet", "from", "sourceAsMap", "." ]
train
https://github.com/NLPchina/elasticsearch-sql/blob/eaab70b4bf1729978911b83eb96e816ebcfe6e7f/src/main/java/org/elasticsearch/plugin/nlpcn/ElasticUtils.java#L43-L71
OpenBEL/openbel-framework
org.openbel.framework.core/src/main/java/org/openbel/framework/core/protonetwork/ProtoNetworkBuilder.java
ProtoNetworkBuilder.buildAnnotationPairs
protected Set<AnnotationPair> buildAnnotationPairs( ProtoNetwork protoNetwork, Map<String, Annotation> annotationMap) { // build annotation value to annotation definition map Set<AnnotationPair> valueDefinitions = new LinkedHashSet<AnnotationPair>(); AnnotationValueTable avt = protoNetwork.getAnnotationValueTable(); AnnotationDefinitionTable adt = protoNetwork.getAnnotationDefinitionTable(); Set<Annotation> annotationMapValues = new HashSet<Annotation>( annotationMap.values()); for (Annotation a : annotationMapValues) { int adid = adt.getDefinitionIndex().get( new TableAnnotationDefinition(a.getDefinition())); int aid = avt.addAnnotationValue(adid, a.getValue()); valueDefinitions.add(new AnnotationPair(adid, aid)); } return valueDefinitions; }
java
protected Set<AnnotationPair> buildAnnotationPairs( ProtoNetwork protoNetwork, Map<String, Annotation> annotationMap) { // build annotation value to annotation definition map Set<AnnotationPair> valueDefinitions = new LinkedHashSet<AnnotationPair>(); AnnotationValueTable avt = protoNetwork.getAnnotationValueTable(); AnnotationDefinitionTable adt = protoNetwork.getAnnotationDefinitionTable(); Set<Annotation> annotationMapValues = new HashSet<Annotation>( annotationMap.values()); for (Annotation a : annotationMapValues) { int adid = adt.getDefinitionIndex().get( new TableAnnotationDefinition(a.getDefinition())); int aid = avt.addAnnotationValue(adid, a.getValue()); valueDefinitions.add(new AnnotationPair(adid, aid)); } return valueDefinitions; }
[ "protected", "Set", "<", "AnnotationPair", ">", "buildAnnotationPairs", "(", "ProtoNetwork", "protoNetwork", ",", "Map", "<", "String", ",", "Annotation", ">", "annotationMap", ")", "{", "// build annotation value to annotation definition map", "Set", "<", "AnnotationPair...
Build a {@link Set} of {@link AnnotationPair} objects from a {@link Map} of {@link Annotation} values. @param protoNetwork {@link ProtoNetwork}, the proto network @param annotationMap {@link Map}, the annotations map @return {@link Set}, the {@link Set} of annotation definition and value pairs
[ "Build", "a", "{", "@link", "Set", "}", "of", "{", "@link", "AnnotationPair", "}", "objects", "from", "a", "{", "@link", "Map", "}", "of", "{", "@link", "Annotation", "}", "values", "." ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/protonetwork/ProtoNetworkBuilder.java#L396-L417
netty/netty
handler/src/main/java/io/netty/handler/ssl/CipherSuiteConverter.java
CipherSuiteConverter.toJava
static String toJava(String openSslCipherSuite, String protocol) { Map<String, String> p2j = o2j.get(openSslCipherSuite); if (p2j == null) { p2j = cacheFromOpenSsl(openSslCipherSuite); // This may happen if this method is queried when OpenSSL doesn't yet have a cipher setup. It will return // "(NONE)" in this case. if (p2j == null) { return null; } } String javaCipherSuite = p2j.get(protocol); if (javaCipherSuite == null) { String cipher = p2j.get(""); if (cipher == null) { return null; } javaCipherSuite = protocol + '_' + cipher; } return javaCipherSuite; }
java
static String toJava(String openSslCipherSuite, String protocol) { Map<String, String> p2j = o2j.get(openSslCipherSuite); if (p2j == null) { p2j = cacheFromOpenSsl(openSslCipherSuite); // This may happen if this method is queried when OpenSSL doesn't yet have a cipher setup. It will return // "(NONE)" in this case. if (p2j == null) { return null; } } String javaCipherSuite = p2j.get(protocol); if (javaCipherSuite == null) { String cipher = p2j.get(""); if (cipher == null) { return null; } javaCipherSuite = protocol + '_' + cipher; } return javaCipherSuite; }
[ "static", "String", "toJava", "(", "String", "openSslCipherSuite", ",", "String", "protocol", ")", "{", "Map", "<", "String", ",", "String", ">", "p2j", "=", "o2j", ".", "get", "(", "openSslCipherSuite", ")", ";", "if", "(", "p2j", "==", "null", ")", "...
Convert from OpenSSL cipher suite name convention to java cipher suite name convention. @param openSslCipherSuite An OpenSSL cipher suite name. @param protocol The cryptographic protocol (i.e. SSL, TLS, ...). @return The translated cipher suite name according to java conventions. This will not be {@code null}.
[ "Convert", "from", "OpenSSL", "cipher", "suite", "name", "convention", "to", "java", "cipher", "suite", "name", "convention", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/CipherSuiteConverter.java#L282-L303
actorapp/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java
Messenger.bindRawFile
@ObjectiveCName("bindRawFileWithReference:autoStart:withCallback:") public void bindRawFile(FileReference fileReference, boolean isAutoStart, FileCallback callback) { modules.getFilesModule().bindFile(fileReference, isAutoStart, callback); }
java
@ObjectiveCName("bindRawFileWithReference:autoStart:withCallback:") public void bindRawFile(FileReference fileReference, boolean isAutoStart, FileCallback callback) { modules.getFilesModule().bindFile(fileReference, isAutoStart, callback); }
[ "@", "ObjectiveCName", "(", "\"bindRawFileWithReference:autoStart:withCallback:\"", ")", "public", "void", "bindRawFile", "(", "FileReference", "fileReference", ",", "boolean", "isAutoStart", ",", "FileCallback", "callback", ")", "{", "modules", ".", "getFilesModule", "("...
Raw Bind File @param fileReference reference to file @param isAutoStart automatically start download @param callback file state callback
[ "Raw", "Bind", "File" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java#L1930-L1933
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/FileSystem.java
FileSystem.moveToLocalFile
public void moveToLocalFile(Path src, Path dst) throws IOException { copyToLocalFile(true, false, src, dst); }
java
public void moveToLocalFile(Path src, Path dst) throws IOException { copyToLocalFile(true, false, src, dst); }
[ "public", "void", "moveToLocalFile", "(", "Path", "src", ",", "Path", "dst", ")", "throws", "IOException", "{", "copyToLocalFile", "(", "true", ",", "false", ",", "src", ",", "dst", ")", ";", "}" ]
The src file is under FS, and the dst is on the local disk. Copy it from FS control to the local dst name. Remove the source afterwards
[ "The", "src", "file", "is", "under", "FS", "and", "the", "dst", "is", "on", "the", "local", "disk", ".", "Copy", "it", "from", "FS", "control", "to", "the", "local", "dst", "name", ".", "Remove", "the", "source", "afterwards" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FileSystem.java#L1730-L1732
softindex/datakernel
core-serializer/src/main/java/io/datakernel/serializer/SerializerBuilder.java
SerializerBuilder.build
public <T> BinarySerializer<T> build(Class<T> type) { SerializerForType[] serializerForTypes = new SerializerForType[0]; return build(type, serializerForTypes); }
java
public <T> BinarySerializer<T> build(Class<T> type) { SerializerForType[] serializerForTypes = new SerializerForType[0]; return build(type, serializerForTypes); }
[ "public", "<", "T", ">", "BinarySerializer", "<", "T", ">", "build", "(", "Class", "<", "T", ">", "type", ")", "{", "SerializerForType", "[", "]", "serializerForTypes", "=", "new", "SerializerForType", "[", "0", "]", ";", "return", "build", "(", "type", ...
Creates a {@code BinarySerializer} for the given type token. @return {@code BinarySerializer} for the given type token
[ "Creates", "a", "{", "@code", "BinarySerializer", "}", "for", "the", "given", "type", "token", "." ]
train
https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-serializer/src/main/java/io/datakernel/serializer/SerializerBuilder.java#L267-L270
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/Check.java
Check.equality
public static void equality(int a, int b) { if (a != b) { throw new LionEngineException(ERROR_ARGUMENT + String.valueOf(a) + ERROR_EQUALS + String.valueOf(b)); } }
java
public static void equality(int a, int b) { if (a != b) { throw new LionEngineException(ERROR_ARGUMENT + String.valueOf(a) + ERROR_EQUALS + String.valueOf(b)); } }
[ "public", "static", "void", "equality", "(", "int", "a", ",", "int", "b", ")", "{", "if", "(", "a", "!=", "b", ")", "{", "throw", "new", "LionEngineException", "(", "ERROR_ARGUMENT", "+", "String", ".", "valueOf", "(", "a", ")", "+", "ERROR_EQUALS", ...
Check if <code>a</code> is equal to <code>b</code>. @param a The parameter to test. @param b The parameter to compare to. @throws LionEngineException If check failed.
[ "Check", "if", "<code", ">", "a<", "/", "code", ">", "is", "equal", "to", "<code", ">", "b<", "/", "code", ">", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/Check.java#L214-L220
artikcloud/artikcloud-java
src/main/java/cloud/artik/api/MessagesApi.java
MessagesApi.getFieldPresenceAsync
public com.squareup.okhttp.Call getFieldPresenceAsync(Long startDate, Long endDate, String interval, String sdid, String fieldPresence, final ApiCallback<FieldPresenceEnvelope> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getFieldPresenceValidateBeforeCall(startDate, endDate, interval, sdid, fieldPresence, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<FieldPresenceEnvelope>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
java
public com.squareup.okhttp.Call getFieldPresenceAsync(Long startDate, Long endDate, String interval, String sdid, String fieldPresence, final ApiCallback<FieldPresenceEnvelope> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getFieldPresenceValidateBeforeCall(startDate, endDate, interval, sdid, fieldPresence, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<FieldPresenceEnvelope>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "getFieldPresenceAsync", "(", "Long", "startDate", ",", "Long", "endDate", ",", "String", "interval", ",", "String", "sdid", ",", "String", "fieldPresence", ",", "final", "ApiCallback", "<", "FieldP...
Get normalized message presence (asynchronously) Get normalized message presence. @param startDate startDate (required) @param endDate endDate (required) @param interval String representing grouping interval. One of: &#39;minute&#39; (1 hour limit), &#39;hour&#39; (1 day limit), &#39;day&#39; (31 days limit), &#39;month&#39; (1 year limit), or &#39;year&#39; (10 years limit). (required) @param sdid Source device ID of the messages being searched. (optional) @param fieldPresence String representing a field from the specified device ID. (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "Get", "normalized", "message", "presence", "(", "asynchronously", ")", "Get", "normalized", "message", "presence", "." ]
train
https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/MessagesApi.java#L334-L359
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dimensionalityreduction/PCA.java
PCA.estimateVariance
public double estimateVariance(INDArray data, int ndims) { INDArray dx = data.sub(mean); INDArray v = eigenvectors.transpose().mmul(dx.reshape(dx.columns(), 1)); INDArray t2 = Transforms.pow(v, 2); double fraction = t2.get(NDArrayIndex.interval(0, ndims)).sumNumber().doubleValue(); double total = t2.sumNumber().doubleValue(); return fraction / total; }
java
public double estimateVariance(INDArray data, int ndims) { INDArray dx = data.sub(mean); INDArray v = eigenvectors.transpose().mmul(dx.reshape(dx.columns(), 1)); INDArray t2 = Transforms.pow(v, 2); double fraction = t2.get(NDArrayIndex.interval(0, ndims)).sumNumber().doubleValue(); double total = t2.sumNumber().doubleValue(); return fraction / total; }
[ "public", "double", "estimateVariance", "(", "INDArray", "data", ",", "int", "ndims", ")", "{", "INDArray", "dx", "=", "data", ".", "sub", "(", "mean", ")", ";", "INDArray", "v", "=", "eigenvectors", ".", "transpose", "(", ")", ".", "mmul", "(", "dx", ...
Estimate the variance of a single record with reduced # of dimensions. @param data A single record with the same <i>N</i> features as the constructing data set @param ndims The number of dimensions to include in calculation @return The fraction (0 to 1) of the total variance covered by the <i>ndims</i> basis set.
[ "Estimate", "the", "variance", "of", "a", "single", "record", "with", "reduced", "#", "of", "dimensions", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dimensionalityreduction/PCA.java#L106-L113
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java
AppServiceEnvironmentsInner.beginCreateOrUpdateMultiRolePoolAsync
public Observable<WorkerPoolResourceInner> beginCreateOrUpdateMultiRolePoolAsync(String resourceGroupName, String name, WorkerPoolResourceInner multiRolePoolEnvelope) { return beginCreateOrUpdateMultiRolePoolWithServiceResponseAsync(resourceGroupName, name, multiRolePoolEnvelope).map(new Func1<ServiceResponse<WorkerPoolResourceInner>, WorkerPoolResourceInner>() { @Override public WorkerPoolResourceInner call(ServiceResponse<WorkerPoolResourceInner> response) { return response.body(); } }); }
java
public Observable<WorkerPoolResourceInner> beginCreateOrUpdateMultiRolePoolAsync(String resourceGroupName, String name, WorkerPoolResourceInner multiRolePoolEnvelope) { return beginCreateOrUpdateMultiRolePoolWithServiceResponseAsync(resourceGroupName, name, multiRolePoolEnvelope).map(new Func1<ServiceResponse<WorkerPoolResourceInner>, WorkerPoolResourceInner>() { @Override public WorkerPoolResourceInner call(ServiceResponse<WorkerPoolResourceInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "WorkerPoolResourceInner", ">", "beginCreateOrUpdateMultiRolePoolAsync", "(", "String", "resourceGroupName", ",", "String", "name", ",", "WorkerPoolResourceInner", "multiRolePoolEnvelope", ")", "{", "return", "beginCreateOrUpdateMultiRolePoolWithServi...
Create or update a multi-role pool. Create or update a multi-role pool. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @param multiRolePoolEnvelope Properties of the multi-role pool. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the WorkerPoolResourceInner object
[ "Create", "or", "update", "a", "multi", "-", "role", "pool", ".", "Create", "or", "update", "a", "multi", "-", "role", "pool", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L2383-L2390
apereo/cas
core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/WebUtils.java
WebUtils.putServiceResponseIntoRequestScope
public static void putServiceResponseIntoRequestScope(final RequestContext requestContext, final Response response) { requestContext.getRequestScope().put("parameters", response.getAttributes()); putServiceRedirectUrl(requestContext, response.getUrl()); }
java
public static void putServiceResponseIntoRequestScope(final RequestContext requestContext, final Response response) { requestContext.getRequestScope().put("parameters", response.getAttributes()); putServiceRedirectUrl(requestContext, response.getUrl()); }
[ "public", "static", "void", "putServiceResponseIntoRequestScope", "(", "final", "RequestContext", "requestContext", ",", "final", "Response", "response", ")", "{", "requestContext", ".", "getRequestScope", "(", ")", ".", "put", "(", "\"parameters\"", ",", "response", ...
Put service response into request scope. @param requestContext the request context @param response the response
[ "Put", "service", "response", "into", "request", "scope", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/WebUtils.java#L762-L765
OpenLiberty/open-liberty
dev/com.ibm.ws.jdbc/src/com/ibm/ws/jdbc/internal/JDBCDrivers.java
JDBCDrivers.tryToLoad
private static String tryToLoad(Class<?> type, ClassLoader loader, String... classNames) { final boolean trace = TraceComponent.isAnyTracingEnabled(); for (String className : classNames) try { Class<?> c = loader.loadClass(className); boolean isInstance = type.isAssignableFrom(c); if (trace && tc.isDebugEnabled()) Tr.debug(tc, className + " is " + (isInstance ? "" : "not ") + "an instance of " + type.getName()); if (type.isAssignableFrom(c)) return className; } catch (ClassNotFoundException x) { if (trace && tc.isDebugEnabled()) Tr.debug(tc, className + " not found on " + loader); } return null; }
java
private static String tryToLoad(Class<?> type, ClassLoader loader, String... classNames) { final boolean trace = TraceComponent.isAnyTracingEnabled(); for (String className : classNames) try { Class<?> c = loader.loadClass(className); boolean isInstance = type.isAssignableFrom(c); if (trace && tc.isDebugEnabled()) Tr.debug(tc, className + " is " + (isInstance ? "" : "not ") + "an instance of " + type.getName()); if (type.isAssignableFrom(c)) return className; } catch (ClassNotFoundException x) { if (trace && tc.isDebugEnabled()) Tr.debug(tc, className + " not found on " + loader); } return null; }
[ "private", "static", "String", "tryToLoad", "(", "Class", "<", "?", ">", "type", ",", "ClassLoader", "loader", ",", "String", "...", "classNames", ")", "{", "final", "boolean", "trace", "=", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", ";", "for",...
Attempt to load the specified class names, returning the first that successfully loads and is an instance of the specified type. @param type data source interface @param loader class loader @param classNames ordered list of class names to check @return the first class name that successfully loads and is an instance of the specified interface. Otherwise, NULL.
[ "Attempt", "to", "load", "the", "specified", "class", "names", "returning", "the", "first", "that", "successfully", "loads", "and", "is", "an", "instance", "of", "the", "specified", "type", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/jdbc/internal/JDBCDrivers.java#L504-L520
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/TileSheetsConfig.java
TileSheetsConfig.exports
public static void exports(Media configSheets, int tileWidth, int tileHeight, Collection<String> sheets) { Check.notNull(configSheets); Check.notNull(sheets); final Xml nodeSheets = new Xml(NODE_TILE_SHEETS); nodeSheets.writeString(Constant.XML_HEADER, Constant.ENGINE_WEBSITE); final Xml tileSize = nodeSheets.createChild(NODE_TILE_SIZE); tileSize.writeString(ATT_TILE_WIDTH, String.valueOf(tileWidth)); tileSize.writeString(ATT_TILE_HEIGHT, String.valueOf(tileHeight)); exportSheets(nodeSheets, sheets); nodeSheets.save(configSheets); }
java
public static void exports(Media configSheets, int tileWidth, int tileHeight, Collection<String> sheets) { Check.notNull(configSheets); Check.notNull(sheets); final Xml nodeSheets = new Xml(NODE_TILE_SHEETS); nodeSheets.writeString(Constant.XML_HEADER, Constant.ENGINE_WEBSITE); final Xml tileSize = nodeSheets.createChild(NODE_TILE_SIZE); tileSize.writeString(ATT_TILE_WIDTH, String.valueOf(tileWidth)); tileSize.writeString(ATT_TILE_HEIGHT, String.valueOf(tileHeight)); exportSheets(nodeSheets, sheets); nodeSheets.save(configSheets); }
[ "public", "static", "void", "exports", "(", "Media", "configSheets", ",", "int", "tileWidth", ",", "int", "tileHeight", ",", "Collection", "<", "String", ">", "sheets", ")", "{", "Check", ".", "notNull", "(", "configSheets", ")", ";", "Check", ".", "notNul...
Export the sheets configuration. @param configSheets The export media (must not be <code>null</code>). @param tileWidth The tile width. @param tileHeight The tile height. @param sheets The sheets filename (must not be <code>null</code>). @throws LionEngineException If error on writing.
[ "Export", "the", "sheets", "configuration", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/TileSheetsConfig.java#L80-L95
eclipse/xtext-lib
org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/BigDecimalExtensions.java
BigDecimalExtensions.operator_multiply
@Pure @Inline(value="$1.multiply($2)") public static BigDecimal operator_multiply(BigDecimal a, BigDecimal b) { return a.multiply(b); }
java
@Pure @Inline(value="$1.multiply($2)") public static BigDecimal operator_multiply(BigDecimal a, BigDecimal b) { return a.multiply(b); }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"$1.multiply($2)\"", ")", "public", "static", "BigDecimal", "operator_multiply", "(", "BigDecimal", "a", ",", "BigDecimal", "b", ")", "{", "return", "a", ".", "multiply", "(", "b", ")", ";", "}" ]
The binary <code>times</code> operator. @param a a BigDecimal. May not be <code>null</code>. @param b a BigDecimal. May not be <code>null</code>. @return <code>a.multiply(b)</code> @throws NullPointerException if {@code a} or {@code b} is <code>null</code>.
[ "The", "binary", "<code", ">", "times<", "/", "code", ">", "operator", "." ]
train
https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/BigDecimalExtensions.java#L100-L104
OpenTSDB/opentsdb
src/tsd/QueryRpc.java
QueryRpc.parseRateOptions
static final public RateOptions parseRateOptions(final boolean rate, final String spec) { if (!rate || spec.length() == 4) { return new RateOptions(false, Long.MAX_VALUE, RateOptions.DEFAULT_RESET_VALUE); } if (spec.length() < 6) { throw new BadRequestException("Invalid rate options specification: " + spec); } String[] parts = Tags .splitString(spec.substring(5, spec.length() - 1), ','); if (parts.length < 1 || parts.length > 3) { throw new BadRequestException( "Incorrect number of values in rate options specification, must be " + "counter[,counter max value,reset value], recieved: " + parts.length + " parts"); } final boolean counter = parts[0].endsWith("counter"); try { final long max = (parts.length >= 2 && parts[1].length() > 0 ? Long .parseLong(parts[1]) : Long.MAX_VALUE); try { final long reset = (parts.length >= 3 && parts[2].length() > 0 ? Long .parseLong(parts[2]) : RateOptions.DEFAULT_RESET_VALUE); final boolean drop_counter = parts[0].equals("dropcounter"); return new RateOptions(counter, max, reset, drop_counter); } catch (NumberFormatException e) { throw new BadRequestException( "Reset value of counter was not a number, received '" + parts[2] + "'"); } } catch (NumberFormatException e) { throw new BadRequestException( "Max value of counter was not a number, received '" + parts[1] + "'"); } }
java
static final public RateOptions parseRateOptions(final boolean rate, final String spec) { if (!rate || spec.length() == 4) { return new RateOptions(false, Long.MAX_VALUE, RateOptions.DEFAULT_RESET_VALUE); } if (spec.length() < 6) { throw new BadRequestException("Invalid rate options specification: " + spec); } String[] parts = Tags .splitString(spec.substring(5, spec.length() - 1), ','); if (parts.length < 1 || parts.length > 3) { throw new BadRequestException( "Incorrect number of values in rate options specification, must be " + "counter[,counter max value,reset value], recieved: " + parts.length + " parts"); } final boolean counter = parts[0].endsWith("counter"); try { final long max = (parts.length >= 2 && parts[1].length() > 0 ? Long .parseLong(parts[1]) : Long.MAX_VALUE); try { final long reset = (parts.length >= 3 && parts[2].length() > 0 ? Long .parseLong(parts[2]) : RateOptions.DEFAULT_RESET_VALUE); final boolean drop_counter = parts[0].equals("dropcounter"); return new RateOptions(counter, max, reset, drop_counter); } catch (NumberFormatException e) { throw new BadRequestException( "Reset value of counter was not a number, received '" + parts[2] + "'"); } } catch (NumberFormatException e) { throw new BadRequestException( "Max value of counter was not a number, received '" + parts[1] + "'"); } }
[ "static", "final", "public", "RateOptions", "parseRateOptions", "(", "final", "boolean", "rate", ",", "final", "String", "spec", ")", "{", "if", "(", "!", "rate", "||", "spec", ".", "length", "(", ")", "==", "4", ")", "{", "return", "new", "RateOptions",...
Parses the "rate" section of the query string and returns an instance of the RateOptions class that contains the values found. <p/> The format of the rate specification is rate[{counter[,#[,#]]}]. @param rate If true, then the query is set as a rate query and the rate specification will be parsed. If false, a default RateOptions instance will be returned and largely ignored by the rest of the processing @param spec The part of the query string that pertains to the rate @return An initialized RateOptions instance based on the specification @throws BadRequestException if the parameter is malformed @since 2.0
[ "Parses", "the", "rate", "section", "of", "the", "query", "string", "and", "returns", "an", "instance", "of", "the", "RateOptions", "class", "that", "contains", "the", "values", "found", ".", "<p", "/", ">", "The", "format", "of", "the", "rate", "specifica...
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tsd/QueryRpc.java#L758-L797
undertow-io/undertow
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodePingUtil.java
NodePingUtil.pingHost
static void pingHost(InetSocketAddress address, HttpServerExchange exchange, PingCallback callback, OptionMap options) { final XnioIoThread thread = exchange.getIoThread(); final XnioWorker worker = thread.getWorker(); final HostPingTask r = new HostPingTask(address, worker, callback, options); // Schedule timeout task scheduleCancelTask(exchange.getIoThread(), r, 5, TimeUnit.SECONDS); exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE : thread, r); }
java
static void pingHost(InetSocketAddress address, HttpServerExchange exchange, PingCallback callback, OptionMap options) { final XnioIoThread thread = exchange.getIoThread(); final XnioWorker worker = thread.getWorker(); final HostPingTask r = new HostPingTask(address, worker, callback, options); // Schedule timeout task scheduleCancelTask(exchange.getIoThread(), r, 5, TimeUnit.SECONDS); exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE : thread, r); }
[ "static", "void", "pingHost", "(", "InetSocketAddress", "address", ",", "HttpServerExchange", "exchange", ",", "PingCallback", "callback", ",", "OptionMap", "options", ")", "{", "final", "XnioIoThread", "thread", "=", "exchange", ".", "getIoThread", "(", ")", ";",...
Try to open a socket connection to given address. @param address the socket address @param exchange the http servers exchange @param callback the ping callback @param options the options
[ "Try", "to", "open", "a", "socket", "connection", "to", "given", "address", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/NodePingUtil.java#L83-L91
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/rules/Rules.java
Rules.conditionsRule
public static Rule conditionsRule(final Set<Condition> conditions, StateObj results) { if (null == conditions) { throw new NullPointerException("conditions must not be null"); } final StateObj newstate = States.state(results); return new Rule() { @Override public boolean test(final StateObj input) { return applyConditions(input, conditions, true); } @Override public StateObj evaluate(final StateObj stateObj) { if (test(stateObj)) { return newstate; } return null; } @Override public String toString() { return "Rule: Conditions(" + conditions + ") => " + newstate; } }; }
java
public static Rule conditionsRule(final Set<Condition> conditions, StateObj results) { if (null == conditions) { throw new NullPointerException("conditions must not be null"); } final StateObj newstate = States.state(results); return new Rule() { @Override public boolean test(final StateObj input) { return applyConditions(input, conditions, true); } @Override public StateObj evaluate(final StateObj stateObj) { if (test(stateObj)) { return newstate; } return null; } @Override public String toString() { return "Rule: Conditions(" + conditions + ") => " + newstate; } }; }
[ "public", "static", "Rule", "conditionsRule", "(", "final", "Set", "<", "Condition", ">", "conditions", ",", "StateObj", "results", ")", "{", "if", "(", "null", "==", "conditions", ")", "{", "throw", "new", "NullPointerException", "(", "\"conditions must not be ...
Create a rule: predicate(conditions) => new state(results) @param conditions conditions @param results results @return rule
[ "Create", "a", "rule", ":", "predicate", "(", "conditions", ")", "=", ">", "new", "state", "(", "results", ")" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/rules/Rules.java#L152-L176
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionValueRelPersistenceImpl.java
CPDefinitionOptionValueRelPersistenceImpl.findByUUID_G
@Override public CPDefinitionOptionValueRel findByUUID_G(String uuid, long groupId) throws NoSuchCPDefinitionOptionValueRelException { CPDefinitionOptionValueRel cpDefinitionOptionValueRel = fetchByUUID_G(uuid, groupId); if (cpDefinitionOptionValueRel == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPDefinitionOptionValueRelException(msg.toString()); } return cpDefinitionOptionValueRel; }
java
@Override public CPDefinitionOptionValueRel findByUUID_G(String uuid, long groupId) throws NoSuchCPDefinitionOptionValueRelException { CPDefinitionOptionValueRel cpDefinitionOptionValueRel = fetchByUUID_G(uuid, groupId); if (cpDefinitionOptionValueRel == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPDefinitionOptionValueRelException(msg.toString()); } return cpDefinitionOptionValueRel; }
[ "@", "Override", "public", "CPDefinitionOptionValueRel", "findByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "throws", "NoSuchCPDefinitionOptionValueRelException", "{", "CPDefinitionOptionValueRel", "cpDefinitionOptionValueRel", "=", "fetchByUUID_G", "(", "uui...
Returns the cp definition option value rel where uuid = &#63; and groupId = &#63; or throws a {@link NoSuchCPDefinitionOptionValueRelException} if it could not be found. @param uuid the uuid @param groupId the group ID @return the matching cp definition option value rel @throws NoSuchCPDefinitionOptionValueRelException if a matching cp definition option value rel could not be found
[ "Returns", "the", "cp", "definition", "option", "value", "rel", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "or", "throws", "a", "{", "@link", "NoSuchCPDefinitionOptionValueRelException", "}", "if", "it", "could", "not", "be", "fou...
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionValueRelPersistenceImpl.java#L676-L703
albfernandez/itext2
src/main/java/com/lowagie/text/Row.java
Row.setElement
void setElement(Object aElement, int column) { if (reserved[column]) throw new IllegalArgumentException("setElement - position already taken"); cells[column] = aElement; if (aElement != null) { reserved[column] = true; } }
java
void setElement(Object aElement, int column) { if (reserved[column]) throw new IllegalArgumentException("setElement - position already taken"); cells[column] = aElement; if (aElement != null) { reserved[column] = true; } }
[ "void", "setElement", "(", "Object", "aElement", ",", "int", "column", ")", "{", "if", "(", "reserved", "[", "column", "]", ")", "throw", "new", "IllegalArgumentException", "(", "\"setElement - position already taken\"", ")", ";", "cells", "[", "column", "]", ...
Puts <CODE>Cell</CODE> to the <CODE>Row</CODE> at the position given, doesn't reserve colspan. @param aElement the cell to add. @param column the position where to add the cell.
[ "Puts", "<CODE", ">", "Cell<", "/", "CODE", ">", "to", "the", "<CODE", ">", "Row<", "/", "CODE", ">", "at", "the", "position", "given", "doesn", "t", "reserve", "colspan", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/Row.java#L244-L251
Berico-Technologies/CLAVIN-NERD
src/main/java/com/bericotech/clavin/nerd/StanfordExtractor.java
StanfordExtractor.convertNERtoCLAVIN
public static List<LocationOccurrence> convertNERtoCLAVIN (List<Triple<String, Integer, Integer>> entities, String text) { List<LocationOccurrence> locations = new ArrayList<LocationOccurrence>(); if (entities != null) { // iterate over each entity Triple for (Triple<String, Integer, Integer> entity : entities) { // check if the entity is a "Location" if (entity.first.equalsIgnoreCase("LOCATION")) { // build a LocationOccurrence object locations.add(new LocationOccurrence(text.substring(entity.second, entity.third), entity.second)); } } } return locations; }
java
public static List<LocationOccurrence> convertNERtoCLAVIN (List<Triple<String, Integer, Integer>> entities, String text) { List<LocationOccurrence> locations = new ArrayList<LocationOccurrence>(); if (entities != null) { // iterate over each entity Triple for (Triple<String, Integer, Integer> entity : entities) { // check if the entity is a "Location" if (entity.first.equalsIgnoreCase("LOCATION")) { // build a LocationOccurrence object locations.add(new LocationOccurrence(text.substring(entity.second, entity.third), entity.second)); } } } return locations; }
[ "public", "static", "List", "<", "LocationOccurrence", ">", "convertNERtoCLAVIN", "(", "List", "<", "Triple", "<", "String", ",", "Integer", ",", "Integer", ">", ">", "entities", ",", "String", "text", ")", "{", "List", "<", "LocationOccurrence", ">", "locat...
Converts output from Stanford NER to input required by CLAVIN resolver. @param entities A List&lt;Triple&lt;String, Integer, Integer&gt;&gt; from Stanford NER @param text text content processed by Stanford NER + CLAVIN resolver @return List&lt;LocationOccurrence&gt; used by CLAVIN resolver
[ "Converts", "output", "from", "Stanford", "NER", "to", "input", "required", "by", "CLAVIN", "resolver", "." ]
train
https://github.com/Berico-Technologies/CLAVIN-NERD/blob/96a51b841ce42f3e406f45d7949d31f73e5e12d5/src/main/java/com/bericotech/clavin/nerd/StanfordExtractor.java#L109-L126
burberius/eve-esi
src/main/java/net/troja/eve/esi/api/UserInterfaceApi.java
UserInterfaceApi.postUiOpenwindowInformation
public void postUiOpenwindowInformation(Integer targetId, String datasource, String token) throws ApiException { postUiOpenwindowInformationWithHttpInfo(targetId, datasource, token); }
java
public void postUiOpenwindowInformation(Integer targetId, String datasource, String token) throws ApiException { postUiOpenwindowInformationWithHttpInfo(targetId, datasource, token); }
[ "public", "void", "postUiOpenwindowInformation", "(", "Integer", "targetId", ",", "String", "datasource", ",", "String", "token", ")", "throws", "ApiException", "{", "postUiOpenwindowInformationWithHttpInfo", "(", "targetId", ",", "datasource", ",", "token", ")", ";",...
Open Information Window Open the information window for a character, corporation or alliance inside the client --- SSO Scope: esi-ui.open_window.v1 @param targetId The target to open (required) @param datasource The server name you would like data from (optional, default to tranquility) @param token Access token to use if unable to set a header (optional) @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Open", "Information", "Window", "Open", "the", "information", "window", "for", "a", "character", "corporation", "or", "alliance", "inside", "the", "client", "---", "SSO", "Scope", ":", "esi", "-", "ui", ".", "open_window", ".", "v1" ]
train
https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/api/UserInterfaceApi.java#L477-L479
lordcodes/SnackbarBuilder
snackbarbuilder/src/main/java/com/github/andrewlord1990/snackbarbuilder/SnackbarBuilder.java
SnackbarBuilder.appendMessage
public SnackbarBuilder appendMessage(CharSequence message, @ColorInt int color) { initialiseAppendMessages(); Spannable spannable = new SpannableString(message); spannable.setSpan(new ForegroundColorSpan(color), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); appendMessages.append(spannable); return this; }
java
public SnackbarBuilder appendMessage(CharSequence message, @ColorInt int color) { initialiseAppendMessages(); Spannable spannable = new SpannableString(message); spannable.setSpan(new ForegroundColorSpan(color), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); appendMessages.append(spannable); return this; }
[ "public", "SnackbarBuilder", "appendMessage", "(", "CharSequence", "message", ",", "@", "ColorInt", "int", "color", ")", "{", "initialiseAppendMessages", "(", ")", ";", "Spannable", "spannable", "=", "new", "SpannableString", "(", "message", ")", ";", "spannable",...
Add some text to append to the message shown on the Snackbar and a colour to make it. @param message Text to append to the Snackbar message. @param color Colour to make the appended text. @return This instance.
[ "Add", "some", "text", "to", "append", "to", "the", "message", "shown", "on", "the", "Snackbar", "and", "a", "colour", "to", "make", "it", "." ]
train
https://github.com/lordcodes/SnackbarBuilder/blob/a104a753c78ed66940c19d295e141a521cf81d73/snackbarbuilder/src/main/java/com/github/andrewlord1990/snackbarbuilder/SnackbarBuilder.java#L198-L205
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/ContinuousDistributions.java
ContinuousDistributions.betinc
protected static double betinc(double x, double A, double B) { double A0=0.0; double B0=1.0; double A1=1.0; double B1=1.0; double M9=0.0; double A2=0.0; while (Math.abs((A1-A2)/A1)>0.00001) { A2=A1; double C9=-(A+M9)*(A+B+M9)*x/(A+2.0*M9)/(A+2.0*M9+1.0); A0=A1+C9*A0; B0=B1+C9*B0; M9=M9+1; C9=M9*(B-M9)*x/(A+2.0*M9-1.0)/(A+2.0*M9); A1=A0+C9*A1; B1=B0+C9*B1; A0=A0/B1; B0=B0/B1; A1=A1/B1; B1=1.0; } return A1/A; }
java
protected static double betinc(double x, double A, double B) { double A0=0.0; double B0=1.0; double A1=1.0; double B1=1.0; double M9=0.0; double A2=0.0; while (Math.abs((A1-A2)/A1)>0.00001) { A2=A1; double C9=-(A+M9)*(A+B+M9)*x/(A+2.0*M9)/(A+2.0*M9+1.0); A0=A1+C9*A0; B0=B1+C9*B0; M9=M9+1; C9=M9*(B-M9)*x/(A+2.0*M9-1.0)/(A+2.0*M9); A1=A0+C9*A1; B1=B0+C9*B1; A0=A0/B1; B0=B0/B1; A1=A1/B1; B1=1.0; } return A1/A; }
[ "protected", "static", "double", "betinc", "(", "double", "x", ",", "double", "A", ",", "double", "B", ")", "{", "double", "A0", "=", "0.0", ";", "double", "B0", "=", "1.0", ";", "double", "A1", "=", "1.0", ";", "double", "B1", "=", "1.0", ";", "...
Internal function used by StudentCdf @param x @param A @param B @return
[ "Internal", "function", "used", "by", "StudentCdf" ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/ContinuousDistributions.java#L128-L150
EasyinnovaSL/Tiff-Library-4J
src/main/java/com/easyinnova/tiff/reader/TiffReader.java
TiffReader.getTiffITValidation
public ValidationResult getTiffITValidation(int profile) { TiffITProfile bpit = new TiffITProfile(tiffModel, profile); bpit.validate(); return bpit.getValidation(); }
java
public ValidationResult getTiffITValidation(int profile) { TiffITProfile bpit = new TiffITProfile(tiffModel, profile); bpit.validate(); return bpit.getValidation(); }
[ "public", "ValidationResult", "getTiffITValidation", "(", "int", "profile", ")", "{", "TiffITProfile", "bpit", "=", "new", "TiffITProfile", "(", "tiffModel", ",", "profile", ")", ";", "bpit", ".", "validate", "(", ")", ";", "return", "bpit", ".", "getValidatio...
Gets the result of the validation. @param profile the TiffIT profile (0: default, 1: P1, 2: P2) @return the validation result
[ "Gets", "the", "result", "of", "the", "validation", "." ]
train
https://github.com/EasyinnovaSL/Tiff-Library-4J/blob/682605d3ed207a66213278c054c98f1b909472b7/src/main/java/com/easyinnova/tiff/reader/TiffReader.java#L152-L156
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UPropertyAliases.java
UPropertyAliases.getPropertyName
public String getPropertyName(int property, int nameChoice) { int valueMapIndex=findProperty(property); if(valueMapIndex==0) { throw new IllegalArgumentException( "Invalid property enum "+property+" (0x"+Integer.toHexString(property)+")"); } return getName(valueMaps[valueMapIndex], nameChoice); }
java
public String getPropertyName(int property, int nameChoice) { int valueMapIndex=findProperty(property); if(valueMapIndex==0) { throw new IllegalArgumentException( "Invalid property enum "+property+" (0x"+Integer.toHexString(property)+")"); } return getName(valueMaps[valueMapIndex], nameChoice); }
[ "public", "String", "getPropertyName", "(", "int", "property", ",", "int", "nameChoice", ")", "{", "int", "valueMapIndex", "=", "findProperty", "(", "property", ")", ";", "if", "(", "valueMapIndex", "==", "0", ")", "{", "throw", "new", "IllegalArgumentExceptio...
Returns a property name given a property enum. Multiple names may be available for each property; the nameChoice selects among them.
[ "Returns", "a", "property", "name", "given", "a", "property", "enum", ".", "Multiple", "names", "may", "be", "available", "for", "each", "property", ";", "the", "nameChoice", "selects", "among", "them", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UPropertyAliases.java#L243-L250
glyptodon/guacamole-client
guacamole/src/main/java/org/apache/guacamole/tunnel/websocket/jetty9/GuacamoleWebSocketTunnelListener.java
GuacamoleWebSocketTunnelListener.closeConnection
private void closeConnection(Session session, int guacamoleStatusCode, int webSocketCode) { try { String message = Integer.toString(guacamoleStatusCode); session.close(new CloseStatus(webSocketCode, message)); } catch (IOException e) { logger.debug("Unable to close WebSocket connection.", e); } }
java
private void closeConnection(Session session, int guacamoleStatusCode, int webSocketCode) { try { String message = Integer.toString(guacamoleStatusCode); session.close(new CloseStatus(webSocketCode, message)); } catch (IOException e) { logger.debug("Unable to close WebSocket connection.", e); } }
[ "private", "void", "closeConnection", "(", "Session", "session", ",", "int", "guacamoleStatusCode", ",", "int", "webSocketCode", ")", "{", "try", "{", "String", "message", "=", "Integer", ".", "toString", "(", "guacamoleStatusCode", ")", ";", "session", ".", "...
Sends the given numeric Guacamole and WebSocket status codes on the given WebSocket connection and closes the connection. @param session The outbound WebSocket connection to close. @param guacamoleStatusCode The numeric Guacamole status code to send. @param webSocketCode The numeric WebSocket status code to send.
[ "Sends", "the", "given", "numeric", "Guacamole", "and", "WebSocket", "status", "codes", "on", "the", "given", "WebSocket", "connection", "and", "closes", "the", "connection", "." ]
train
https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/guacamole/src/main/java/org/apache/guacamole/tunnel/websocket/jetty9/GuacamoleWebSocketTunnelListener.java#L92-L103
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/analyzer/CocoaPodsAnalyzer.java
CocoaPodsAnalyzer.analyzePodfileLockDependencies
private void analyzePodfileLockDependencies(Dependency podfileLock, Engine engine) throws AnalysisException { engine.removeDependency(podfileLock); final String contents; try { contents = FileUtils.readFileToString(podfileLock.getActualFile(), Charset.defaultCharset()); } catch (IOException e) { throw new AnalysisException( "Problem occurred while reading dependency file.", e); } final Matcher matcher = PODFILE_LOCK_DEPENDENCY_PATTERN.matcher(contents); while (matcher.find()) { final String name = matcher.group(1); final String version = matcher.group(2); final Dependency dependency = new Dependency(podfileLock.getActualFile(), true); dependency.setEcosystem(DEPENDENCY_ECOSYSTEM); dependency.setName(name); dependency.setVersion(version); final String packagePath = String.format("%s:%s", name, version); dependency.setPackagePath(packagePath); dependency.setDisplayFileName(packagePath); dependency.setSha1sum(Checksum.getSHA1Checksum(packagePath)); dependency.setSha256sum(Checksum.getSHA256Checksum(packagePath)); dependency.setMd5sum(Checksum.getMD5Checksum(packagePath)); dependency.addEvidence(EvidenceType.VENDOR, PODFILE_LOCK, "name", name, Confidence.HIGHEST); dependency.addEvidence(EvidenceType.PRODUCT, PODFILE_LOCK, "name", name, Confidence.HIGHEST); dependency.addEvidence(EvidenceType.VERSION, PODFILE_LOCK, "version", version, Confidence.HIGHEST); engine.addDependency(dependency); } }
java
private void analyzePodfileLockDependencies(Dependency podfileLock, Engine engine) throws AnalysisException { engine.removeDependency(podfileLock); final String contents; try { contents = FileUtils.readFileToString(podfileLock.getActualFile(), Charset.defaultCharset()); } catch (IOException e) { throw new AnalysisException( "Problem occurred while reading dependency file.", e); } final Matcher matcher = PODFILE_LOCK_DEPENDENCY_PATTERN.matcher(contents); while (matcher.find()) { final String name = matcher.group(1); final String version = matcher.group(2); final Dependency dependency = new Dependency(podfileLock.getActualFile(), true); dependency.setEcosystem(DEPENDENCY_ECOSYSTEM); dependency.setName(name); dependency.setVersion(version); final String packagePath = String.format("%s:%s", name, version); dependency.setPackagePath(packagePath); dependency.setDisplayFileName(packagePath); dependency.setSha1sum(Checksum.getSHA1Checksum(packagePath)); dependency.setSha256sum(Checksum.getSHA256Checksum(packagePath)); dependency.setMd5sum(Checksum.getMD5Checksum(packagePath)); dependency.addEvidence(EvidenceType.VENDOR, PODFILE_LOCK, "name", name, Confidence.HIGHEST); dependency.addEvidence(EvidenceType.PRODUCT, PODFILE_LOCK, "name", name, Confidence.HIGHEST); dependency.addEvidence(EvidenceType.VERSION, PODFILE_LOCK, "version", version, Confidence.HIGHEST); engine.addDependency(dependency); } }
[ "private", "void", "analyzePodfileLockDependencies", "(", "Dependency", "podfileLock", ",", "Engine", "engine", ")", "throws", "AnalysisException", "{", "engine", ".", "removeDependency", "(", "podfileLock", ")", ";", "final", "String", "contents", ";", "try", "{", ...
Analyzes the podfile.lock file to extract evidence for the dependency. @param podfileLock the dependency to analyze @param engine the analysis engine @throws AnalysisException thrown if there is an error analyzing the dependency
[ "Analyzes", "the", "podfile", ".", "lock", "file", "to", "extract", "evidence", "for", "the", "dependency", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/CocoaPodsAnalyzer.java#L165-L197
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/web/Dashboard.java
Dashboard.addWidget
public Widget addWidget(String widgetId, int columnId) { if (columnId < 1) { throw new IllegalArgumentException("Widget column starts with 1"); } Widget widget = new Widget(widgetId); widgetsByColumn.put(columnId, widget); return widget; }
java
public Widget addWidget(String widgetId, int columnId) { if (columnId < 1) { throw new IllegalArgumentException("Widget column starts with 1"); } Widget widget = new Widget(widgetId); widgetsByColumn.put(columnId, widget); return widget; }
[ "public", "Widget", "addWidget", "(", "String", "widgetId", ",", "int", "columnId", ")", "{", "if", "(", "columnId", "<", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Widget column starts with 1\"", ")", ";", "}", "Widget", "widget", "=",...
Add a widget with the given parameters, and return the newly created {@link Widget} object if one wants to add parameters to it. <p>The widget ids are listed by the web service /api/widgets @param widgetId id of an existing widget @param columnId column starts with 1. The widget is ignored if the column id does not match the layout.
[ "Add", "a", "widget", "with", "the", "given", "parameters", "and", "return", "the", "newly", "created", "{", "@link", "Widget", "}", "object", "if", "one", "wants", "to", "add", "parameters", "to", "it", "." ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/web/Dashboard.java#L65-L73
artikcloud/artikcloud-java
src/main/java/cloud/artik/api/DevicesSharesApi.java
DevicesSharesApi.deleteSharingForDevice
public DeviceSharingId deleteSharingForDevice(String deviceId, String shareId) throws ApiException { ApiResponse<DeviceSharingId> resp = deleteSharingForDeviceWithHttpInfo(deviceId, shareId); return resp.getData(); }
java
public DeviceSharingId deleteSharingForDevice(String deviceId, String shareId) throws ApiException { ApiResponse<DeviceSharingId> resp = deleteSharingForDeviceWithHttpInfo(deviceId, shareId); return resp.getData(); }
[ "public", "DeviceSharingId", "deleteSharingForDevice", "(", "String", "deviceId", ",", "String", "shareId", ")", "throws", "ApiException", "{", "ApiResponse", "<", "DeviceSharingId", ">", "resp", "=", "deleteSharingForDeviceWithHttpInfo", "(", "deviceId", ",", "shareId"...
Delete specific share of the given device id Delete specific share of the given device id @param deviceId Device ID. (required) @param shareId Share ID. (required) @return DeviceSharingId @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Delete", "specific", "share", "of", "the", "given", "device", "id", "Delete", "specific", "share", "of", "the", "given", "device", "id" ]
train
https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/DevicesSharesApi.java#L261-L264
gitblit/fathom
fathom-core/src/main/java/fathom/utils/RequireUtil.java
RequireUtil.allowInstance
public static boolean allowInstance(Settings settings, Object object) { Preconditions.checkNotNull(object, "Can not check runtime permissions on a null instance!"); if (object instanceof Method) { return allowMethod(settings, (Method) object); } return allowClass(settings, object.getClass()); }
java
public static boolean allowInstance(Settings settings, Object object) { Preconditions.checkNotNull(object, "Can not check runtime permissions on a null instance!"); if (object instanceof Method) { return allowMethod(settings, (Method) object); } return allowClass(settings, object.getClass()); }
[ "public", "static", "boolean", "allowInstance", "(", "Settings", "settings", ",", "Object", "object", ")", "{", "Preconditions", ".", "checkNotNull", "(", "object", ",", "\"Can not check runtime permissions on a null instance!\"", ")", ";", "if", "(", "object", "insta...
Determines if this object may be used in the current runtime environment. Fathom settings are considered as well as runtime modes. @param settings @param object @return true if the object may be used
[ "Determines", "if", "this", "object", "may", "be", "used", "in", "the", "current", "runtime", "environment", ".", "Fathom", "settings", "are", "considered", "as", "well", "as", "runtime", "modes", "." ]
train
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-core/src/main/java/fathom/utils/RequireUtil.java#L55-L64
CloudSlang/cs-actions
cs-amazon/src/main/java/io/cloudslang/content/amazon/utils/InputsUtil.java
InputsUtil.getEnforcedBooleanCondition
public static boolean getEnforcedBooleanCondition(String input, boolean enforcedBoolean) { return (enforcedBoolean) ? isTrueOrFalse(input) == Boolean.parseBoolean(input) : Boolean.parseBoolean(input); }
java
public static boolean getEnforcedBooleanCondition(String input, boolean enforcedBoolean) { return (enforcedBoolean) ? isTrueOrFalse(input) == Boolean.parseBoolean(input) : Boolean.parseBoolean(input); }
[ "public", "static", "boolean", "getEnforcedBooleanCondition", "(", "String", "input", ",", "boolean", "enforcedBoolean", ")", "{", "return", "(", "enforcedBoolean", ")", "?", "isTrueOrFalse", "(", "input", ")", "==", "Boolean", ".", "parseBoolean", "(", "input", ...
If enforcedBoolean is "true" and string input is: null, empty, many empty chars, TrUe, tRuE... but not "false" then returns "true". If enforcedBoolean is "false" and string input is: null, empty, many empty chars, FaLsE, fAlSe... but not "true" then returns "false" This behavior is needed for inputs like: "imageNoReboot" when we want them to be set to "true" disregarding the value provided (null, empty, many empty chars, TrUe, tRuE) except the case when is "false" @param input String to be evaluated. @param enforcedBoolean Enforcement boolean. @return A boolean according with above description.
[ "If", "enforcedBoolean", "is", "true", "and", "string", "input", "is", ":", "null", "empty", "many", "empty", "chars", "TrUe", "tRuE", "...", "but", "not", "false", "then", "returns", "true", ".", "If", "enforcedBoolean", "is", "false", "and", "string", "i...
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/utils/InputsUtil.java#L295-L297
Ordinastie/MalisisCore
src/main/java/net/malisis/core/client/gui/component/container/UITabGroup.java
UITabGroup.addTab
public UITab addTab(UITab tab, UIContainer container) { if (tab.isActive()) activeTab = tab; add(tab); tab.setContainer(container); tab.setActive(false); listTabs.put(tab, container); updateSize(); if (attachedContainer != null) { setupTabContainer(container); calculateTabPosition(); } return tab; }
java
public UITab addTab(UITab tab, UIContainer container) { if (tab.isActive()) activeTab = tab; add(tab); tab.setContainer(container); tab.setActive(false); listTabs.put(tab, container); updateSize(); if (attachedContainer != null) { setupTabContainer(container); calculateTabPosition(); } return tab; }
[ "public", "UITab", "addTab", "(", "UITab", "tab", ",", "UIContainer", "container", ")", "{", "if", "(", "tab", ".", "isActive", "(", ")", ")", "activeTab", "=", "tab", ";", "add", "(", "tab", ")", ";", "tab", ".", "setContainer", "(", "container", ")...
Adds a {@link UITab} and its corresponding {@link UIContainer} to this {@link UITabGroup}.<br> Also sets the width of this {@code UITabGroup}. @param tab tab to add to the UITabGroup @param container {@link UIContainer} linked to the {@link UITab} @return this {@link UITab}
[ "Adds", "a", "{", "@link", "UITab", "}", "and", "its", "corresponding", "{", "@link", "UIContainer", "}", "to", "this", "{", "@link", "UITabGroup", "}", ".", "<br", ">", "Also", "sets", "the", "width", "of", "this", "{", "@code", "UITabGroup", "}", "."...
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/client/gui/component/container/UITabGroup.java#L188-L205
awin/rabbiteasy
rabbiteasy-core/src/main/java/com/zanox/rabbiteasy/MessageReader.java
MessageReader.readBodyAsObject
@SuppressWarnings("unchecked") public <T> T readBodyAsObject(Class<T> type) { Charset charset = readCharset(); InputStream inputStream = new ByteArrayInputStream(message.getBodyContent()); InputStreamReader inputReader = new InputStreamReader(inputStream, charset); StreamSource streamSource = new StreamSource(inputReader); try { Unmarshaller unmarshaller = JAXBContext.newInstance(type).createUnmarshaller(); if (type.isAnnotationPresent(XmlRootElement.class)) { return (T)unmarshaller.unmarshal(streamSource); } else { JAXBElement<T> element = unmarshaller.unmarshal(streamSource, type); return element.getValue(); } } catch (JAXBException e) { throw new RuntimeException(e); } }
java
@SuppressWarnings("unchecked") public <T> T readBodyAsObject(Class<T> type) { Charset charset = readCharset(); InputStream inputStream = new ByteArrayInputStream(message.getBodyContent()); InputStreamReader inputReader = new InputStreamReader(inputStream, charset); StreamSource streamSource = new StreamSource(inputReader); try { Unmarshaller unmarshaller = JAXBContext.newInstance(type).createUnmarshaller(); if (type.isAnnotationPresent(XmlRootElement.class)) { return (T)unmarshaller.unmarshal(streamSource); } else { JAXBElement<T> element = unmarshaller.unmarshal(streamSource, type); return element.getValue(); } } catch (JAXBException e) { throw new RuntimeException(e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "T", "readBodyAsObject", "(", "Class", "<", "T", ">", "type", ")", "{", "Charset", "charset", "=", "readCharset", "(", ")", ";", "InputStream", "inputStream", "=", "new", "ByteArr...
Extracts the message body and interprets it as the XML representation of an object of the given type. @param type The type (class) of the object @return The message body as an object of the specified type
[ "Extracts", "the", "message", "body", "and", "interprets", "it", "as", "the", "XML", "representation", "of", "an", "object", "of", "the", "given", "type", "." ]
train
https://github.com/awin/rabbiteasy/blob/c161efda6c0f7ef319aedf09dfe40a4a90165510/rabbiteasy-core/src/main/java/com/zanox/rabbiteasy/MessageReader.java#L143-L160
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.hasAnnotation
public static boolean hasAnnotation(AnnotatedNode node, String name) { return AstUtil.getAnnotation(node, name) != null; }
java
public static boolean hasAnnotation(AnnotatedNode node, String name) { return AstUtil.getAnnotation(node, name) != null; }
[ "public", "static", "boolean", "hasAnnotation", "(", "AnnotatedNode", "node", ",", "String", "name", ")", "{", "return", "AstUtil", ".", "getAnnotation", "(", "node", ",", "name", ")", "!=", "null", ";", "}" ]
Return true only if the node has the named annotation @param node - the AST Node to check @param name - the name of the annotation @return true only if the node has the named annotation
[ "Return", "true", "only", "if", "the", "node", "has", "the", "named", "annotation" ]
train
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L489-L491
pravega/pravega
controller/src/main/java/io/pravega/controller/server/SegmentHelper.java
SegmentHelper.createTableSegment
public CompletableFuture<Boolean> createTableSegment(final String tableName, String delegationToken, final long clientRequestId) { final CompletableFuture<Boolean> result = new CompletableFuture<>(); final Controller.NodeUri uri = getTableUri(tableName); final WireCommandType type = WireCommandType.CREATE_TABLE_SEGMENT; final long requestId = (clientRequestId == RequestTag.NON_EXISTENT_ID) ? idGenerator.get() : clientRequestId; final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override public void connectionDropped() { log.warn(requestId, "CreateTableSegment {} Connection dropped", tableName); result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped)); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { log.warn(requestId, "CreateTableSegment {} wrong host", tableName); result.completeExceptionally(new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost)); } @Override public void segmentAlreadyExists(WireCommands.SegmentAlreadyExists segmentAlreadyExists) { log.info(requestId, "CreateTableSegment {} segmentAlreadyExists", tableName); result.complete(true); } @Override public void segmentCreated(WireCommands.SegmentCreated segmentCreated) { log.info(requestId, "CreateTableSegment {} SegmentCreated", tableName); result.complete(true); } @Override public void processingFailure(Exception error) { log.error(requestId, "CreateTableSegment {} threw exception", tableName, error); handleError(error, result, type); } @Override public void authTokenCheckFailed(WireCommands.AuthTokenCheckFailed authTokenCheckFailed) { result.completeExceptionally( new WireCommandFailedException(new AuthenticationException(authTokenCheckFailed.toString()), type, WireCommandFailedException.Reason.AuthFailed)); } }; WireCommands.CreateTableSegment request = new WireCommands.CreateTableSegment(requestId, tableName, delegationToken); sendRequestAsync(request, replyProcessor, result, ModelHelper.encode(uri)); return result; }
java
public CompletableFuture<Boolean> createTableSegment(final String tableName, String delegationToken, final long clientRequestId) { final CompletableFuture<Boolean> result = new CompletableFuture<>(); final Controller.NodeUri uri = getTableUri(tableName); final WireCommandType type = WireCommandType.CREATE_TABLE_SEGMENT; final long requestId = (clientRequestId == RequestTag.NON_EXISTENT_ID) ? idGenerator.get() : clientRequestId; final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override public void connectionDropped() { log.warn(requestId, "CreateTableSegment {} Connection dropped", tableName); result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped)); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { log.warn(requestId, "CreateTableSegment {} wrong host", tableName); result.completeExceptionally(new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost)); } @Override public void segmentAlreadyExists(WireCommands.SegmentAlreadyExists segmentAlreadyExists) { log.info(requestId, "CreateTableSegment {} segmentAlreadyExists", tableName); result.complete(true); } @Override public void segmentCreated(WireCommands.SegmentCreated segmentCreated) { log.info(requestId, "CreateTableSegment {} SegmentCreated", tableName); result.complete(true); } @Override public void processingFailure(Exception error) { log.error(requestId, "CreateTableSegment {} threw exception", tableName, error); handleError(error, result, type); } @Override public void authTokenCheckFailed(WireCommands.AuthTokenCheckFailed authTokenCheckFailed) { result.completeExceptionally( new WireCommandFailedException(new AuthenticationException(authTokenCheckFailed.toString()), type, WireCommandFailedException.Reason.AuthFailed)); } }; WireCommands.CreateTableSegment request = new WireCommands.CreateTableSegment(requestId, tableName, delegationToken); sendRequestAsync(request, replyProcessor, result, ModelHelper.encode(uri)); return result; }
[ "public", "CompletableFuture", "<", "Boolean", ">", "createTableSegment", "(", "final", "String", "tableName", ",", "String", "delegationToken", ",", "final", "long", "clientRequestId", ")", "{", "final", "CompletableFuture", "<", "Boolean", ">", "result", "=", "n...
This method sends a WireCommand to create a table segment. @param tableName Qualified table name. @param delegationToken The token to be presented to the segmentstore. @param clientRequestId Request id. @return A CompletableFuture that, when completed normally, will indicate the table segment creation completed successfully. If the operation failed, the future will be failed with the causing exception. If the exception can be retried then the future will be failed with {@link WireCommandFailedException}.
[ "This", "method", "sends", "a", "WireCommand", "to", "create", "a", "table", "segment", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/server/SegmentHelper.java#L632-L683
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/debug/GVRConsoleFactory.java
GVRConsoleFactory.createTerminalConsoleShell
static Shell createTerminalConsoleShell(String prompt, String appName, ShellCommandHandler mainHandler, InputStream input, OutputStream output) { try { PrintStream out = new PrintStream(output); // Build jline terminal jline.Terminal term = TerminalFactory.get(); final ConsoleReader console = new ConsoleReader(input, output, term); console.setBellEnabled(true); console.setHistoryEnabled(true); // Build console BufferedReader in = new BufferedReader(new InputStreamReader( new ConsoleReaderInputStream(console))); ConsoleIO.PromptListener promptListener = new ConsoleIO.PromptListener() { @Override public boolean onPrompt(String prompt) { console.setPrompt(prompt); return true; // suppress normal prompt } }; return createConsoleShell(prompt, appName, mainHandler, in, out, out, promptListener); } catch (Exception e) { // Failover: use default shell BufferedReader in = new BufferedReader(new InputStreamReader(input)); PrintStream out = new PrintStream(output); return createConsoleShell(prompt, appName, mainHandler, in, out, out, null); } }
java
static Shell createTerminalConsoleShell(String prompt, String appName, ShellCommandHandler mainHandler, InputStream input, OutputStream output) { try { PrintStream out = new PrintStream(output); // Build jline terminal jline.Terminal term = TerminalFactory.get(); final ConsoleReader console = new ConsoleReader(input, output, term); console.setBellEnabled(true); console.setHistoryEnabled(true); // Build console BufferedReader in = new BufferedReader(new InputStreamReader( new ConsoleReaderInputStream(console))); ConsoleIO.PromptListener promptListener = new ConsoleIO.PromptListener() { @Override public boolean onPrompt(String prompt) { console.setPrompt(prompt); return true; // suppress normal prompt } }; return createConsoleShell(prompt, appName, mainHandler, in, out, out, promptListener); } catch (Exception e) { // Failover: use default shell BufferedReader in = new BufferedReader(new InputStreamReader(input)); PrintStream out = new PrintStream(output); return createConsoleShell(prompt, appName, mainHandler, in, out, out, null); } }
[ "static", "Shell", "createTerminalConsoleShell", "(", "String", "prompt", ",", "String", "appName", ",", "ShellCommandHandler", "mainHandler", ",", "InputStream", "input", ",", "OutputStream", "output", ")", "{", "try", "{", "PrintStream", "out", "=", "new", "Prin...
Facade method for operating the Unix-like terminal supporting line editing and command history. @param prompt Prompt to be displayed @param appName The app name string @param mainHandler Main command handler @param input Input stream. @param output Output stream. @return Shell that can be either further customized or run directly by calling commandLoop().
[ "Facade", "method", "for", "operating", "the", "Unix", "-", "like", "terminal", "supporting", "line", "editing", "and", "command", "history", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/debug/GVRConsoleFactory.java#L97-L128
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/coverage/CoverageUtilities.java
CoverageUtilities.integerArray2WritableRaster
public static WritableRaster integerArray2WritableRaster( int[] array, double divide, int width, int height ) { WritableRaster writableRaster = createWritableRaster(width, height, null, null, null); int index = 0;; for( int x = 0; x < width; x++ ) { for( int y = 0; y < height; y++ ) { double value = (double) array[index++] / divide; writableRaster.setSample(x, y, 0, value); } } return writableRaster; }
java
public static WritableRaster integerArray2WritableRaster( int[] array, double divide, int width, int height ) { WritableRaster writableRaster = createWritableRaster(width, height, null, null, null); int index = 0;; for( int x = 0; x < width; x++ ) { for( int y = 0; y < height; y++ ) { double value = (double) array[index++] / divide; writableRaster.setSample(x, y, 0, value); } } return writableRaster; }
[ "public", "static", "WritableRaster", "integerArray2WritableRaster", "(", "int", "[", "]", "array", ",", "double", "divide", ",", "int", "width", ",", "int", "height", ")", "{", "WritableRaster", "writableRaster", "=", "createWritableRaster", "(", "width", ",", ...
Transforms an array of integer values into a {@link WritableRaster}. @param array the values to transform. @param divide the factor by which to divide the values. @param width the width of the resulting image. @param height the height of the resulting image. @return the raster.
[ "Transforms", "an", "array", "of", "integer", "values", "into", "a", "{", "@link", "WritableRaster", "}", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/coverage/CoverageUtilities.java#L1112-L1122
biojava/biojava
biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java
Alignments.getAllPairsAlignments
public static <S extends Sequence<C>, C extends Compound> List<SequencePair<S, C>> getAllPairsAlignments( List<S> sequences, PairwiseSequenceAlignerType type, GapPenalty gapPenalty, SubstitutionMatrix<C> subMatrix) { return runPairwiseAligners(getAllPairsAligners(sequences, type, gapPenalty, subMatrix)); }
java
public static <S extends Sequence<C>, C extends Compound> List<SequencePair<S, C>> getAllPairsAlignments( List<S> sequences, PairwiseSequenceAlignerType type, GapPenalty gapPenalty, SubstitutionMatrix<C> subMatrix) { return runPairwiseAligners(getAllPairsAligners(sequences, type, gapPenalty, subMatrix)); }
[ "public", "static", "<", "S", "extends", "Sequence", "<", "C", ">", ",", "C", "extends", "Compound", ">", "List", "<", "SequencePair", "<", "S", ",", "C", ">", ">", "getAllPairsAlignments", "(", "List", "<", "S", ">", "sequences", ",", "PairwiseSequenceA...
Factory method which computes a sequence alignment for all {@link Sequence} pairs in the given {@link List}. This method runs the alignments in parallel by submitting all of the alignments to the shared thread pool of the {@link ConcurrencyTools} utility. @param <S> each {@link Sequence} of an alignment pair is of type S @param <C> each element of an {@link AlignedSequence} is a {@link Compound} of type C @param sequences the {@link List} of {@link Sequence}s to align @param type chosen type from list of pairwise sequence alignment routines @param gapPenalty the gap penalties used during alignment @param subMatrix the set of substitution scores used during alignment @return list of sequence alignment pairs
[ "Factory", "method", "which", "computes", "a", "sequence", "alignment", "for", "all", "{", "@link", "Sequence", "}", "pairs", "in", "the", "given", "{", "@link", "List", "}", ".", "This", "method", "runs", "the", "alignments", "in", "parallel", "by", "subm...
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java#L132-L136
skuzzle/semantic-version
src/main/java/de/skuzzle/semantic/Version.java
Version.nextMajor
public Version nextMajor(String newPrelease) { require(newPrelease != null, "newPreRelease is null"); final String[] preReleaseParts = parsePreRelease(newPrelease); return new Version(this.major + 1, 0, 0, preReleaseParts, EMPTY_ARRAY); }
java
public Version nextMajor(String newPrelease) { require(newPrelease != null, "newPreRelease is null"); final String[] preReleaseParts = parsePreRelease(newPrelease); return new Version(this.major + 1, 0, 0, preReleaseParts, EMPTY_ARRAY); }
[ "public", "Version", "nextMajor", "(", "String", "newPrelease", ")", "{", "require", "(", "newPrelease", "!=", "null", ",", "\"newPreRelease is null\"", ")", ";", "final", "String", "[", "]", "preReleaseParts", "=", "parsePreRelease", "(", "newPrelease", ")", ";...
Given this Version, returns the next major Version. That is, the major part is incremented by 1 and the remaining parts are set to 0. The pre-release part will be set to the given identifier and the build-meta-data is dropped. @param newPrelease The pre-release part for the resulting Version. @return The incremented version. @throws VersionFormatException If the given String is not a valid pre-release identifier. @throws IllegalArgumentException If newPreRelease is null. @see #nextMajor() @see #nextMajor(String[]) @since 1.2.0
[ "Given", "this", "Version", "returns", "the", "next", "major", "Version", ".", "That", "is", "the", "major", "part", "is", "incremented", "by", "1", "and", "the", "remaining", "parts", "are", "set", "to", "0", ".", "The", "pre", "-", "release", "part", ...
train
https://github.com/skuzzle/semantic-version/blob/2ddb66fb80244cd7f67c77ed5f8072d1132ad933/src/main/java/de/skuzzle/semantic/Version.java#L717-L721
alibaba/jstorm
jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/common/HdfsUtils.java
HdfsUtils.tryCreateFile
public static FSDataOutputStream tryCreateFile(FileSystem fs, Path file) throws IOException { try { FSDataOutputStream os = fs.create(file, false); return os; } catch (FileAlreadyExistsException e) { return null; } catch (RemoteException e) { if( e.unwrapRemoteException() instanceof AlreadyBeingCreatedException ) { return null; } else { // unexpected error throw e; } } }
java
public static FSDataOutputStream tryCreateFile(FileSystem fs, Path file) throws IOException { try { FSDataOutputStream os = fs.create(file, false); return os; } catch (FileAlreadyExistsException e) { return null; } catch (RemoteException e) { if( e.unwrapRemoteException() instanceof AlreadyBeingCreatedException ) { return null; } else { // unexpected error throw e; } } }
[ "public", "static", "FSDataOutputStream", "tryCreateFile", "(", "FileSystem", "fs", ",", "Path", "file", ")", "throws", "IOException", "{", "try", "{", "FSDataOutputStream", "os", "=", "fs", ".", "create", "(", "file", ",", "false", ")", ";", "return", "os",...
Returns null if file already exists. throws if there was unexpected problem
[ "Returns", "null", "if", "file", "already", "exists", ".", "throws", "if", "there", "was", "unexpected", "problem" ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/common/HdfsUtils.java#L65-L78
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java
JobsImpl.listFromJobSchedule
public PagedList<CloudJob> listFromJobSchedule(final String jobScheduleId) { ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders> response = listFromJobScheduleSinglePageAsync(jobScheduleId).toBlocking().single(); return new PagedList<CloudJob>(response.body()) { @Override public Page<CloudJob> nextPage(String nextPageLink) { return listFromJobScheduleNextSinglePageAsync(nextPageLink, null).toBlocking().single().body(); } }; }
java
public PagedList<CloudJob> listFromJobSchedule(final String jobScheduleId) { ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders> response = listFromJobScheduleSinglePageAsync(jobScheduleId).toBlocking().single(); return new PagedList<CloudJob>(response.body()) { @Override public Page<CloudJob> nextPage(String nextPageLink) { return listFromJobScheduleNextSinglePageAsync(nextPageLink, null).toBlocking().single().body(); } }; }
[ "public", "PagedList", "<", "CloudJob", ">", "listFromJobSchedule", "(", "final", "String", "jobScheduleId", ")", "{", "ServiceResponseWithHeaders", "<", "Page", "<", "CloudJob", ">", ",", "JobListFromJobScheduleHeaders", ">", "response", "=", "listFromJobScheduleSingle...
Lists the jobs that have been created under the specified job schedule. @param jobScheduleId The ID of the job schedule from which you want to get a list of jobs. @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PagedList&lt;CloudJob&gt; object if successful.
[ "Lists", "the", "jobs", "that", "have", "been", "created", "under", "the", "specified", "job", "schedule", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java#L2512-L2520
ixa-ehu/ixa-pipe-nerc
src/main/java/eus/ixa/ixa/pipe/nerc/NERTaggerServer.java
NERTaggerServer.getAnnotations
private String getAnnotations(Annotate annotator, String stringFromClient) throws JDOMException, IOException { // get a breader from the string coming from the client BufferedReader clientReader = new BufferedReader( new StringReader(stringFromClient)); KAFDocument kaf = KAFDocument.createFromStream(clientReader); KAFDocument.LinguisticProcessor newLp = kaf.addLinguisticProcessor( "entities", "ixa-pipe-nerc-" + Files.getNameWithoutExtension(model), version + "-" + commit); newLp.setBeginTimestamp(); annotator.annotateNEsToKAF(kaf); // get outputFormat String kafToString = null; if (outputFormat.equalsIgnoreCase("conll03")) { kafToString = annotator.annotateNEsToCoNLL2003(kaf); } else if (outputFormat.equalsIgnoreCase("conll02")) { kafToString = annotator.annotateNEsToCoNLL2002(kaf); } else { newLp.setEndTimestamp(); kafToString = kaf.toString(); } return kafToString; }
java
private String getAnnotations(Annotate annotator, String stringFromClient) throws JDOMException, IOException { // get a breader from the string coming from the client BufferedReader clientReader = new BufferedReader( new StringReader(stringFromClient)); KAFDocument kaf = KAFDocument.createFromStream(clientReader); KAFDocument.LinguisticProcessor newLp = kaf.addLinguisticProcessor( "entities", "ixa-pipe-nerc-" + Files.getNameWithoutExtension(model), version + "-" + commit); newLp.setBeginTimestamp(); annotator.annotateNEsToKAF(kaf); // get outputFormat String kafToString = null; if (outputFormat.equalsIgnoreCase("conll03")) { kafToString = annotator.annotateNEsToCoNLL2003(kaf); } else if (outputFormat.equalsIgnoreCase("conll02")) { kafToString = annotator.annotateNEsToCoNLL2002(kaf); } else { newLp.setEndTimestamp(); kafToString = kaf.toString(); } return kafToString; }
[ "private", "String", "getAnnotations", "(", "Annotate", "annotator", ",", "String", "stringFromClient", ")", "throws", "JDOMException", ",", "IOException", "{", "// get a breader from the string coming from the client", "BufferedReader", "clientReader", "=", "new", "BufferedR...
Named Entity annotator. @param annotator the annotator @param stringFromClient the string to be annotated @return the annotation result @throws IOException if io error @throws JDOMException if xml error
[ "Named", "Entity", "annotator", "." ]
train
https://github.com/ixa-ehu/ixa-pipe-nerc/blob/299cb49348eb7650fef2ae47c73f6d3384b43c34/src/main/java/eus/ixa/ixa/pipe/nerc/NERTaggerServer.java#L187-L209
nostra13/Android-Universal-Image-Loader
library/src/main/java/com/nostra13/universalimageloader/core/DefaultConfigurationFactory.java
DefaultConfigurationFactory.createMemoryCache
public static MemoryCache createMemoryCache(Context context, int memoryCacheSize) { if (memoryCacheSize == 0) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); int memoryClass = am.getMemoryClass(); if (hasHoneycomb() && isLargeHeap(context)) { memoryClass = getLargeMemoryClass(am); } memoryCacheSize = 1024 * 1024 * memoryClass / 8; } return new LruMemoryCache(memoryCacheSize); }
java
public static MemoryCache createMemoryCache(Context context, int memoryCacheSize) { if (memoryCacheSize == 0) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); int memoryClass = am.getMemoryClass(); if (hasHoneycomb() && isLargeHeap(context)) { memoryClass = getLargeMemoryClass(am); } memoryCacheSize = 1024 * 1024 * memoryClass / 8; } return new LruMemoryCache(memoryCacheSize); }
[ "public", "static", "MemoryCache", "createMemoryCache", "(", "Context", "context", ",", "int", "memoryCacheSize", ")", "{", "if", "(", "memoryCacheSize", "==", "0", ")", "{", "ActivityManager", "am", "=", "(", "ActivityManager", ")", "context", ".", "getSystemSe...
Creates default implementation of {@link MemoryCache} - {@link LruMemoryCache}<br /> Default cache size = 1/8 of available app memory.
[ "Creates", "default", "implementation", "of", "{" ]
train
https://github.com/nostra13/Android-Universal-Image-Loader/blob/fc3c5f6779bb4f702e233653b61bd9d559e345cc/library/src/main/java/com/nostra13/universalimageloader/core/DefaultConfigurationFactory.java#L114-L124
lightblueseas/file-worker
src/main/java/de/alpharogroup/file/copy/CopyFileExtensions.java
CopyFileExtensions.copyFile
public static boolean copyFile(final File source, final File destination, final Charset sourceEncoding, final Charset destinationEncoding, final boolean lastModified) throws IOException { if (source.isDirectory()) { throw new IllegalArgumentException("The source File " + destination.getName() + " should be a File but is a Directory."); } if (destination.isDirectory()) { throw new IllegalArgumentException("The destination File " + destination.getName() + " should be a File but is a Directory."); } boolean copied = false; try (InputStream inputStream = StreamExtensions.getInputStream(source); InputStreamReader reader = sourceEncoding != null ? new InputStreamReader(inputStream, sourceEncoding) : new InputStreamReader(inputStream); OutputStream outputStream = StreamExtensions.getOutputStream(destination, !destination.exists()); BufferedOutputStream bos = new BufferedOutputStream(outputStream); OutputStreamWriter writer = destinationEncoding != null ? new OutputStreamWriter(bos, destinationEncoding) : new OutputStreamWriter(bos)) { int tmp; final char[] charArray = new char[FileConst.BLOCKSIZE]; while ((tmp = reader.read(charArray)) > 0) { writer.write(charArray, 0, tmp); } copied = true; } catch (final IOException e) { throw e; } if (lastModified) { destination.setLastModified(source.lastModified()); } return copied; }
java
public static boolean copyFile(final File source, final File destination, final Charset sourceEncoding, final Charset destinationEncoding, final boolean lastModified) throws IOException { if (source.isDirectory()) { throw new IllegalArgumentException("The source File " + destination.getName() + " should be a File but is a Directory."); } if (destination.isDirectory()) { throw new IllegalArgumentException("The destination File " + destination.getName() + " should be a File but is a Directory."); } boolean copied = false; try (InputStream inputStream = StreamExtensions.getInputStream(source); InputStreamReader reader = sourceEncoding != null ? new InputStreamReader(inputStream, sourceEncoding) : new InputStreamReader(inputStream); OutputStream outputStream = StreamExtensions.getOutputStream(destination, !destination.exists()); BufferedOutputStream bos = new BufferedOutputStream(outputStream); OutputStreamWriter writer = destinationEncoding != null ? new OutputStreamWriter(bos, destinationEncoding) : new OutputStreamWriter(bos)) { int tmp; final char[] charArray = new char[FileConst.BLOCKSIZE]; while ((tmp = reader.read(charArray)) > 0) { writer.write(charArray, 0, tmp); } copied = true; } catch (final IOException e) { throw e; } if (lastModified) { destination.setLastModified(source.lastModified()); } return copied; }
[ "public", "static", "boolean", "copyFile", "(", "final", "File", "source", ",", "final", "File", "destination", ",", "final", "Charset", "sourceEncoding", ",", "final", "Charset", "destinationEncoding", ",", "final", "boolean", "lastModified", ")", "throws", "IOEx...
Copies the given source file to the given destination file with the given source encodings and destination encodings. @param source the source @param destination the destination @param sourceEncoding the source encoding @param destinationEncoding the destination encoding @param lastModified if true the last modified flag is set. @return true if the given file is copied otherwise false. @throws IOException Signals that an I/O exception has occurred.
[ "Copies", "the", "given", "source", "file", "to", "the", "given", "destination", "file", "with", "the", "given", "source", "encodings", "and", "destination", "encodings", "." ]
train
https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/copy/CopyFileExtensions.java#L531-L574
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.getCertificateVersionsWithServiceResponseAsync
public Observable<ServiceResponse<Page<CertificateItem>>> getCertificateVersionsWithServiceResponseAsync(final String vaultBaseUrl, final String certificateName) { return getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName) .concatMap(new Func1<ServiceResponse<Page<CertificateItem>>, Observable<ServiceResponse<Page<CertificateItem>>>>() { @Override public Observable<ServiceResponse<Page<CertificateItem>>> call(ServiceResponse<Page<CertificateItem>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(getCertificateVersionsNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<CertificateItem>>> getCertificateVersionsWithServiceResponseAsync(final String vaultBaseUrl, final String certificateName) { return getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName) .concatMap(new Func1<ServiceResponse<Page<CertificateItem>>, Observable<ServiceResponse<Page<CertificateItem>>>>() { @Override public Observable<ServiceResponse<Page<CertificateItem>>> call(ServiceResponse<Page<CertificateItem>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(getCertificateVersionsNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "CertificateItem", ">", ">", ">", "getCertificateVersionsWithServiceResponseAsync", "(", "final", "String", "vaultBaseUrl", ",", "final", "String", "certificateName", ")", "{", "return", "getCertificateVe...
List the versions of a certificate. The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This operation requires the certificates/list permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param certificateName The name of the certificate. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;CertificateItem&gt; object
[ "List", "the", "versions", "of", "a", "certificate", ".", "The", "GetCertificateVersions", "operation", "returns", "the", "versions", "of", "a", "certificate", "in", "the", "specified", "key", "vault", ".", "This", "operation", "requires", "the", "certificates", ...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L6961-L6973
rubensousa/RecyclerViewSnap
gravitysnaphelper/src/main/java/com/github/rubensousa/gravitysnaphelper/GravityDelegate.java
GravityDelegate.findEdgeView
@Nullable private View findEdgeView(LinearLayoutManager lm, OrientationHelper helper, boolean start) { if (lm.getChildCount() == 0) { return null; } // If we're at the end of the list, we shouldn't snap // to avoid having the last item not completely visible. if (isAtEndOfList(lm) && !snapLastItem) { return null; } View edgeView = null; int distanceToEdge = Integer.MAX_VALUE; for (int i = 0; i < lm.getChildCount(); i++) { View currentView = lm.getChildAt(i); int currentViewDistance; if ((start && !isRtl) || (!start && isRtl)) { currentViewDistance = Math.abs(helper.getDecoratedStart(currentView)); } else { currentViewDistance = Math.abs(helper.getDecoratedEnd(currentView) - helper.getEnd()); } if (currentViewDistance < distanceToEdge) { distanceToEdge = currentViewDistance; edgeView = currentView; } } return edgeView; }
java
@Nullable private View findEdgeView(LinearLayoutManager lm, OrientationHelper helper, boolean start) { if (lm.getChildCount() == 0) { return null; } // If we're at the end of the list, we shouldn't snap // to avoid having the last item not completely visible. if (isAtEndOfList(lm) && !snapLastItem) { return null; } View edgeView = null; int distanceToEdge = Integer.MAX_VALUE; for (int i = 0; i < lm.getChildCount(); i++) { View currentView = lm.getChildAt(i); int currentViewDistance; if ((start && !isRtl) || (!start && isRtl)) { currentViewDistance = Math.abs(helper.getDecoratedStart(currentView)); } else { currentViewDistance = Math.abs(helper.getDecoratedEnd(currentView) - helper.getEnd()); } if (currentViewDistance < distanceToEdge) { distanceToEdge = currentViewDistance; edgeView = currentView; } } return edgeView; }
[ "@", "Nullable", "private", "View", "findEdgeView", "(", "LinearLayoutManager", "lm", ",", "OrientationHelper", "helper", ",", "boolean", "start", ")", "{", "if", "(", "lm", ".", "getChildCount", "(", ")", "==", "0", ")", "{", "return", "null", ";", "}", ...
Returns the first view that we should snap to. @param lm the recyclerview's layout manager @param helper orientation helper to calculate view sizes @return the first view in the LayoutManager to snap to
[ "Returns", "the", "first", "view", "that", "we", "should", "snap", "to", "." ]
train
https://github.com/rubensousa/RecyclerViewSnap/blob/94686150f06bf8ad2b083a9b421a693ce3134656/gravitysnaphelper/src/main/java/com/github/rubensousa/gravitysnaphelper/GravityDelegate.java#L227-L257
OpenLiberty/open-liberty
dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/handlers/FileStatusHostStatusHandler.java
FileStatusHostStatusHandler.taskHosts
private void taskHosts(RESTRequest request, RESTResponse response) { String taskID = RESTHelper.getRequiredParam(request, APIConstants.PARAM_TASK_ID); String taskHostsJson = getMultipleRoutingHelper().getHosts(taskID); OutputHelper.writeJsonOutput(response, taskHostsJson); }
java
private void taskHosts(RESTRequest request, RESTResponse response) { String taskID = RESTHelper.getRequiredParam(request, APIConstants.PARAM_TASK_ID); String taskHostsJson = getMultipleRoutingHelper().getHosts(taskID); OutputHelper.writeJsonOutput(response, taskHostsJson); }
[ "private", "void", "taskHosts", "(", "RESTRequest", "request", ",", "RESTResponse", "response", ")", "{", "String", "taskID", "=", "RESTHelper", ".", "getRequiredParam", "(", "request", ",", "APIConstants", ".", "PARAM_TASK_ID", ")", ";", "String", "taskHostsJson"...
Returns a JSON array of {hostName, status, } tuple, representing the host names associated with that task (no particular order). [ {"hostName" : "host", "hostStatus" : "status", "hostURL" : "url"}* ]
[ "Returns", "a", "JSON", "array", "of", "{", "hostName", "status", "}", "tuple", "representing", "the", "host", "names", "associated", "with", "that", "task", "(", "no", "particular", "order", ")", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/handlers/FileStatusHostStatusHandler.java#L87-L92
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/common/CommsByteBuffer.java
CommsByteBuffer.putMessage
public synchronized int putMessage(JsMessage message, CommsConnection commsConnection, Conversation conversation) throws MessageCopyFailedException, IncorrectMessageTypeException, MessageEncodeFailedException, UnsupportedEncodingException, SIConnectionDroppedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "putMessage", new Object[]{message, commsConnection, conversation}); int messageLength = putMessgeWithoutEncode(encodeFast(message, commsConnection, conversation)); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "putMessage", messageLength); return messageLength; }
java
public synchronized int putMessage(JsMessage message, CommsConnection commsConnection, Conversation conversation) throws MessageCopyFailedException, IncorrectMessageTypeException, MessageEncodeFailedException, UnsupportedEncodingException, SIConnectionDroppedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "putMessage", new Object[]{message, commsConnection, conversation}); int messageLength = putMessgeWithoutEncode(encodeFast(message, commsConnection, conversation)); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "putMessage", messageLength); return messageLength; }
[ "public", "synchronized", "int", "putMessage", "(", "JsMessage", "message", ",", "CommsConnection", "commsConnection", ",", "Conversation", "conversation", ")", "throws", "MessageCopyFailedException", ",", "IncorrectMessageTypeException", ",", "MessageEncodeFailedException", ...
Puts a message into the byte buffer using the <code>encodeFast()</code> method of encoding messages. This method takes account of any <i>capabilities</i> negotiated at the point the connection was established. <p>This method is used for putting an entire message into the buffer. There are more efficient ways of doing this to aid the Java memory manager that were introduced in FAP9. These methods should be used in favour of this one. @see putDataSlice(). @param message The message to encode. @param commsConnection The comms connection which is passed to MFP. @param conversation The conversation over which the encoded message data is to be transferred. @return Returns the message length. @exception MessageCopyFailedException @exception IncorrectMessageTypeException @exception MessageEncodeFailedException @exception UnsupportedEncodingException @exception SIConnectionDroppedException
[ "Puts", "a", "message", "into", "the", "byte", "buffer", "using", "the", "<code", ">", "encodeFast", "()", "<", "/", "code", ">", "method", "of", "encoding", "messages", ".", "This", "method", "takes", "account", "of", "any", "<i", ">", "capabilities<", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/common/CommsByteBuffer.java#L429-L443
micronaut-projects/micronaut-core
tracing/src/main/java/io/micronaut/tracing/brave/instrument/http/AbstractBraveTracingFilter.java
AbstractBraveTracingFilter.withSpanInScope
void withSpanInScope(HttpRequest<?> request, Span span) { request.setAttribute(TraceRequestAttributes.CURRENT_SPAN, span); Tracer.SpanInScope spanInScope = httpTracing.tracing().tracer().withSpanInScope(span); request.setAttribute(TraceRequestAttributes.CURRENT_SCOPE, spanInScope); }
java
void withSpanInScope(HttpRequest<?> request, Span span) { request.setAttribute(TraceRequestAttributes.CURRENT_SPAN, span); Tracer.SpanInScope spanInScope = httpTracing.tracing().tracer().withSpanInScope(span); request.setAttribute(TraceRequestAttributes.CURRENT_SCOPE, spanInScope); }
[ "void", "withSpanInScope", "(", "HttpRequest", "<", "?", ">", "request", ",", "Span", "span", ")", "{", "request", ".", "setAttribute", "(", "TraceRequestAttributes", ".", "CURRENT_SPAN", ",", "span", ")", ";", "Tracer", ".", "SpanInScope", "spanInScope", "=",...
Configures the request with the given Span. @param request The request @param span The span
[ "Configures", "the", "request", "with", "the", "given", "Span", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/tracing/src/main/java/io/micronaut/tracing/brave/instrument/http/AbstractBraveTracingFilter.java#L53-L57
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/remote/AbstractRemoteConnector.java
AbstractRemoteConnector.parseResponse
private JsonParser parseResponse(Response response) throws IOException { InputStream is = response.getInputStream(); Reader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); return new JsonParser(new JsonLexer(r)); }
java
private JsonParser parseResponse(Response response) throws IOException { InputStream is = response.getInputStream(); Reader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); return new JsonParser(new JsonLexer(r)); }
[ "private", "JsonParser", "parseResponse", "(", "Response", "response", ")", "throws", "IOException", "{", "InputStream", "is", "=", "response", ".", "getInputStream", "(", ")", ";", "Reader", "r", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(...
Parses the given response. The response's input stream doesn't have to be closed. The caller will already do this. @param response the HTTP response to parse @return the parsed result @throws IOException if the response could not be read
[ "Parses", "the", "given", "response", ".", "The", "response", "s", "input", "stream", "doesn", "t", "have", "to", "be", "closed", ".", "The", "caller", "will", "already", "do", "this", "." ]
train
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/remote/AbstractRemoteConnector.java#L205-L209
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/widgets/tabs/Packer.java
Packer.setInsetTop
public Packer setInsetTop(final int val) { Insets i = gc.insets; if (i == null) { i = new Insets(0, 0, 0, 0); } gc.insets = new Insets(val, i.left, i.bottom, i.right); setConstraints(comp, gc); return this; }
java
public Packer setInsetTop(final int val) { Insets i = gc.insets; if (i == null) { i = new Insets(0, 0, 0, 0); } gc.insets = new Insets(val, i.left, i.bottom, i.right); setConstraints(comp, gc); return this; }
[ "public", "Packer", "setInsetTop", "(", "final", "int", "val", ")", "{", "Insets", "i", "=", "gc", ".", "insets", ";", "if", "(", "i", "==", "null", ")", "{", "i", "=", "new", "Insets", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "}", ...
sets top Insets on the constraints for the current component to the value specified.
[ "sets", "top", "Insets", "on", "the", "constraints", "for", "the", "current", "component", "to", "the", "value", "specified", "." ]
train
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/widgets/tabs/Packer.java#L815-L823
OpenTSDB/opentsdb
src/tsd/HttpSerializer.java
HttpSerializer.formatJVMStatsV1
public ChannelBuffer formatJVMStatsV1(final Map<String, Map<String, Object>> map) { throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, "The requested API endpoint has not been implemented", this.getClass().getCanonicalName() + " has not implemented formatJVMStatsV1"); }
java
public ChannelBuffer formatJVMStatsV1(final Map<String, Map<String, Object>> map) { throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, "The requested API endpoint has not been implemented", this.getClass().getCanonicalName() + " has not implemented formatJVMStatsV1"); }
[ "public", "ChannelBuffer", "formatJVMStatsV1", "(", "final", "Map", "<", "String", ",", "Map", "<", "String", ",", "Object", ">", ">", "map", ")", "{", "throw", "new", "BadRequestException", "(", "HttpResponseStatus", ".", "NOT_IMPLEMENTED", ",", "\"The requeste...
Format a list of JVM statistics @param map The JVM stats list to format @return A ChannelBuffer object to pass on to the caller @throws BadRequestException if the plugin has not implemented this method @since 2.2
[ "Format", "a", "list", "of", "JVM", "statistics" ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tsd/HttpSerializer.java#L754-L759
UrielCh/ovh-java-sdk
ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java
ApiOvhIp.loadBalancing_serviceName_importCustomSsl_POST
public OvhLoadBalancingTask loadBalancing_serviceName_importCustomSsl_POST(String serviceName, String certificate, String chain, String key) throws IOException { String qPath = "/ip/loadBalancing/{serviceName}/importCustomSsl"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "certificate", certificate); addBody(o, "chain", chain); addBody(o, "key", key); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhLoadBalancingTask.class); }
java
public OvhLoadBalancingTask loadBalancing_serviceName_importCustomSsl_POST(String serviceName, String certificate, String chain, String key) throws IOException { String qPath = "/ip/loadBalancing/{serviceName}/importCustomSsl"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "certificate", certificate); addBody(o, "chain", chain); addBody(o, "key", key); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhLoadBalancingTask.class); }
[ "public", "OvhLoadBalancingTask", "loadBalancing_serviceName_importCustomSsl_POST", "(", "String", "serviceName", ",", "String", "certificate", ",", "String", "chain", ",", "String", "key", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/ip/loadBalancing/{s...
Import your own ssl certificate on your IP load balancing. Ssl option is needed to use this url. REST: POST /ip/loadBalancing/{serviceName}/importCustomSsl @param chain [required] certificate chain @param key [required] certificate key @param certificate [required] certificate @param serviceName [required] The internal name of your IP load balancing
[ "Import", "your", "own", "ssl", "certificate", "on", "your", "IP", "load", "balancing", ".", "Ssl", "option", "is", "needed", "to", "use", "this", "url", "." ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java#L1276-L1285
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpSubsystemChannel.java
SftpSubsystemChannel.createSymbolicLink
public void createSymbolicLink(String targetpath, String linkpath) throws SftpStatusException, SshException { if (version < 3) { throw new SftpStatusException( SftpStatusException.SSH_FX_OP_UNSUPPORTED, "Symbolic links are not supported by the server SFTP version " + String.valueOf(version)); } try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_SYMLINK); msg.writeInt(requestId.longValue()); msg.writeString(linkpath, CHARSET_ENCODING); msg.writeString(targetpath, CHARSET_ENCODING); sendMessage(msg); getOKRequestStatus(requestId); } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
java
public void createSymbolicLink(String targetpath, String linkpath) throws SftpStatusException, SshException { if (version < 3) { throw new SftpStatusException( SftpStatusException.SSH_FX_OP_UNSUPPORTED, "Symbolic links are not supported by the server SFTP version " + String.valueOf(version)); } try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_SYMLINK); msg.writeInt(requestId.longValue()); msg.writeString(linkpath, CHARSET_ENCODING); msg.writeString(targetpath, CHARSET_ENCODING); sendMessage(msg); getOKRequestStatus(requestId); } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
[ "public", "void", "createSymbolicLink", "(", "String", "targetpath", ",", "String", "linkpath", ")", "throws", "SftpStatusException", ",", "SshException", "{", "if", "(", "version", "<", "3", ")", "{", "throw", "new", "SftpStatusException", "(", "SftpStatusExcepti...
Create a symbolic link. @param targetpath the symbolic link to create @param linkpath the path to which the symbolic link points @throws SshException if the remote SFTP version is < 3 an exception is thrown as this feature is not supported by previous versions of the protocol.
[ "Create", "a", "symbolic", "link", "." ]
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpSubsystemChannel.java#L1207-L1233
OpenLiberty/open-liberty
dev/com.ibm.ws.microprofile.config_git_fat_tck/fat/src/com/ibm/ws/microprofile/config/tck/ConfigGitTckLauncher.java
ConfigGitTckLauncher.runFreshMasterBranchTck
@Mode(TestMode.EXPERIMENTAL) @Test @AllowedFFDC // The tested exceptions cause FFDC so we have to allow for this. public void runFreshMasterBranchTck() throws Exception { File repoParent = new File(GIT_REPO_PARENT_DIR); File repo = new File(repoParent, GIT_REPO_NAME); MvnUtils.mvnCleanInstall(repo); HashMap<String, String> addedProps = new HashMap<String, String>(); String apiVersion = MvnUtils.getApiSpecVersionAfterClone(repo); System.out.println("Queried api.version is : " + apiVersion); addedProps.put(MvnUtils.API_VERSION, apiVersion); String tckVersion = MvnUtils.getTckVersionAfterClone(repo); System.out.println("Queried tck.version is : " + tckVersion); addedProps.put(MvnUtils.TCK_VERSION, tckVersion); // A command line -Dprop=value actually gets to here as a environment variable... String implVersion = System.getenv("impl.version"); System.out.println("Passed in impl.version is : " + implVersion); addedProps.put(MvnUtils.IMPL_VERSION, implVersion); // We store a set of keys that we want the system to add "1.1" or "1.2" etc to // depending on the pom.xml contents. HashSet<String> versionedLibraries = new HashSet<>(Arrays.asList("com.ibm.websphere.org.eclipse.microprofile.config")); String backStopImpl = "1.4"; // Used if there is no impl matching the spec/pom.xml <version> AND impl.version is not set addedProps.put(MvnUtils.BACKSTOP_VERSION, backStopImpl); MvnUtils.runTCKMvnCmd(server, "com.ibm.ws.microprofile.config_fat_tck", this .getClass() + ":launchConfigTCK", MvnUtils.DEFAULT_SUITE_FILENAME, addedProps, versionedLibraries); }
java
@Mode(TestMode.EXPERIMENTAL) @Test @AllowedFFDC // The tested exceptions cause FFDC so we have to allow for this. public void runFreshMasterBranchTck() throws Exception { File repoParent = new File(GIT_REPO_PARENT_DIR); File repo = new File(repoParent, GIT_REPO_NAME); MvnUtils.mvnCleanInstall(repo); HashMap<String, String> addedProps = new HashMap<String, String>(); String apiVersion = MvnUtils.getApiSpecVersionAfterClone(repo); System.out.println("Queried api.version is : " + apiVersion); addedProps.put(MvnUtils.API_VERSION, apiVersion); String tckVersion = MvnUtils.getTckVersionAfterClone(repo); System.out.println("Queried tck.version is : " + tckVersion); addedProps.put(MvnUtils.TCK_VERSION, tckVersion); // A command line -Dprop=value actually gets to here as a environment variable... String implVersion = System.getenv("impl.version"); System.out.println("Passed in impl.version is : " + implVersion); addedProps.put(MvnUtils.IMPL_VERSION, implVersion); // We store a set of keys that we want the system to add "1.1" or "1.2" etc to // depending on the pom.xml contents. HashSet<String> versionedLibraries = new HashSet<>(Arrays.asList("com.ibm.websphere.org.eclipse.microprofile.config")); String backStopImpl = "1.4"; // Used if there is no impl matching the spec/pom.xml <version> AND impl.version is not set addedProps.put(MvnUtils.BACKSTOP_VERSION, backStopImpl); MvnUtils.runTCKMvnCmd(server, "com.ibm.ws.microprofile.config_fat_tck", this .getClass() + ":launchConfigTCK", MvnUtils.DEFAULT_SUITE_FILENAME, addedProps, versionedLibraries); }
[ "@", "Mode", "(", "TestMode", ".", "EXPERIMENTAL", ")", "@", "Test", "@", "AllowedFFDC", "// The tested exceptions cause FFDC so we have to allow for this.", "public", "void", "runFreshMasterBranchTck", "(", ")", "throws", "Exception", "{", "File", "repoParent", "=", "n...
Run the TCK (controlled by autoFVT/publish/tckRunner/tcl/tck-suite.html) @throws Exception
[ "Run", "the", "TCK", "(", "controlled", "by", "autoFVT", "/", "publish", "/", "tckRunner", "/", "tcl", "/", "tck", "-", "suite", ".", "html", ")" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.config_git_fat_tck/fat/src/com/ibm/ws/microprofile/config/tck/ConfigGitTckLauncher.java#L75-L108
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/io/IOUtils.java
IOUtils.linesFromFile
public static List<String> linesFromFile(String filename,String encoding) { try { List<String> lines = new ArrayList<String>(); BufferedReader in = new BufferedReader(new EncodingFileReader(filename,encoding)); String line; while ((line = in.readLine()) != null) { lines.add(line); } in.close(); return lines; } catch (IOException e) { e.printStackTrace(); return null; } }
java
public static List<String> linesFromFile(String filename,String encoding) { try { List<String> lines = new ArrayList<String>(); BufferedReader in = new BufferedReader(new EncodingFileReader(filename,encoding)); String line; while ((line = in.readLine()) != null) { lines.add(line); } in.close(); return lines; } catch (IOException e) { e.printStackTrace(); return null; } }
[ "public", "static", "List", "<", "String", ">", "linesFromFile", "(", "String", "filename", ",", "String", "encoding", ")", "{", "try", "{", "List", "<", "String", ">", "lines", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "BufferedReader"...
Returns the contents of a file as a list of strings. The list may be empty, if the file is empty. If there is an IOException, it is caught and null is returned. Encoding can also be specified
[ "Returns", "the", "contents", "of", "a", "file", "as", "a", "list", "of", "strings", ".", "The", "list", "may", "be", "empty", "if", "the", "file", "is", "empty", ".", "If", "there", "is", "an", "IOException", "it", "is", "caught", "and", "null", "is...
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/io/IOUtils.java#L1231-L1246
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/math/ArrayMath.java
ArrayMath.sampleWithoutReplacement
public static void sampleWithoutReplacement(int[] array, int numArgClasses, Random rand) { int[] temp = new int[numArgClasses]; for (int i = 0; i < temp.length; i++) { temp[i] = i; } shuffle(temp, rand); System.arraycopy(temp, 0, array, 0, array.length); }
java
public static void sampleWithoutReplacement(int[] array, int numArgClasses, Random rand) { int[] temp = new int[numArgClasses]; for (int i = 0; i < temp.length; i++) { temp[i] = i; } shuffle(temp, rand); System.arraycopy(temp, 0, array, 0, array.length); }
[ "public", "static", "void", "sampleWithoutReplacement", "(", "int", "[", "]", "array", ",", "int", "numArgClasses", ",", "Random", "rand", ")", "{", "int", "[", "]", "temp", "=", "new", "int", "[", "numArgClasses", "]", ";", "for", "(", "int", "i", "="...
Fills the array with sample from 0 to numArgClasses-1 without replacement.
[ "Fills", "the", "array", "with", "sample", "from", "0", "to", "numArgClasses", "-", "1", "without", "replacement", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/math/ArrayMath.java#L1399-L1406
alkacon/opencms-core
src/org/opencms/util/CmsUUID.java
CmsUUID.checkId
public static void checkId(CmsUUID id, boolean canBeNull) { if (canBeNull && (id == null)) { return; } if ((!canBeNull && (id == null)) || id.isNullUUID()) { throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_INVALID_UUID_1, id)); } }
java
public static void checkId(CmsUUID id, boolean canBeNull) { if (canBeNull && (id == null)) { return; } if ((!canBeNull && (id == null)) || id.isNullUUID()) { throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_INVALID_UUID_1, id)); } }
[ "public", "static", "void", "checkId", "(", "CmsUUID", "id", ",", "boolean", "canBeNull", ")", "{", "if", "(", "canBeNull", "&&", "(", "id", "==", "null", ")", ")", "{", "return", ";", "}", "if", "(", "(", "!", "canBeNull", "&&", "(", "id", "==", ...
Check that the given id is not the null id.<p> @param id the id to check @param canBeNull only if flag is set, <code>null</code> is accepted @see #isNullUUID()
[ "Check", "that", "the", "given", "id", "is", "not", "the", "null", "id", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsUUID.java#L145-L153
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/core/Block.java
Block.parseTransactions
protected void parseTransactions(final int transactionsOffset) throws ProtocolException { cursor = transactionsOffset; optimalEncodingMessageSize = HEADER_SIZE; if (payload.length == cursor) { // This message is just a header, it has no transactions. transactionBytesValid = false; return; } int numTransactions = (int) readVarInt(); optimalEncodingMessageSize += VarInt.sizeOf(numTransactions); transactions = new ArrayList<>(Math.min(numTransactions, Utils.MAX_INITIAL_ARRAY_LENGTH)); for (int i = 0; i < numTransactions; i++) { Transaction tx = new Transaction(params, payload, cursor, this, serializer, UNKNOWN_LENGTH, null); // Label the transaction as coming from the P2P network, so code that cares where we first saw it knows. tx.getConfidence().setSource(TransactionConfidence.Source.NETWORK); transactions.add(tx); cursor += tx.getMessageSize(); optimalEncodingMessageSize += tx.getOptimalEncodingMessageSize(); } transactionBytesValid = serializer.isParseRetainMode(); }
java
protected void parseTransactions(final int transactionsOffset) throws ProtocolException { cursor = transactionsOffset; optimalEncodingMessageSize = HEADER_SIZE; if (payload.length == cursor) { // This message is just a header, it has no transactions. transactionBytesValid = false; return; } int numTransactions = (int) readVarInt(); optimalEncodingMessageSize += VarInt.sizeOf(numTransactions); transactions = new ArrayList<>(Math.min(numTransactions, Utils.MAX_INITIAL_ARRAY_LENGTH)); for (int i = 0; i < numTransactions; i++) { Transaction tx = new Transaction(params, payload, cursor, this, serializer, UNKNOWN_LENGTH, null); // Label the transaction as coming from the P2P network, so code that cares where we first saw it knows. tx.getConfidence().setSource(TransactionConfidence.Source.NETWORK); transactions.add(tx); cursor += tx.getMessageSize(); optimalEncodingMessageSize += tx.getOptimalEncodingMessageSize(); } transactionBytesValid = serializer.isParseRetainMode(); }
[ "protected", "void", "parseTransactions", "(", "final", "int", "transactionsOffset", ")", "throws", "ProtocolException", "{", "cursor", "=", "transactionsOffset", ";", "optimalEncodingMessageSize", "=", "HEADER_SIZE", ";", "if", "(", "payload", ".", "length", "==", ...
Parse transactions from the block. @param transactionsOffset Offset of the transactions within the block. Useful for non-Bitcoin chains where the block header may not be a fixed size.
[ "Parse", "transactions", "from", "the", "block", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L230-L251
jbundle/jcalendarbutton
src/main/java/org/jbundle/util/jcalendarbutton/JCalendarPopup.java
JCalendarPopup.createCalendarPopup
public static JCalendarPopup createCalendarPopup(String strDateParam, Date dateTarget, Component button) { return JCalendarPopup.createCalendarPopup(null, dateTarget, button, null); }
java
public static JCalendarPopup createCalendarPopup(String strDateParam, Date dateTarget, Component button) { return JCalendarPopup.createCalendarPopup(null, dateTarget, button, null); }
[ "public", "static", "JCalendarPopup", "createCalendarPopup", "(", "String", "strDateParam", ",", "Date", "dateTarget", ",", "Component", "button", ")", "{", "return", "JCalendarPopup", ".", "createCalendarPopup", "(", "null", ",", "dateTarget", ",", "button", ",", ...
Create this calendar in a popup menu and synchronize the text field on change. @param strDateParam The name of the date property (defaults to "date"). @param dateTarget The initial date for this button. @param button The calling button.
[ "Create", "this", "calendar", "in", "a", "popup", "menu", "and", "synchronize", "the", "text", "field", "on", "change", "." ]
train
https://github.com/jbundle/jcalendarbutton/blob/2944e6a0b634b83768d5c0b7b4a2898176421403/src/main/java/org/jbundle/util/jcalendarbutton/JCalendarPopup.java#L582-L585
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/XmlStringBuilder.java
XmlStringBuilder.appendAttribute
public void appendAttribute(final String name, final int value) { write(' '); write(name); write("=\""); write(String.valueOf(value)); write('"'); }
java
public void appendAttribute(final String name, final int value) { write(' '); write(name); write("=\""); write(String.valueOf(value)); write('"'); }
[ "public", "void", "appendAttribute", "(", "final", "String", "name", ",", "final", "int", "value", ")", "{", "write", "(", "'", "'", ")", ";", "write", "(", "name", ")", ";", "write", "(", "\"=\\\"\"", ")", ";", "write", "(", "String", ".", "valueOf"...
<p> Adds an xml attribute name+value pair to the end of this XmlStringBuilder. </p> <p> Eg. name="1" </p> @param name the name of the attribute to be added. @param value the value of the attribute to be added.
[ "<p", ">", "Adds", "an", "xml", "attribute", "name", "+", "value", "pair", "to", "the", "end", "of", "this", "XmlStringBuilder", ".", "<", "/", "p", ">", "<p", ">", "Eg", ".", "name", "=", "1", "<", "/", "p", ">" ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/XmlStringBuilder.java#L215-L221
apache/flink
flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/pregel/VertexCentricIteration.java
VertexCentricIteration.setUpIteration
private void setUpIteration(DeltaIteration<?, ?> iteration) { // set up the iteration operator if (this.configuration != null) { iteration.name(this.configuration.getName("Vertex-centric iteration (" + computeFunction + ")")); iteration.parallelism(this.configuration.getParallelism()); iteration.setSolutionSetUnManaged(this.configuration.isSolutionSetUnmanagedMemory()); // register all aggregators for (Map.Entry<String, Aggregator<?>> entry : this.configuration.getAggregators().entrySet()) { iteration.registerAggregator(entry.getKey(), entry.getValue()); } } else { // no configuration provided; set default name iteration.name("Vertex-centric iteration (" + computeFunction + ")"); } }
java
private void setUpIteration(DeltaIteration<?, ?> iteration) { // set up the iteration operator if (this.configuration != null) { iteration.name(this.configuration.getName("Vertex-centric iteration (" + computeFunction + ")")); iteration.parallelism(this.configuration.getParallelism()); iteration.setSolutionSetUnManaged(this.configuration.isSolutionSetUnmanagedMemory()); // register all aggregators for (Map.Entry<String, Aggregator<?>> entry : this.configuration.getAggregators().entrySet()) { iteration.registerAggregator(entry.getKey(), entry.getValue()); } } else { // no configuration provided; set default name iteration.name("Vertex-centric iteration (" + computeFunction + ")"); } }
[ "private", "void", "setUpIteration", "(", "DeltaIteration", "<", "?", ",", "?", ">", "iteration", ")", "{", "// set up the iteration operator", "if", "(", "this", ".", "configuration", "!=", "null", ")", "{", "iteration", ".", "name", "(", "this", ".", "conf...
Helper method which sets up an iteration with the given vertex value. @param iteration
[ "Helper", "method", "which", "sets", "up", "an", "iteration", "with", "the", "given", "vertex", "value", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/pregel/VertexCentricIteration.java#L443-L461
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyFactory.java
KeyFactory.getInstance
public static KeyFactory getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { Instance instance = GetInstance.getInstance("KeyFactory", KeyFactorySpi.class, algorithm, provider); return new KeyFactory((KeyFactorySpi)instance.impl, instance.provider, algorithm); }
java
public static KeyFactory getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { Instance instance = GetInstance.getInstance("KeyFactory", KeyFactorySpi.class, algorithm, provider); return new KeyFactory((KeyFactorySpi)instance.impl, instance.provider, algorithm); }
[ "public", "static", "KeyFactory", "getInstance", "(", "String", "algorithm", ",", "String", "provider", ")", "throws", "NoSuchAlgorithmException", ",", "NoSuchProviderException", "{", "Instance", "instance", "=", "GetInstance", ".", "getInstance", "(", "\"KeyFactory\"",...
Returns a KeyFactory object that converts public/private keys of the specified algorithm. <p> A new KeyFactory object encapsulating the KeyFactorySpi implementation from the specified provider is returned. The specified provider must be registered in the security provider list. <p> Note that the list of registered providers may be retrieved via the {@link Security#getProviders() Security.getProviders()} method. @param algorithm the name of the requested key algorithm. See the KeyFactory section in the <a href= "{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/StandardNames.html#KeyFactory"> Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information about standard algorithm names. @param provider the name of the provider. @return the new KeyFactory object. @exception NoSuchAlgorithmException if a KeyFactorySpi implementation for the specified algorithm is not available from the specified provider. @exception NoSuchProviderException if the specified provider is not registered in the security provider list. @exception IllegalArgumentException if the provider name is null or empty. @see Provider
[ "Returns", "a", "KeyFactory", "object", "that", "converts", "public", "/", "private", "keys", "of", "the", "specified", "algorithm", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyFactory.java#L232-L238
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/DescriptorFactory.java
DescriptorFactory.getMethodDescriptor
public MethodDescriptor getMethodDescriptor(@SlashedClassName String className, String name, String signature, boolean isStatic) { if (className == null) { throw new NullPointerException("className must be nonnull"); } MethodDescriptor methodDescriptor = new MethodDescriptor(className, name, signature, isStatic); MethodDescriptor existing = methodDescriptorMap.get(methodDescriptor); if (existing == null) { methodDescriptorMap.put(methodDescriptor, methodDescriptor); existing = methodDescriptor; } return existing; }
java
public MethodDescriptor getMethodDescriptor(@SlashedClassName String className, String name, String signature, boolean isStatic) { if (className == null) { throw new NullPointerException("className must be nonnull"); } MethodDescriptor methodDescriptor = new MethodDescriptor(className, name, signature, isStatic); MethodDescriptor existing = methodDescriptorMap.get(methodDescriptor); if (existing == null) { methodDescriptorMap.put(methodDescriptor, methodDescriptor); existing = methodDescriptor; } return existing; }
[ "public", "MethodDescriptor", "getMethodDescriptor", "(", "@", "SlashedClassName", "String", "className", ",", "String", "name", ",", "String", "signature", ",", "boolean", "isStatic", ")", "{", "if", "(", "className", "==", "null", ")", "{", "throw", "new", "...
Get a MethodDescriptor. @param className name of the class containing the method, in VM format (e.g., "java/lang/String") @param name name of the method @param signature signature of the method @param isStatic true if method is static, false otherwise @return MethodDescriptor
[ "Get", "a", "MethodDescriptor", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/DescriptorFactory.java#L172-L184
http-builder-ng/http-builder-ng
http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
HttpBuilder.traceAsync
public <T> CompletableFuture<T> traceAsync(final Class<T> type, final Consumer<HttpConfig> configuration) { return CompletableFuture.supplyAsync(() -> trace(type, configuration), getExecutor()); }
java
public <T> CompletableFuture<T> traceAsync(final Class<T> type, final Consumer<HttpConfig> configuration) { return CompletableFuture.supplyAsync(() -> trace(type, configuration), getExecutor()); }
[ "public", "<", "T", ">", "CompletableFuture", "<", "T", ">", "traceAsync", "(", "final", "Class", "<", "T", ">", "type", ",", "final", "Consumer", "<", "HttpConfig", ">", "configuration", ")", "{", "return", "CompletableFuture", ".", "supplyAsync", "(", "(...
Executes an asynchronous TRACE request on the configured URI (asynchronous alias to `trace(Class,Consumer)`), with additional configuration provided by the configuration function. The result will be cast to the specified `type`. This method is generally used for Java-specific configuration. [source,groovy] ---- HttpBuilder http = HttpBuilder.configure(config -> { config.getRequest().setUri("http://localhost:10101"); }); String result = http.traceAsync(String.class, config -> { config.getRequest().getUri().setPath("/foo"); }); ---- The `configuration` {@link Consumer} allows additional configuration for this request based on the {@link HttpConfig} interface. @param type the type of the response content @param configuration the additional configuration function (delegated to {@link HttpConfig}) @return the resulting content cast to the specified type wrapped in a {@link CompletableFuture}
[ "Executes", "an", "asynchronous", "TRACE", "request", "on", "the", "configured", "URI", "(", "asynchronous", "alias", "to", "trace", "(", "Class", "Consumer", ")", ")", "with", "additional", "configuration", "provided", "by", "the", "configuration", "function", ...
train
https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java#L2218-L2220
Azure/azure-sdk-for-java
sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/FailoverGroupsInner.java
FailoverGroupsInner.beginUpdate
public FailoverGroupInner beginUpdate(String resourceGroupName, String serverName, String failoverGroupName, FailoverGroupUpdate parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, serverName, failoverGroupName, parameters).toBlocking().single().body(); }
java
public FailoverGroupInner beginUpdate(String resourceGroupName, String serverName, String failoverGroupName, FailoverGroupUpdate parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, serverName, failoverGroupName, parameters).toBlocking().single().body(); }
[ "public", "FailoverGroupInner", "beginUpdate", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "failoverGroupName", ",", "FailoverGroupUpdate", "parameters", ")", "{", "return", "beginUpdateWithServiceResponseAsync", "(", "resourceGroupName", ...
Updates a failover group. @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 containing the failover group. @param failoverGroupName The name of the failover group. @param parameters The failover group parameters. @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 FailoverGroupInner object if successful.
[ "Updates", "a", "failover", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/FailoverGroupsInner.java#L666-L668
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/VirtualCdj.java
VirtualCdj.assembleAndSendPacket
@SuppressWarnings("SameParameterValue") private void assembleAndSendPacket(Util.PacketType kind, byte[] payload, InetAddress destination, int port) throws IOException { DatagramPacket packet = Util.buildPacket(kind, ByteBuffer.wrap(announcementBytes, DEVICE_NAME_OFFSET, DEVICE_NAME_LENGTH).asReadOnlyBuffer(), ByteBuffer.wrap(payload)); packet.setAddress(destination); packet.setPort(port); socket.get().send(packet); }
java
@SuppressWarnings("SameParameterValue") private void assembleAndSendPacket(Util.PacketType kind, byte[] payload, InetAddress destination, int port) throws IOException { DatagramPacket packet = Util.buildPacket(kind, ByteBuffer.wrap(announcementBytes, DEVICE_NAME_OFFSET, DEVICE_NAME_LENGTH).asReadOnlyBuffer(), ByteBuffer.wrap(payload)); packet.setAddress(destination); packet.setPort(port); socket.get().send(packet); }
[ "@", "SuppressWarnings", "(", "\"SameParameterValue\"", ")", "private", "void", "assembleAndSendPacket", "(", "Util", ".", "PacketType", "kind", ",", "byte", "[", "]", "payload", ",", "InetAddress", "destination", ",", "int", "port", ")", "throws", "IOException", ...
Finish the work of building and sending a protocol packet. @param kind the type of packet to create and send @param payload the content which will follow our device name in the packet @param destination where the packet should be sent @param port the port to which the packet should be sent @throws IOException if there is a problem sending the packet
[ "Finish", "the", "work", "of", "building", "and", "sending", "a", "protocol", "packet", "." ]
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/VirtualCdj.java#L1092-L1100
woxblom/DragListView
library/src/main/java/com/woxthebox/draglistview/BoardView.java
BoardView.addColumn
public DragItemRecyclerView addColumn(final DragItemAdapter adapter, final @Nullable View header, @Nullable View columnDragView, boolean hasFixedItemSize) { final DragItemRecyclerView recyclerView = insertColumn(adapter, getColumnCount(), header, hasFixedItemSize); setupColumnDragListener(columnDragView, recyclerView); return recyclerView; }
java
public DragItemRecyclerView addColumn(final DragItemAdapter adapter, final @Nullable View header, @Nullable View columnDragView, boolean hasFixedItemSize) { final DragItemRecyclerView recyclerView = insertColumn(adapter, getColumnCount(), header, hasFixedItemSize); setupColumnDragListener(columnDragView, recyclerView); return recyclerView; }
[ "public", "DragItemRecyclerView", "addColumn", "(", "final", "DragItemAdapter", "adapter", ",", "final", "@", "Nullable", "View", "header", ",", "@", "Nullable", "View", "columnDragView", ",", "boolean", "hasFixedItemSize", ")", "{", "final", "DragItemRecyclerView", ...
Adds a column at the last index of the board. @param adapter Adapter with the items for the column. @param header Header view that will be positioned above the column. Can be null. @param columnDragView View that will act as handle to drag and drop columns. Can be null. @param hasFixedItemSize If the items will have a fixed or dynamic size. @return The created DragItemRecyclerView.
[ "Adds", "a", "column", "at", "the", "last", "index", "of", "the", "board", "." ]
train
https://github.com/woxblom/DragListView/blob/9823406f21d96035e88d8fd173f64419d0bb89f3/library/src/main/java/com/woxthebox/draglistview/BoardView.java#L815-L819
fcrepo3/fcrepo
fcrepo-common/src/main/java/org/fcrepo/utilities/xml/DOM.java
DOM.selectString
public static String selectString(Node node, String xpath, String defaultValue) { return selector.selectString(node, xpath, defaultValue); }
java
public static String selectString(Node node, String xpath, String defaultValue) { return selector.selectString(node, xpath, defaultValue); }
[ "public", "static", "String", "selectString", "(", "Node", "node", ",", "String", "xpath", ",", "String", "defaultValue", ")", "{", "return", "selector", ".", "selectString", "(", "node", ",", "xpath", ",", "defaultValue", ")", ";", "}" ]
<p>Extract the given value from the node as a String or if the value cannot be extracted, {@code defaultValue} is returned. </p><p> Example: To get the value of the attribute "foo" in the node, specify "@foo" as the path. </p> Note: This method does not handle namespaces explicitely. @param node the node with the wanted attribute @param xpath the XPath to extract. @param defaultValue the default value @return the value of the path, if existing, else {@code defaultValue}
[ "<p", ">", "Extract", "the", "given", "value", "from", "the", "node", "as", "a", "String", "or", "if", "the", "value", "cannot", "be", "extracted", "{", "@code", "defaultValue", "}", "is", "returned", ".", "<", "/", "p", ">", "<p", ">", "Example", ":...
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-common/src/main/java/org/fcrepo/utilities/xml/DOM.java#L304-L306
alkacon/opencms-core
src/org/opencms/db/generic/CmsVfsDriver.java
CmsVfsDriver.prepareProjectCondition
protected void prepareProjectCondition(CmsUUID projectId, int mode, StringBuffer conditions, List<Object> params) { if ((mode & CmsDriverManager.READMODE_INCLUDE_PROJECT) > 0) { // C_READMODE_INCLUDE_PROJECT: add condition to match the PROJECT_ID conditions.append(BEGIN_INCLUDE_CONDITION); conditions.append(m_sqlManager.readQuery(projectId, "C_RESOURCES_SELECT_BY_PROJECT_LASTMODIFIED")); conditions.append(END_CONDITION); params.add(projectId.toString()); } }
java
protected void prepareProjectCondition(CmsUUID projectId, int mode, StringBuffer conditions, List<Object> params) { if ((mode & CmsDriverManager.READMODE_INCLUDE_PROJECT) > 0) { // C_READMODE_INCLUDE_PROJECT: add condition to match the PROJECT_ID conditions.append(BEGIN_INCLUDE_CONDITION); conditions.append(m_sqlManager.readQuery(projectId, "C_RESOURCES_SELECT_BY_PROJECT_LASTMODIFIED")); conditions.append(END_CONDITION); params.add(projectId.toString()); } }
[ "protected", "void", "prepareProjectCondition", "(", "CmsUUID", "projectId", ",", "int", "mode", ",", "StringBuffer", "conditions", ",", "List", "<", "Object", ">", "params", ")", "{", "if", "(", "(", "mode", "&", "CmsDriverManager", ".", "READMODE_INCLUDE_PROJE...
Appends the appropriate selection criteria related with the projectId.<p> @param projectId the id of the project of the resources @param mode the selection mode @param conditions buffer to append the selection criteria @param params list to append the selection parameters
[ "Appends", "the", "appropriate", "selection", "criteria", "related", "with", "the", "projectId", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsVfsDriver.java#L4225-L4234
intendia-oss/rxjava-gwt
src/main/modified/io/reactivex/super/io/reactivex/Completable.java
Completable.mergeWith
@CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Completable mergeWith(CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); return mergeArray(this, other); }
java
@CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final Completable mergeWith(CompletableSource other) { ObjectHelper.requireNonNull(other, "other is null"); return mergeArray(this, other); }
[ "@", "CheckReturnValue", "@", "SchedulerSupport", "(", "SchedulerSupport", ".", "NONE", ")", "public", "final", "Completable", "mergeWith", "(", "CompletableSource", "other", ")", "{", "ObjectHelper", ".", "requireNonNull", "(", "other", ",", "\"other is null\"", ")...
Returns a Completable which subscribes to this and the other Completable and completes when both of them complete or one emits an error. <p> <img width="640" height="442" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.mergeWith.png" alt=""> <dl> <dt><b>Scheduler:</b></dt> <dd>{@code mergeWith} does not operate by default on a particular {@link Scheduler}.</dd> </dl> @param other the other Completable instance @return the new Completable instance @throws NullPointerException if other is null
[ "Returns", "a", "Completable", "which", "subscribes", "to", "this", "and", "the", "other", "Completable", "and", "completes", "when", "both", "of", "them", "complete", "or", "one", "emits", "an", "error", ".", "<p", ">", "<img", "width", "=", "640", "heigh...
train
https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Completable.java#L1749-L1754
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/JsonUtil.java
JsonUtil.toJsonObject
public static JsonObject toJsonObject(Map<String, ?> map) { JsonObject properties = new JsonObject(); for (Map.Entry<String, ?> property : map.entrySet()) { properties.add(property.getKey(), Json.value(property.getValue().toString())); } return properties; }
java
public static JsonObject toJsonObject(Map<String, ?> map) { JsonObject properties = new JsonObject(); for (Map.Entry<String, ?> property : map.entrySet()) { properties.add(property.getKey(), Json.value(property.getValue().toString())); } return properties; }
[ "public", "static", "JsonObject", "toJsonObject", "(", "Map", "<", "String", ",", "?", ">", "map", ")", "{", "JsonObject", "properties", "=", "new", "JsonObject", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "?", ">", "property",...
Transforms the provided map of name/value pairs into a {@link JsonObject}. @param map map of JSON name-value pairs @return the JSON object
[ "Transforms", "the", "provided", "map", "of", "name", "/", "value", "pairs", "into", "a", "{", "@link", "JsonObject", "}", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/JsonUtil.java#L307-L313
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.intToLongFunction
public static IntToLongFunction intToLongFunction(CheckedIntToLongFunction function, Consumer<Throwable> handler) { return t -> { try { return function.applyAsLong(t); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
java
public static IntToLongFunction intToLongFunction(CheckedIntToLongFunction function, Consumer<Throwable> handler) { return t -> { try { return function.applyAsLong(t); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
[ "public", "static", "IntToLongFunction", "intToLongFunction", "(", "CheckedIntToLongFunction", "function", ",", "Consumer", "<", "Throwable", ">", "handler", ")", "{", "return", "t", "->", "{", "try", "{", "return", "function", ".", "applyAsLong", "(", "t", ")",...
Wrap a {@link CheckedIntToLongFunction} in a {@link IntToLongFunction} with a custom handler for checked exceptions. <p> Example: <code><pre> IntStream.of(1, 2, 3).mapToLong(Unchecked.intToLongFunction( i -> { if (i &lt; 0) throw new Exception("Only positive numbers allowed"); return (long) i; }, e -> { throw new IllegalStateException(e); } )); </pre></code>
[ "Wrap", "a", "{", "@link", "CheckedIntToLongFunction", "}", "in", "a", "{", "@link", "IntToLongFunction", "}", "with", "a", "custom", "handler", "for", "checked", "exceptions", ".", "<p", ">", "Example", ":", "<code", ">", "<pre", ">", "IntStream", ".", "o...
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L1115-L1126
apache/incubator-gobblin
gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanClient.java
AzkabanClient.fetchFlowExecution
public AzkabanFetchExecuteFlowStatus fetchFlowExecution(String execId) throws AzkabanClientException { AzkabanMultiCallables.FetchFlowExecCallable callable = AzkabanMultiCallables.FetchFlowExecCallable.builder() .client(this) .execId(execId) .build(); return runWithRetry(callable, AzkabanFetchExecuteFlowStatus.class); }
java
public AzkabanFetchExecuteFlowStatus fetchFlowExecution(String execId) throws AzkabanClientException { AzkabanMultiCallables.FetchFlowExecCallable callable = AzkabanMultiCallables.FetchFlowExecCallable.builder() .client(this) .execId(execId) .build(); return runWithRetry(callable, AzkabanFetchExecuteFlowStatus.class); }
[ "public", "AzkabanFetchExecuteFlowStatus", "fetchFlowExecution", "(", "String", "execId", ")", "throws", "AzkabanClientException", "{", "AzkabanMultiCallables", ".", "FetchFlowExecCallable", "callable", "=", "AzkabanMultiCallables", ".", "FetchFlowExecCallable", ".", "builder",...
Given an execution id, fetches all the detailed information of that execution, including a list of all the job executions. @param execId execution id to be fetched. @return The status object which contains success status and all the detailed information of that execution.
[ "Given", "an", "execution", "id", "fetches", "all", "the", "detailed", "information", "of", "that", "execution", "including", "a", "list", "of", "all", "the", "job", "executions", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanClient.java#L415-L423
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/allocator/MaxFreeAllocator.java
MaxFreeAllocator.getCandidateDirInTier
private StorageDirView getCandidateDirInTier(StorageTierView tierView, long blockSize) { StorageDirView candidateDirView = null; long maxFreeBytes = blockSize - 1; for (StorageDirView dirView : tierView.getDirViews()) { if (dirView.getAvailableBytes() > maxFreeBytes) { maxFreeBytes = dirView.getAvailableBytes(); candidateDirView = dirView; } } return candidateDirView; }
java
private StorageDirView getCandidateDirInTier(StorageTierView tierView, long blockSize) { StorageDirView candidateDirView = null; long maxFreeBytes = blockSize - 1; for (StorageDirView dirView : tierView.getDirViews()) { if (dirView.getAvailableBytes() > maxFreeBytes) { maxFreeBytes = dirView.getAvailableBytes(); candidateDirView = dirView; } } return candidateDirView; }
[ "private", "StorageDirView", "getCandidateDirInTier", "(", "StorageTierView", "tierView", ",", "long", "blockSize", ")", "{", "StorageDirView", "candidateDirView", "=", "null", ";", "long", "maxFreeBytes", "=", "blockSize", "-", "1", ";", "for", "(", "StorageDirView...
Finds a directory view in a tier view that has max free space and is able to store the block. @param tierView the storage tier view @param blockSize the size of block in bytes @return the storage directory view if found, null otherwise
[ "Finds", "a", "directory", "view", "in", "a", "tier", "view", "that", "has", "max", "free", "space", "and", "is", "able", "to", "store", "the", "block", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/allocator/MaxFreeAllocator.java#L91-L101
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/platform/BackendCleanup.java
BackendCleanup.resetData
public void resetData() { try (DbSession dbSession = dbClient.openSession(false); Connection connection = dbSession.getConnection()) { truncateAnalysisTables(connection); deleteManualRules(connection); truncateInternalProperties(null, null, connection); truncateUsers(null, null, connection); truncateOrganizations(null, null, connection); } catch (SQLException e) { throw new IllegalStateException("Fail to reset data", e); } clearIndex(IssueIndexDefinition.DESCRIPTOR); clearIndex(ViewIndexDefinition.DESCRIPTOR); clearIndex(ProjectMeasuresIndexDefinition.DESCRIPTOR); clearIndex(ComponentIndexDefinition.DESCRIPTOR); }
java
public void resetData() { try (DbSession dbSession = dbClient.openSession(false); Connection connection = dbSession.getConnection()) { truncateAnalysisTables(connection); deleteManualRules(connection); truncateInternalProperties(null, null, connection); truncateUsers(null, null, connection); truncateOrganizations(null, null, connection); } catch (SQLException e) { throw new IllegalStateException("Fail to reset data", e); } clearIndex(IssueIndexDefinition.DESCRIPTOR); clearIndex(ViewIndexDefinition.DESCRIPTOR); clearIndex(ProjectMeasuresIndexDefinition.DESCRIPTOR); clearIndex(ComponentIndexDefinition.DESCRIPTOR); }
[ "public", "void", "resetData", "(", ")", "{", "try", "(", "DbSession", "dbSession", "=", "dbClient", ".", "openSession", "(", "false", ")", ";", "Connection", "connection", "=", "dbSession", ".", "getConnection", "(", ")", ")", "{", "truncateAnalysisTables", ...
Reset data in order to to be in same state as a fresh installation (but without having to drop db and restart the server). Please be careful when updating this method as it's called by Orchestrator.
[ "Reset", "data", "in", "order", "to", "to", "be", "in", "same", "state", "as", "a", "fresh", "installation", "(", "but", "without", "having", "to", "drop", "db", "and", "restart", "the", "server", ")", "." ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/platform/BackendCleanup.java#L113-L130
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBFileParser.java
PDBFileParser.assignAsymIds
private void assignAsymIds(List<List<Chain>> polys, List<List<Chain>> nonPolys, List<List<Chain>> waters) { for (int i=0; i<polys.size(); i++) { String asymId = "A"; for (Chain poly:polys.get(i)) { poly.setId(asymId); asymId = getNextAsymId(asymId); } for (Chain nonPoly:nonPolys.get(i)) { nonPoly.setId(asymId); asymId = getNextAsymId(asymId); } for (Chain water:waters.get(i)) { water.setId(asymId); asymId = getNextAsymId(asymId); } } }
java
private void assignAsymIds(List<List<Chain>> polys, List<List<Chain>> nonPolys, List<List<Chain>> waters) { for (int i=0; i<polys.size(); i++) { String asymId = "A"; for (Chain poly:polys.get(i)) { poly.setId(asymId); asymId = getNextAsymId(asymId); } for (Chain nonPoly:nonPolys.get(i)) { nonPoly.setId(asymId); asymId = getNextAsymId(asymId); } for (Chain water:waters.get(i)) { water.setId(asymId); asymId = getNextAsymId(asymId); } } }
[ "private", "void", "assignAsymIds", "(", "List", "<", "List", "<", "Chain", ">", ">", "polys", ",", "List", "<", "List", "<", "Chain", ">", ">", "nonPolys", ",", "List", "<", "List", "<", "Chain", ">", ">", "waters", ")", "{", "for", "(", "int", ...
Assign asym ids following the rules used by the PDB to assign asym ids in mmCIF files @param polys @param nonPolys @param waters
[ "Assign", "asym", "ids", "following", "the", "rules", "used", "by", "the", "PDB", "to", "assign", "asym", "ids", "in", "mmCIF", "files" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBFileParser.java#L3047-L3065
fcrepo4/fcrepo4
fcrepo-kernel-api/src/main/java/org/fcrepo/kernel/api/rdf/DefaultRdfStream.java
DefaultRdfStream.fromModel
public static RdfStream fromModel(final Node node, final Model model) { return new DefaultRdfStream(node, stream(spliteratorUnknownSize(model.listStatements(), IMMUTABLE), false).map(Statement::asTriple)); }
java
public static RdfStream fromModel(final Node node, final Model model) { return new DefaultRdfStream(node, stream(spliteratorUnknownSize(model.listStatements(), IMMUTABLE), false).map(Statement::asTriple)); }
[ "public", "static", "RdfStream", "fromModel", "(", "final", "Node", "node", ",", "final", "Model", "model", ")", "{", "return", "new", "DefaultRdfStream", "(", "node", ",", "stream", "(", "spliteratorUnknownSize", "(", "model", ".", "listStatements", "(", ")",...
Create an RdfStream from an existing Model. @param node The subject node @param model An input Model @return a new RdfStream object
[ "Create", "an", "RdfStream", "from", "an", "existing", "Model", "." ]
train
https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-api/src/main/java/org/fcrepo/kernel/api/rdf/DefaultRdfStream.java#L73-L76
lazy-koala/java-toolkit
fast-toolkit3d/src/main/java/com/thankjava/toolkit3d/core/xml/XMLBeanUtil.java
XMLBeanUtil.xml2Bean
public static <T> T xml2Bean(String xmlRoot, String xml, Class<T> clazz, boolean isIgnoreUnknownEles) { XStream xStream = xStreamInstance.get(clazz); if (xStream == null) { xStream = new XStream(new DomDriver(ENCODING)); xStream.alias(xmlRoot, clazz); if (isIgnoreUnknownEles) { xStream.ignoreUnknownElements(); } } return (T) xStream.fromXML(xml); }
java
public static <T> T xml2Bean(String xmlRoot, String xml, Class<T> clazz, boolean isIgnoreUnknownEles) { XStream xStream = xStreamInstance.get(clazz); if (xStream == null) { xStream = new XStream(new DomDriver(ENCODING)); xStream.alias(xmlRoot, clazz); if (isIgnoreUnknownEles) { xStream.ignoreUnknownElements(); } } return (T) xStream.fromXML(xml); }
[ "public", "static", "<", "T", ">", "T", "xml2Bean", "(", "String", "xmlRoot", ",", "String", "xml", ",", "Class", "<", "T", ">", "clazz", ",", "boolean", "isIgnoreUnknownEles", ")", "{", "XStream", "xStream", "=", "xStreamInstance", ".", "get", "(", "cla...
将xml转java对象 <p>Function: xml2Bean</p> <p>Description: </p> @param xmlRoot xml根节点名 @param xml @param clazz 对应的java对象 @param isIgnoreUnknownEles 是否容错(如果不允许容错,xml报文中有的节点 java对象中没有将抛异常) @return @author acexy@thankjava.com @date 2016年8月12日 下午3:14:40 @version 1.0
[ "将xml转java对象", "<p", ">", "Function", ":", "xml2Bean<", "/", "p", ">", "<p", ">", "Description", ":", "<", "/", "p", ">" ]
train
https://github.com/lazy-koala/java-toolkit/blob/f46055fae0cc73049597a3708e515f5c6582d27a/fast-toolkit3d/src/main/java/com/thankjava/toolkit3d/core/xml/XMLBeanUtil.java#L40-L50
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java
CheckArg.isSame
public static <T> void isSame( final T argument, String argumentName, final T object, String objectName ) { if (argument != object) { if (objectName == null) objectName = getObjectName(object); throw new IllegalArgumentException(CommonI18n.argumentMustBeSameAs.text(argumentName, objectName)); } }
java
public static <T> void isSame( final T argument, String argumentName, final T object, String objectName ) { if (argument != object) { if (objectName == null) objectName = getObjectName(object); throw new IllegalArgumentException(CommonI18n.argumentMustBeSameAs.text(argumentName, objectName)); } }
[ "public", "static", "<", "T", ">", "void", "isSame", "(", "final", "T", "argument", ",", "String", "argumentName", ",", "final", "T", "object", ",", "String", "objectName", ")", "{", "if", "(", "argument", "!=", "object", ")", "{", "if", "(", "objectNa...
Asserts that the specified first object is the same as (==) the specified second object. @param <T> @param argument The argument to assert as the same as <code>object</code>. @param argumentName The name that will be used within the exception message for the argument should an exception be thrown @param object The object to assert as the same as <code>argument</code>. @param objectName The name that will be used within the exception message for <code>object</code> should an exception be thrown; if <code>null</code> and <code>object</code> is not <code>null</code>, <code>object.toString()</code> will be used. @throws IllegalArgumentException If the specified objects are not the same.
[ "Asserts", "that", "the", "specified", "first", "object", "is", "the", "same", "as", "(", "==", ")", "the", "specified", "second", "object", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java#L472-L480
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/evictor/GreedyEvictor.java
GreedyEvictor.selectEvictableDirFromTier
private StorageDirView selectEvictableDirFromTier(StorageTierView tierView, long availableBytes) { for (StorageDirView dirView : tierView.getDirViews()) { if (canEvictBlocksFromDir(dirView, availableBytes)) { return dirView; } } return null; }
java
private StorageDirView selectEvictableDirFromTier(StorageTierView tierView, long availableBytes) { for (StorageDirView dirView : tierView.getDirViews()) { if (canEvictBlocksFromDir(dirView, availableBytes)) { return dirView; } } return null; }
[ "private", "StorageDirView", "selectEvictableDirFromTier", "(", "StorageTierView", "tierView", ",", "long", "availableBytes", ")", "{", "for", "(", "StorageDirView", "dirView", ":", "tierView", ".", "getDirViews", "(", ")", ")", "{", "if", "(", "canEvictBlocksFromDi...
Selects a dir with enough space (including space evictable) from a given tier
[ "Selects", "a", "dir", "with", "enough", "space", "(", "including", "space", "evictable", ")", "from", "a", "given", "tier" ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/evictor/GreedyEvictor.java#L149-L156
alkacon/opencms-core
src/org/opencms/ui/editors/messagebundle/CmsMessageBundleEditorModel.java
CmsMessageBundleEditorModel.getMasterState
private EditorState getMasterState() { List<TableProperty> cols = new ArrayList<TableProperty>(4); cols.add(TableProperty.KEY); cols.add(TableProperty.DESCRIPTION); cols.add(TableProperty.DEFAULT); cols.add(TableProperty.TRANSLATION); return new EditorState(cols, true); }
java
private EditorState getMasterState() { List<TableProperty> cols = new ArrayList<TableProperty>(4); cols.add(TableProperty.KEY); cols.add(TableProperty.DESCRIPTION); cols.add(TableProperty.DEFAULT); cols.add(TableProperty.TRANSLATION); return new EditorState(cols, true); }
[ "private", "EditorState", "getMasterState", "(", ")", "{", "List", "<", "TableProperty", ">", "cols", "=", "new", "ArrayList", "<", "TableProperty", ">", "(", "4", ")", ";", "cols", ".", "add", "(", "TableProperty", ".", "KEY", ")", ";", "cols", ".", "...
Returns the master mode's editor state for editing a bundle with descriptor. @return the master mode's editor state for editing a bundle with descriptor.
[ "Returns", "the", "master", "mode", "s", "editor", "state", "for", "editing", "a", "bundle", "with", "descriptor", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/editors/messagebundle/CmsMessageBundleEditorModel.java#L1298-L1306
martinwithaar/Encryptor4j
src/main/java/org/encryptor4j/DHPeer.java
DHPeer.createKeyPair
public static final KeyPair createKeyPair(BigInteger p, BigInteger g) throws GeneralSecurityException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM); keyGen.initialize(new DHParameterSpec(p, g), new SecureRandom()); return keyGen.generateKeyPair(); }
java
public static final KeyPair createKeyPair(BigInteger p, BigInteger g) throws GeneralSecurityException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM); keyGen.initialize(new DHParameterSpec(p, g), new SecureRandom()); return keyGen.generateKeyPair(); }
[ "public", "static", "final", "KeyPair", "createKeyPair", "(", "BigInteger", "p", ",", "BigInteger", "g", ")", "throws", "GeneralSecurityException", "{", "KeyPairGenerator", "keyGen", "=", "KeyPairGenerator", ".", "getInstance", "(", "ALGORITHM", ")", ";", "keyGen", ...
<p>Creates and returns a DH key pair for the given <code>p</code> and <code>g</code>.</p> @param p @param g @return @throws GeneralSecurityException
[ "<p", ">", "Creates", "and", "returns", "a", "DH", "key", "pair", "for", "the", "given", "<code", ">", "p<", "/", "code", ">", "and", "<code", ">", "g<", "/", "code", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/martinwithaar/Encryptor4j/blob/8c31d84d9136309f59d810323ed68d902b9bac55/src/main/java/org/encryptor4j/DHPeer.java#L111-L115