repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 218 | func_name stringlengths 5 140 | whole_func_string stringlengths 79 3.99k | language stringclasses 1
value | func_code_string stringlengths 79 3.99k | func_code_tokens listlengths 20 624 | func_documentation_string stringlengths 61 1.96k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 107 339 |
|---|---|---|---|---|---|---|---|---|---|---|
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsJmsMapMessageImpl.java | JsJmsMapMessageImpl.setChar | public void setChar(String name, char value) throws UnsupportedEncodingException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setChar", Character.valueOf(value));
getBodyMap().put(name, Character.valueOf(value));
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setChar");
} | java | public void setChar(String name, char value) throws UnsupportedEncodingException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setChar", Character.valueOf(value));
getBodyMap().put(name, Character.valueOf(value));
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setChar");
} | [
"public",
"void",
"setChar",
"(",
"String",
"name",
",",
"char",
"value",
")",
"throws",
"UnsupportedEncodingException",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"... | /*
Set a Unicode character value with the given name, into the Map.
Javadoc description supplied by JsJmsMessage interface. | [
"/",
"*",
"Set",
"a",
"Unicode",
"character",
"value",
"with",
"the",
"given",
"name",
"into",
"the",
"Map",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsJmsMapMessageImpl.java#L306-L310 |
CleverTap/clevertap-android-sdk | clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/CleverTapAPI.java | CleverTapAPI.setMultiValuesForKey | @SuppressWarnings({"unused", "WeakerAccess"})
public void setMultiValuesForKey(final String key, final ArrayList<String> values) {
postAsyncSafely("setMultiValuesForKey", new Runnable() {
@Override
public void run() {
_handleMultiValues(values, key, Constants.COMMAND_SET);
}
});
} | java | @SuppressWarnings({"unused", "WeakerAccess"})
public void setMultiValuesForKey(final String key, final ArrayList<String> values) {
postAsyncSafely("setMultiValuesForKey", new Runnable() {
@Override
public void run() {
_handleMultiValues(values, key, Constants.COMMAND_SET);
}
});
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"unused\"",
",",
"\"WeakerAccess\"",
"}",
")",
"public",
"void",
"setMultiValuesForKey",
"(",
"final",
"String",
"key",
",",
"final",
"ArrayList",
"<",
"String",
">",
"values",
")",
"{",
"postAsyncSafely",
"(",
"\"setMultiVal... | Set a collection of unique values as a multi-value user profile property, any existing value will be overwritten.
Max 100 values, on reaching 100 cap, oldest value(s) will be removed.
Values must be Strings and are limited to 512 characters.
@param key String
@param values {@link ArrayList} with String values | [
"Set",
"a",
"collection",
"of",
"unique",
"values",
"as",
"a",
"multi",
"-",
"value",
"user",
"profile",
"property",
"any",
"existing",
"value",
"will",
"be",
"overwritten",
".",
"Max",
"100",
"values",
"on",
"reaching",
"100",
"cap",
"oldest",
"value",
"(... | train | https://github.com/CleverTap/clevertap-android-sdk/blob/be134c06a4f07494c398335ad9ff4976633743e1/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/CleverTapAPI.java#L3371-L3379 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueRange.java | ResidueRange.getResidue | public ResidueNumber getResidue(int positionInRange, AtomPositionMap map) {
if (map == null) throw new NullPointerException("The AtomPositionMap must be non-null");
int i = 0;
for (Map.Entry<ResidueNumber, Integer> entry : map.getNavMap().entrySet()) {
if (i == positionInRange) return entry.getKey();
if (contains(entry.getKey(), map)) {
i++;
}
}
return null;
} | java | public ResidueNumber getResidue(int positionInRange, AtomPositionMap map) {
if (map == null) throw new NullPointerException("The AtomPositionMap must be non-null");
int i = 0;
for (Map.Entry<ResidueNumber, Integer> entry : map.getNavMap().entrySet()) {
if (i == positionInRange) return entry.getKey();
if (contains(entry.getKey(), map)) {
i++;
}
}
return null;
} | [
"public",
"ResidueNumber",
"getResidue",
"(",
"int",
"positionInRange",
",",
"AtomPositionMap",
"map",
")",
"{",
"if",
"(",
"map",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"The AtomPositionMap must be non-null\"",
")",
";",
"int",
"i",
"="... | Returns the ResidueNumber that is at position {@code positionInRange} in
<em>this</em> ResidueRange.
@return The ResidueNumber, or false if it does not exist or is not within this ResidueRange | [
"Returns",
"the",
"ResidueNumber",
"that",
"is",
"at",
"position",
"{"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueRange.java#L215-L225 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/source/util/DocTreeScanner.java | DocTreeScanner.visitProvides | @Override
public R visitProvides(ProvidesTree node, P p) {
R r = scan(node.getServiceType(), p);
r = scanAndReduce(node.getDescription(), p, r);
return r;
} | java | @Override
public R visitProvides(ProvidesTree node, P p) {
R r = scan(node.getServiceType(), p);
r = scanAndReduce(node.getDescription(), p, r);
return r;
} | [
"@",
"Override",
"public",
"R",
"visitProvides",
"(",
"ProvidesTree",
"node",
",",
"P",
"p",
")",
"{",
"R",
"r",
"=",
"scan",
"(",
"node",
".",
"getServiceType",
"(",
")",
",",
"p",
")",
";",
"r",
"=",
"scanAndReduce",
"(",
"node",
".",
"getDescripti... | {@inheritDoc} This implementation scans the children in left to right order.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of scanning | [
"{",
"@inheritDoc",
"}",
"This",
"implementation",
"scans",
"the",
"children",
"in",
"left",
"to",
"right",
"order",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/DocTreeScanner.java#L334-L339 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.token.ltpa/src/com/ibm/ws/security/token/ltpa/internal/LTPAConfigurationImpl.java | LTPAConfigurationImpl.isKeysConfigChanged | private boolean isKeysConfigChanged(String oldKeyImportFile, Long oldKeyTokenExpiration) {
return ((oldKeyImportFile.equals(keyImportFile) == false) || (oldKeyTokenExpiration != keyTokenExpiration));
} | java | private boolean isKeysConfigChanged(String oldKeyImportFile, Long oldKeyTokenExpiration) {
return ((oldKeyImportFile.equals(keyImportFile) == false) || (oldKeyTokenExpiration != keyTokenExpiration));
} | [
"private",
"boolean",
"isKeysConfigChanged",
"(",
"String",
"oldKeyImportFile",
",",
"Long",
"oldKeyTokenExpiration",
")",
"{",
"return",
"(",
"(",
"oldKeyImportFile",
".",
"equals",
"(",
"keyImportFile",
")",
"==",
"false",
")",
"||",
"(",
"oldKeyTokenExpiration",
... | The keys config is changed if the file or expiration were modified.
Changing the password by itself must not be considered a config change that should trigger a keys reload. | [
"The",
"keys",
"config",
"is",
"changed",
"if",
"the",
"file",
"or",
"expiration",
"were",
"modified",
".",
"Changing",
"the",
"password",
"by",
"itself",
"must",
"not",
"be",
"considered",
"a",
"config",
"change",
"that",
"should",
"trigger",
"a",
"keys",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.token.ltpa/src/com/ibm/ws/security/token/ltpa/internal/LTPAConfigurationImpl.java#L214-L216 |
pravega/pravega | controller/src/main/java/io/pravega/controller/task/Stream/StreamTransactionMetadataTasks.java | StreamTransactionMetadataTasks.pingTxn | public CompletableFuture<PingTxnStatus> pingTxn(final String scope,
final String stream,
final UUID txId,
final long lease,
final OperationContext contextOpt) {
final OperationContext context = getNonNullOperationContext(scope, stream, contextOpt);
return pingTxnBody(scope, stream, txId, lease, context);
} | java | public CompletableFuture<PingTxnStatus> pingTxn(final String scope,
final String stream,
final UUID txId,
final long lease,
final OperationContext contextOpt) {
final OperationContext context = getNonNullOperationContext(scope, stream, contextOpt);
return pingTxnBody(scope, stream, txId, lease, context);
} | [
"public",
"CompletableFuture",
"<",
"PingTxnStatus",
">",
"pingTxn",
"(",
"final",
"String",
"scope",
",",
"final",
"String",
"stream",
",",
"final",
"UUID",
"txId",
",",
"final",
"long",
"lease",
",",
"final",
"OperationContext",
"contextOpt",
")",
"{",
"fina... | Transaction heartbeat, that increases transaction timeout by lease number of milliseconds.
@param scope Stream scope.
@param stream Stream name.
@param txId Transaction identifier.
@param lease Amount of time in milliseconds by which to extend the transaction lease.
@param contextOpt operational context
@return Transaction metadata along with the version of it record in the store. | [
"Transaction",
"heartbeat",
"that",
"increases",
"transaction",
"timeout",
"by",
"lease",
"number",
"of",
"milliseconds",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/task/Stream/StreamTransactionMetadataTasks.java#L212-L219 |
alkacon/opencms-core | src/org/opencms/jsp/CmsJspActionElement.java | CmsJspActionElement.getMessages | public CmsMessages getMessages(String bundleName, String language, String defaultLanguage) {
return getMessages(bundleName, language, "", "", defaultLanguage);
} | java | public CmsMessages getMessages(String bundleName, String language, String defaultLanguage) {
return getMessages(bundleName, language, "", "", defaultLanguage);
} | [
"public",
"CmsMessages",
"getMessages",
"(",
"String",
"bundleName",
",",
"String",
"language",
",",
"String",
"defaultLanguage",
")",
"{",
"return",
"getMessages",
"(",
"bundleName",
",",
"language",
",",
"\"\"",
",",
"\"\"",
",",
"defaultLanguage",
")",
";",
... | Generates an initialized instance of {@link CmsMessages} for
convenient access to localized resource bundles.<p>
@param bundleName the name of the ResourceBundle to use
@param language language identifier for the locale of the bundle
@param defaultLanguage default for the language, will be used
if language is null or empty String "", and defaultLanguage is not null
@return CmsMessages a message bundle initialized with the provided values | [
"Generates",
"an",
"initialized",
"instance",
"of",
"{",
"@link",
"CmsMessages",
"}",
"for",
"convenient",
"access",
"to",
"localized",
"resource",
"bundles",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspActionElement.java#L301-L304 |
jbundle/jbundle | base/model/src/main/java/org/jbundle/base/model/Utility.java | Utility.replaceResources | public static String replaceResources(String string, ResourceBundle reg, Map<String, Object> map, PropertyOwner propertyOwner, boolean systemProperties)
{
if (string != null)
if (string.indexOf('{') == -1)
return string;
return Utility.replaceResources(new StringBuilder(string), reg, map, propertyOwner, systemProperties).toString();
} | java | public static String replaceResources(String string, ResourceBundle reg, Map<String, Object> map, PropertyOwner propertyOwner, boolean systemProperties)
{
if (string != null)
if (string.indexOf('{') == -1)
return string;
return Utility.replaceResources(new StringBuilder(string), reg, map, propertyOwner, systemProperties).toString();
} | [
"public",
"static",
"String",
"replaceResources",
"(",
"String",
"string",
",",
"ResourceBundle",
"reg",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
",",
"PropertyOwner",
"propertyOwner",
",",
"boolean",
"systemProperties",
")",
"{",
"if",
"(",
"stri... | Replace the {} resources in this string.
@param reg
@param map A map of key/values
@param strResource
@return | [
"Replace",
"the",
"{}",
"resources",
"in",
"this",
"string",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/model/src/main/java/org/jbundle/base/model/Utility.java#L302-L308 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TransliteratorParser.java | TransliteratorParser.appendVariableDef | private void appendVariableDef(String name, StringBuffer buf) {
char[] ch = variableNames.get(name);
if (ch == null) {
// We allow one undefined variable so that variable definition
// statements work. For the first undefined variable we return
// the special placeholder variableLimit-1, and save the variable
// name.
if (undefinedVariableName == null) {
undefinedVariableName = name;
if (variableNext >= variableLimit) {
throw new RuntimeException("Private use variables exhausted");
}
buf.append(--variableLimit);
} else {
throw new IllegalIcuArgumentException("Undefined variable $"
+ name);
}
} else {
buf.append(ch);
}
} | java | private void appendVariableDef(String name, StringBuffer buf) {
char[] ch = variableNames.get(name);
if (ch == null) {
// We allow one undefined variable so that variable definition
// statements work. For the first undefined variable we return
// the special placeholder variableLimit-1, and save the variable
// name.
if (undefinedVariableName == null) {
undefinedVariableName = name;
if (variableNext >= variableLimit) {
throw new RuntimeException("Private use variables exhausted");
}
buf.append(--variableLimit);
} else {
throw new IllegalIcuArgumentException("Undefined variable $"
+ name);
}
} else {
buf.append(ch);
}
} | [
"private",
"void",
"appendVariableDef",
"(",
"String",
"name",
",",
"StringBuffer",
"buf",
")",
"{",
"char",
"[",
"]",
"ch",
"=",
"variableNames",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"ch",
"==",
"null",
")",
"{",
"// We allow one undefined variab... | Append the value of the given variable name to the given
StringBuffer.
@exception IllegalIcuArgumentException if the name is unknown. | [
"Append",
"the",
"value",
"of",
"the",
"given",
"variable",
"name",
"to",
"the",
"given",
"StringBuffer",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TransliteratorParser.java#L1542-L1562 |
apache/incubator-gobblin | gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/purger/HivePurgerSource.java | HivePurgerSource.sortHiveDatasets | protected List<HivePartitionDataset> sortHiveDatasets(List<HivePartitionDataset> datasets) {
Collections.sort(datasets, new Comparator<HivePartitionDataset>() {
@Override
public int compare(HivePartitionDataset o1, HivePartitionDataset o2) {
return o1.datasetURN().compareTo(o2.datasetURN());
}
});
return datasets;
} | java | protected List<HivePartitionDataset> sortHiveDatasets(List<HivePartitionDataset> datasets) {
Collections.sort(datasets, new Comparator<HivePartitionDataset>() {
@Override
public int compare(HivePartitionDataset o1, HivePartitionDataset o2) {
return o1.datasetURN().compareTo(o2.datasetURN());
}
});
return datasets;
} | [
"protected",
"List",
"<",
"HivePartitionDataset",
">",
"sortHiveDatasets",
"(",
"List",
"<",
"HivePartitionDataset",
">",
"datasets",
")",
"{",
"Collections",
".",
"sort",
"(",
"datasets",
",",
"new",
"Comparator",
"<",
"HivePartitionDataset",
">",
"(",
")",
"{"... | Sort all HiveDatasets on the basis of complete name ie dbName.tableName | [
"Sort",
"all",
"HiveDatasets",
"on",
"the",
"basis",
"of",
"complete",
"name",
"ie",
"dbName",
".",
"tableName"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/purger/HivePurgerSource.java#L220-L228 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/IntegerField.java | IntegerField.moveSQLToField | public void moveSQLToField(ResultSet resultset, int iColumn) throws SQLException
{
int sResult = resultset.getInt(iColumn);
if (resultset.wasNull())
this.setString(Constants.BLANK, false, DBConstants.READ_MOVE); // Null value
else
{
if ((!this.isNullable()) && (sResult == NAN))
this.setString(Constants.BLANK, false, DBConstants.READ_MOVE); // Null value
else
this.setValue(sResult, false, DBConstants.READ_MOVE);
}
} | java | public void moveSQLToField(ResultSet resultset, int iColumn) throws SQLException
{
int sResult = resultset.getInt(iColumn);
if (resultset.wasNull())
this.setString(Constants.BLANK, false, DBConstants.READ_MOVE); // Null value
else
{
if ((!this.isNullable()) && (sResult == NAN))
this.setString(Constants.BLANK, false, DBConstants.READ_MOVE); // Null value
else
this.setValue(sResult, false, DBConstants.READ_MOVE);
}
} | [
"public",
"void",
"moveSQLToField",
"(",
"ResultSet",
"resultset",
",",
"int",
"iColumn",
")",
"throws",
"SQLException",
"{",
"int",
"sResult",
"=",
"resultset",
".",
"getInt",
"(",
"iColumn",
")",
";",
"if",
"(",
"resultset",
".",
"wasNull",
"(",
")",
")"... | Move the physical binary data to this SQL parameter row.
@param resultset The resultset to get the SQL data from.
@param iColumn the column in the resultset that has my data.
@exception SQLException From SQL calls. | [
"Move",
"the",
"physical",
"binary",
"data",
"to",
"this",
"SQL",
"parameter",
"row",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/IntegerField.java#L160-L172 |
jcuda/jcusparse | JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java | JCusparse.cusparseScsc2dense | public static int cusparseScsc2dense(
cusparseHandle handle,
int m,
int n,
cusparseMatDescr descrA,
Pointer cscSortedValA,
Pointer cscSortedRowIndA,
Pointer cscSortedColPtrA,
Pointer A,
int lda)
{
return checkResult(cusparseScsc2denseNative(handle, m, n, descrA, cscSortedValA, cscSortedRowIndA, cscSortedColPtrA, A, lda));
} | java | public static int cusparseScsc2dense(
cusparseHandle handle,
int m,
int n,
cusparseMatDescr descrA,
Pointer cscSortedValA,
Pointer cscSortedRowIndA,
Pointer cscSortedColPtrA,
Pointer A,
int lda)
{
return checkResult(cusparseScsc2denseNative(handle, m, n, descrA, cscSortedValA, cscSortedRowIndA, cscSortedColPtrA, A, lda));
} | [
"public",
"static",
"int",
"cusparseScsc2dense",
"(",
"cusparseHandle",
"handle",
",",
"int",
"m",
",",
"int",
"n",
",",
"cusparseMatDescr",
"descrA",
",",
"Pointer",
"cscSortedValA",
",",
"Pointer",
"cscSortedRowIndA",
",",
"Pointer",
"cscSortedColPtrA",
",",
"Po... | Description: This routine converts a sparse matrix in CSC storage format
to a dense matrix. | [
"Description",
":",
"This",
"routine",
"converts",
"a",
"sparse",
"matrix",
"in",
"CSC",
"storage",
"format",
"to",
"a",
"dense",
"matrix",
"."
] | train | https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L11497-L11509 |
xwiki/xwiki-commons | xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/XARMojo.java | XARMojo.addFileElements | private void addFileElements(Collection<ArchiveEntry> files, Element filesElement) throws Exception
{
for (ArchiveEntry entry : files) {
// Don't add files in META-INF to the package.xml file
if (entry.getName().indexOf("META-INF") == -1) {
XWikiDocument xdoc = getDocFromXML(entry.getFile());
String reference = xdoc.getReference();
Element element = new DOMElement(FILE_TAG);
element.setText(reference);
element.addAttribute("language", xdoc.getLocale());
element.addAttribute("defaultAction", "0");
// Add configured properties
XAREntry cfgEntry = getEntryMap().get(reference);
if (cfgEntry != null && cfgEntry.getType() != null) {
element.addAttribute("type", cfgEntry.getType());
}
filesElement.add(element);
}
}
} | java | private void addFileElements(Collection<ArchiveEntry> files, Element filesElement) throws Exception
{
for (ArchiveEntry entry : files) {
// Don't add files in META-INF to the package.xml file
if (entry.getName().indexOf("META-INF") == -1) {
XWikiDocument xdoc = getDocFromXML(entry.getFile());
String reference = xdoc.getReference();
Element element = new DOMElement(FILE_TAG);
element.setText(reference);
element.addAttribute("language", xdoc.getLocale());
element.addAttribute("defaultAction", "0");
// Add configured properties
XAREntry cfgEntry = getEntryMap().get(reference);
if (cfgEntry != null && cfgEntry.getType() != null) {
element.addAttribute("type", cfgEntry.getType());
}
filesElement.add(element);
}
}
} | [
"private",
"void",
"addFileElements",
"(",
"Collection",
"<",
"ArchiveEntry",
">",
"files",
",",
"Element",
"filesElement",
")",
"throws",
"Exception",
"{",
"for",
"(",
"ArchiveEntry",
"entry",
":",
"files",
")",
"{",
"// Don't add files in META-INF to the package.xml... | Add all the XML elements under the <files> element (the list of files present in the XAR).
@param files the list of files that we want to include in the generated package XML file.
@param filesElement the files element to which to add to | [
"Add",
"all",
"the",
"XML",
"elements",
"under",
"the",
"<",
";",
"files>",
";",
"element",
"(",
"the",
"list",
"of",
"files",
"present",
"in",
"the",
"XAR",
")",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/XARMojo.java#L366-L387 |
shekhargulati/strman-java | src/main/java/strman/Strman.java | Strman.endsWith | public static boolean endsWith(final String value, final String search, final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return endsWith(value, search, value.length(), caseSensitive);
} | java | public static boolean endsWith(final String value, final String search, final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return endsWith(value, search, value.length(), caseSensitive);
} | [
"public",
"static",
"boolean",
"endsWith",
"(",
"final",
"String",
"value",
",",
"final",
"String",
"search",
",",
"final",
"boolean",
"caseSensitive",
")",
"{",
"validate",
"(",
"value",
",",
"NULL_STRING_PREDICATE",
",",
"NULL_STRING_MSG_SUPPLIER",
")",
";",
"... | Test if value ends with search.
@param value input string
@param search string to search
@param caseSensitive true or false
@return true or false | [
"Test",
"if",
"value",
"ends",
"with",
"search",
"."
] | train | https://github.com/shekhargulati/strman-java/blob/d0c2a10a6273fd6082f084e95156653ca55ce1be/src/main/java/strman/Strman.java#L269-L272 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-tasks/src/main/java/com/google/cloud/tasks/v2beta2/CloudTasksClient.java | CloudTasksClient.acknowledgeTask | public final void acknowledgeTask(TaskName name, Timestamp scheduleTime) {
AcknowledgeTaskRequest request =
AcknowledgeTaskRequest.newBuilder()
.setName(name == null ? null : name.toString())
.setScheduleTime(scheduleTime)
.build();
acknowledgeTask(request);
} | java | public final void acknowledgeTask(TaskName name, Timestamp scheduleTime) {
AcknowledgeTaskRequest request =
AcknowledgeTaskRequest.newBuilder()
.setName(name == null ? null : name.toString())
.setScheduleTime(scheduleTime)
.build();
acknowledgeTask(request);
} | [
"public",
"final",
"void",
"acknowledgeTask",
"(",
"TaskName",
"name",
",",
"Timestamp",
"scheduleTime",
")",
"{",
"AcknowledgeTaskRequest",
"request",
"=",
"AcknowledgeTaskRequest",
".",
"newBuilder",
"(",
")",
".",
"setName",
"(",
"name",
"==",
"null",
"?",
"n... | Acknowledges a pull task.
<p>The worker, that is, the entity that
[leased][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] this task must call this method to
indicate that the work associated with the task has finished.
<p>The worker must acknowledge a task within the
[lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration] or the lease will
expire and the task will become available to be leased again. After the task is acknowledged,
it will not be returned by a later
[LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks],
[GetTask][google.cloud.tasks.v2beta2.CloudTasks.GetTask], or
[ListTasks][google.cloud.tasks.v2beta2.CloudTasks.ListTasks].
<p>Sample code:
<pre><code>
try (CloudTasksClient cloudTasksClient = CloudTasksClient.create()) {
TaskName name = TaskName.of("[PROJECT]", "[LOCATION]", "[QUEUE]", "[TASK]");
Timestamp scheduleTime = Timestamp.newBuilder().build();
cloudTasksClient.acknowledgeTask(name, scheduleTime);
}
</code></pre>
@param name Required.
<p>The task name. For example:
`projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`
@param scheduleTime Required.
<p>The task's current schedule time, available in the
[schedule_time][google.cloud.tasks.v2beta2.Task.schedule_time] returned by
[LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] response or
[RenewLease][google.cloud.tasks.v2beta2.CloudTasks.RenewLease] response. This restriction
is to ensure that your worker currently holds the lease.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Acknowledges",
"a",
"pull",
"task",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-tasks/src/main/java/com/google/cloud/tasks/v2beta2/CloudTasksClient.java#L2196-L2204 |
prestodb/presto | presto-main/src/main/java/com/facebook/presto/sql/planner/LiteralEncoder.java | LiteralEncoder.toRowExpression | public static RowExpression toRowExpression(Object object, Type type)
{
requireNonNull(type, "type is null");
if (object instanceof RowExpression) {
return (RowExpression) object;
}
if (object == null) {
return constantNull(type);
}
return constant(object, type);
} | java | public static RowExpression toRowExpression(Object object, Type type)
{
requireNonNull(type, "type is null");
if (object instanceof RowExpression) {
return (RowExpression) object;
}
if (object == null) {
return constantNull(type);
}
return constant(object, type);
} | [
"public",
"static",
"RowExpression",
"toRowExpression",
"(",
"Object",
"object",
",",
"Type",
"type",
")",
"{",
"requireNonNull",
"(",
"type",
",",
"\"type is null\"",
")",
";",
"if",
"(",
"object",
"instanceof",
"RowExpression",
")",
"{",
"return",
"(",
"RowE... | Unlike toExpression, toRowExpression should be very straightforward given object is serializable | [
"Unlike",
"toExpression",
"toRowExpression",
"should",
"be",
"very",
"straightforward",
"given",
"object",
"is",
"serializable"
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/sql/planner/LiteralEncoder.java#L101-L114 |
EsotericSoftware/jsonbeans | src/com/esotericsoftware/jsonbeans/Json.java | Json.writeValue | public void writeValue (String name, Object value, Class knownType) {
try {
writer.name(name);
} catch (IOException ex) {
throw new JsonException(ex);
}
writeValue(value, knownType, null);
} | java | public void writeValue (String name, Object value, Class knownType) {
try {
writer.name(name);
} catch (IOException ex) {
throw new JsonException(ex);
}
writeValue(value, knownType, null);
} | [
"public",
"void",
"writeValue",
"(",
"String",
"name",
",",
"Object",
"value",
",",
"Class",
"knownType",
")",
"{",
"try",
"{",
"writer",
".",
"name",
"(",
"name",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"JsonExcepti... | Writes the value as a field on the current JSON object, writing the class of the object if it differs from the specified
known type.
@param value May be null.
@param knownType May be null if the type is unknown.
@see #writeValue(String, Object, Class, Class) | [
"Writes",
"the",
"value",
"as",
"a",
"field",
"on",
"the",
"current",
"JSON",
"object",
"writing",
"the",
"class",
"of",
"the",
"object",
"if",
"it",
"differs",
"from",
"the",
"specified",
"known",
"type",
"."
] | train | https://github.com/EsotericSoftware/jsonbeans/blob/ff4502d0ff86cc77aa5c61d47371d0c66c14fe2f/src/com/esotericsoftware/jsonbeans/Json.java#L398-L405 |
theHilikus/JRoboCom | jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/World.java | World.addFirst | public void addFirst(Robot eve) {
if (eve.getData().getGeneration() != 0) {
throw new IllegalArgumentException("Robot is not first generation");
}
if (getBotsCount(eve.getData().getTeamId(), false) > 0) {
throw new IllegalArgumentException(
"Provided robot is not the first from its team. Use add(Robot, Robot) instead");
}
Point newPosition;
do {
// TODO: check this, looks biased
int x = generator.nextInt(GameSettings.getInstance().BOARD_SIZE);
int y = generator.nextInt(GameSettings.getInstance().BOARD_SIZE);
newPosition = new Point(x, y);
} while (isOccupied(newPosition));
addCommon(eve, newPosition);
} | java | public void addFirst(Robot eve) {
if (eve.getData().getGeneration() != 0) {
throw new IllegalArgumentException("Robot is not first generation");
}
if (getBotsCount(eve.getData().getTeamId(), false) > 0) {
throw new IllegalArgumentException(
"Provided robot is not the first from its team. Use add(Robot, Robot) instead");
}
Point newPosition;
do {
// TODO: check this, looks biased
int x = generator.nextInt(GameSettings.getInstance().BOARD_SIZE);
int y = generator.nextInt(GameSettings.getInstance().BOARD_SIZE);
newPosition = new Point(x, y);
} while (isOccupied(newPosition));
addCommon(eve, newPosition);
} | [
"public",
"void",
"addFirst",
"(",
"Robot",
"eve",
")",
"{",
"if",
"(",
"eve",
".",
"getData",
"(",
")",
".",
"getGeneration",
"(",
")",
"!=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Robot is not first generation\"",
")",
";",
"}... | Adds the first robot of a team. The robot becomes owned by <i>this</i> object
@param eve the first robot of the player
@throws IllegalArgumentException if the robot is not the first from its team or it exists
already | [
"Adds",
"the",
"first",
"robot",
"of",
"a",
"team",
".",
"The",
"robot",
"becomes",
"owned",
"by",
"<i",
">",
"this<",
"/",
"i",
">",
"object"
] | train | https://github.com/theHilikus/JRoboCom/blob/0e31c1ecf1006e35f68c229ff66c37640effffac/jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/World.java#L117-L135 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java | JBBPDslBuilder.BitArray | public JBBPDslBuilder BitArray(final String name, final JBBPBitNumber bits, final String sizeExpression) {
final Item item = new Item(BinType.BIT_ARRAY, name, this.byteOrder);
item.bitNumber = bits;
item.sizeExpression = assertExpressionChars(sizeExpression);
this.addItem(item);
return this;
} | java | public JBBPDslBuilder BitArray(final String name, final JBBPBitNumber bits, final String sizeExpression) {
final Item item = new Item(BinType.BIT_ARRAY, name, this.byteOrder);
item.bitNumber = bits;
item.sizeExpression = assertExpressionChars(sizeExpression);
this.addItem(item);
return this;
} | [
"public",
"JBBPDslBuilder",
"BitArray",
"(",
"final",
"String",
"name",
",",
"final",
"JBBPBitNumber",
"bits",
",",
"final",
"String",
"sizeExpression",
")",
"{",
"final",
"Item",
"item",
"=",
"new",
"Item",
"(",
"BinType",
".",
"BIT_ARRAY",
",",
"name",
","... | Add named bit array with size calculated through expression.
@param name name of the array, if null then anonymous one
@param bits length of the field, must not be null
@param sizeExpression expression to be used to calculate array size, must not be null
@return the builder instance, must not be null | [
"Add",
"named",
"bit",
"array",
"with",
"size",
"calculated",
"through",
"expression",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L722-L728 |
javers/javers | javers-core/src/main/java/org/javers/repository/jql/QueryBuilder.java | QueryBuilder.byInstanceId | public static QueryBuilder byInstanceId(Object localId, Class entityClass){
Validate.argumentsAreNotNull(localId, entityClass);
return new QueryBuilder(new IdFilterDefinition(instanceId(localId, entityClass)));
} | java | public static QueryBuilder byInstanceId(Object localId, Class entityClass){
Validate.argumentsAreNotNull(localId, entityClass);
return new QueryBuilder(new IdFilterDefinition(instanceId(localId, entityClass)));
} | [
"public",
"static",
"QueryBuilder",
"byInstanceId",
"(",
"Object",
"localId",
",",
"Class",
"entityClass",
")",
"{",
"Validate",
".",
"argumentsAreNotNull",
"(",
"localId",
",",
"entityClass",
")",
";",
"return",
"new",
"QueryBuilder",
"(",
"new",
"IdFilterDefinit... | Query for selecting changes (or snapshots) made on a concrete Entity instance.
<br/><br/>
For example, last changes on "bob" Person:
<pre>
javers.findChanges( QueryBuilder.byInstanceId("bob", Person.class).build() );
</pre> | [
"Query",
"for",
"selecting",
"changes",
"(",
"or",
"snapshots",
")",
"made",
"on",
"a",
"concrete",
"Entity",
"instance",
".",
"<br",
"/",
">",
"<br",
"/",
">"
] | train | https://github.com/javers/javers/blob/a51511be7d8bcee3e1812db8b7e69a45330b4e14/javers-core/src/main/java/org/javers/repository/jql/QueryBuilder.java#L89-L92 |
alkacon/opencms-core | src/org/opencms/search/fields/CmsSearchField.java | CmsSearchField.addUninvertingMappings | public static void addUninvertingMappings(Map<String, Type> uninvertingMap) {
uninvertingMap.put(FIELD_CATEGORY, Type.SORTED);
uninvertingMap.put(FIELD_CONTENT, Type.SORTED);
uninvertingMap.put(FIELD_CONTENT_BLOB, Type.SORTED);
uninvertingMap.put(FIELD_CONTENT_LOCALES, Type.SORTED);
uninvertingMap.put(FIELD_DATE_CONTENT, Type.SORTED);
uninvertingMap.put(FIELD_DATE_CREATED, Type.SORTED);
uninvertingMap.put(FIELD_DATE_CREATED_LOOKUP, Type.SORTED);
uninvertingMap.put(FIELD_DATE_EXPIRED, Type.SORTED);
uninvertingMap.put(FIELD_DATE_LASTMODIFIED, Type.SORTED);
uninvertingMap.put(FIELD_DATE_LASTMODIFIED_LOOKUP, Type.SORTED);
uninvertingMap.put(FIELD_DATE_LOOKUP_SUFFIX, Type.SORTED);
uninvertingMap.put(FIELD_DATE_RELEASED, Type.SORTED);
uninvertingMap.put(FIELD_DEPENDENCY_TYPE, Type.SORTED);
uninvertingMap.put(FIELD_DESCRIPTION, Type.SORTED);
uninvertingMap.put(FIELD_DYNAMIC_EXACT, Type.SORTED);
uninvertingMap.put(FIELD_DYNAMIC_PROPERTIES, Type.SORTED);
uninvertingMap.put(FIELD_EXCERPT, Type.SORTED);
uninvertingMap.put(FIELD_FILENAME, Type.SORTED);
uninvertingMap.put(FIELD_ID, Type.SORTED);
uninvertingMap.put(FIELD_KEYWORDS, Type.SORTED);
uninvertingMap.put(FIELD_LINK, Type.SORTED);
uninvertingMap.put(FIELD_META, Type.SORTED);
uninvertingMap.put(FIELD_MIMETYPE, Type.SORTED);
uninvertingMap.put(FIELD_PARENT_FOLDERS, Type.SORTED);
uninvertingMap.put(FIELD_PATH, Type.SORTED);
uninvertingMap.put(FIELD_PREFIX_DEPENDENCY, Type.SORTED);
uninvertingMap.put(FIELD_PREFIX_DYNAMIC, Type.SORTED);
uninvertingMap.put(FIELD_PREFIX_TEXT, Type.SORTED);
uninvertingMap.put(FIELD_PRIORITY, Type.SORTED);
uninvertingMap.put(FIELD_RESOURCE_LOCALES, Type.SORTED);
uninvertingMap.put(FIELD_SCORE, Type.SORTED);
uninvertingMap.put(FIELD_SEARCH_EXCLUDE, Type.SORTED);
uninvertingMap.put(FIELD_SIZE, Type.SORTED);
uninvertingMap.put(FIELD_SORT_TITLE, Type.SORTED);
uninvertingMap.put(FIELD_STATE, Type.SORTED);
uninvertingMap.put(FIELD_SUFFIX, Type.SORTED);
uninvertingMap.put(FIELD_TEXT, Type.SORTED);
uninvertingMap.put(FIELD_TITLE, Type.SORTED);
uninvertingMap.put(FIELD_TITLE_UNSTORED, Type.SORTED);
uninvertingMap.put(FIELD_TYPE, Type.SORTED);
uninvertingMap.put(FIELD_USER_CREATED, Type.SORTED);
uninvertingMap.put(FIELD_USER_LAST_MODIFIED, Type.SORTED);
uninvertingMap.put(FIELD_VERSION, Type.SORTED);
} | java | public static void addUninvertingMappings(Map<String, Type> uninvertingMap) {
uninvertingMap.put(FIELD_CATEGORY, Type.SORTED);
uninvertingMap.put(FIELD_CONTENT, Type.SORTED);
uninvertingMap.put(FIELD_CONTENT_BLOB, Type.SORTED);
uninvertingMap.put(FIELD_CONTENT_LOCALES, Type.SORTED);
uninvertingMap.put(FIELD_DATE_CONTENT, Type.SORTED);
uninvertingMap.put(FIELD_DATE_CREATED, Type.SORTED);
uninvertingMap.put(FIELD_DATE_CREATED_LOOKUP, Type.SORTED);
uninvertingMap.put(FIELD_DATE_EXPIRED, Type.SORTED);
uninvertingMap.put(FIELD_DATE_LASTMODIFIED, Type.SORTED);
uninvertingMap.put(FIELD_DATE_LASTMODIFIED_LOOKUP, Type.SORTED);
uninvertingMap.put(FIELD_DATE_LOOKUP_SUFFIX, Type.SORTED);
uninvertingMap.put(FIELD_DATE_RELEASED, Type.SORTED);
uninvertingMap.put(FIELD_DEPENDENCY_TYPE, Type.SORTED);
uninvertingMap.put(FIELD_DESCRIPTION, Type.SORTED);
uninvertingMap.put(FIELD_DYNAMIC_EXACT, Type.SORTED);
uninvertingMap.put(FIELD_DYNAMIC_PROPERTIES, Type.SORTED);
uninvertingMap.put(FIELD_EXCERPT, Type.SORTED);
uninvertingMap.put(FIELD_FILENAME, Type.SORTED);
uninvertingMap.put(FIELD_ID, Type.SORTED);
uninvertingMap.put(FIELD_KEYWORDS, Type.SORTED);
uninvertingMap.put(FIELD_LINK, Type.SORTED);
uninvertingMap.put(FIELD_META, Type.SORTED);
uninvertingMap.put(FIELD_MIMETYPE, Type.SORTED);
uninvertingMap.put(FIELD_PARENT_FOLDERS, Type.SORTED);
uninvertingMap.put(FIELD_PATH, Type.SORTED);
uninvertingMap.put(FIELD_PREFIX_DEPENDENCY, Type.SORTED);
uninvertingMap.put(FIELD_PREFIX_DYNAMIC, Type.SORTED);
uninvertingMap.put(FIELD_PREFIX_TEXT, Type.SORTED);
uninvertingMap.put(FIELD_PRIORITY, Type.SORTED);
uninvertingMap.put(FIELD_RESOURCE_LOCALES, Type.SORTED);
uninvertingMap.put(FIELD_SCORE, Type.SORTED);
uninvertingMap.put(FIELD_SEARCH_EXCLUDE, Type.SORTED);
uninvertingMap.put(FIELD_SIZE, Type.SORTED);
uninvertingMap.put(FIELD_SORT_TITLE, Type.SORTED);
uninvertingMap.put(FIELD_STATE, Type.SORTED);
uninvertingMap.put(FIELD_SUFFIX, Type.SORTED);
uninvertingMap.put(FIELD_TEXT, Type.SORTED);
uninvertingMap.put(FIELD_TITLE, Type.SORTED);
uninvertingMap.put(FIELD_TITLE_UNSTORED, Type.SORTED);
uninvertingMap.put(FIELD_TYPE, Type.SORTED);
uninvertingMap.put(FIELD_USER_CREATED, Type.SORTED);
uninvertingMap.put(FIELD_USER_LAST_MODIFIED, Type.SORTED);
uninvertingMap.put(FIELD_VERSION, Type.SORTED);
} | [
"public",
"static",
"void",
"addUninvertingMappings",
"(",
"Map",
"<",
"String",
",",
"Type",
">",
"uninvertingMap",
")",
"{",
"uninvertingMap",
".",
"put",
"(",
"FIELD_CATEGORY",
",",
"Type",
".",
"SORTED",
")",
";",
"uninvertingMap",
".",
"put",
"(",
"FIEL... | To allow sorting on a field the field must be added to the map given to {@link org.apache.solr.uninverting.UninvertingReader#wrap(org.apache.lucene.index.DirectoryReader, Map)}.
The method adds all default fields.
@param uninvertingMap the map to which the fields are added. | [
"To",
"allow",
"sorting",
"on",
"a",
"field",
"the",
"field",
"must",
"be",
"added",
"to",
"the",
"map",
"given",
"to",
"{"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/fields/CmsSearchField.java#L311-L356 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/api/TemplatesApi.java | TemplatesApi.listBulkRecipients | public BulkRecipientsResponse listBulkRecipients(String accountId, String templateId, String recipientId) throws ApiException {
return listBulkRecipients(accountId, templateId, recipientId, null);
} | java | public BulkRecipientsResponse listBulkRecipients(String accountId, String templateId, String recipientId) throws ApiException {
return listBulkRecipients(accountId, templateId, recipientId, null);
} | [
"public",
"BulkRecipientsResponse",
"listBulkRecipients",
"(",
"String",
"accountId",
",",
"String",
"templateId",
",",
"String",
"recipientId",
")",
"throws",
"ApiException",
"{",
"return",
"listBulkRecipients",
"(",
"accountId",
",",
"templateId",
",",
"recipientId",
... | Gets the bulk recipient file from a template.
Retrieves the bulk recipient file information from a template that has a bulk recipient.
@param accountId The external account number (int) or account ID Guid. (required)
@param templateId The ID of the template being accessed. (required)
@param recipientId The ID of the recipient being accessed. (required)
@return BulkRecipientsResponse | [
"Gets",
"the",
"bulk",
"recipient",
"file",
"from",
"a",
"template",
".",
"Retrieves",
"the",
"bulk",
"recipient",
"file",
"information",
"from",
"a",
"template",
"that",
"has",
"a",
"bulk",
"recipient",
"."
] | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/TemplatesApi.java#L2000-L2002 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java | BoxApiFile.getAddCommentRequest | public BoxRequestsFile.AddCommentToFile getAddCommentRequest(String fileId, String message) {
BoxRequestsFile.AddCommentToFile request = new BoxRequestsFile.AddCommentToFile(fileId, message, getCommentUrl(), mSession);
return request;
} | java | public BoxRequestsFile.AddCommentToFile getAddCommentRequest(String fileId, String message) {
BoxRequestsFile.AddCommentToFile request = new BoxRequestsFile.AddCommentToFile(fileId, message, getCommentUrl(), mSession);
return request;
} | [
"public",
"BoxRequestsFile",
".",
"AddCommentToFile",
"getAddCommentRequest",
"(",
"String",
"fileId",
",",
"String",
"message",
")",
"{",
"BoxRequestsFile",
".",
"AddCommentToFile",
"request",
"=",
"new",
"BoxRequestsFile",
".",
"AddCommentToFile",
"(",
"fileId",
","... | Gets a request that adds a comment to a file
@param fileId id of the file to add the comment to
@param message message for the comment that will be added
@return request to add a comment to a file | [
"Gets",
"a",
"request",
"that",
"adds",
"a",
"comment",
"to",
"a",
"file"
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L282-L285 |
http-builder-ng/http-builder-ng | http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java | HttpBuilder.postAsync | public CompletableFuture<Object> postAsync(final Consumer<HttpConfig> configuration) {
return CompletableFuture.supplyAsync(() -> post(configuration), getExecutor());
} | java | public CompletableFuture<Object> postAsync(final Consumer<HttpConfig> configuration) {
return CompletableFuture.supplyAsync(() -> post(configuration), getExecutor());
} | [
"public",
"CompletableFuture",
"<",
"Object",
">",
"postAsync",
"(",
"final",
"Consumer",
"<",
"HttpConfig",
">",
"configuration",
")",
"{",
"return",
"CompletableFuture",
".",
"supplyAsync",
"(",
"(",
")",
"->",
"post",
"(",
"configuration",
")",
",",
"getExe... | Executes an asynchronous POST request on the configured URI (asynchronous alias to `post(Consumer)`), with additional configuration provided by the
configuration function.
This method is generally used for Java-specific configuration.
[source,java]
----
HttpBuilder http = HttpBuilder.configure(config -> {
config.getRequest().setUri("http://localhost:10101");
});
CompletableFuture<Object> future = http.postAsync(config -> {
config.getRequest().getUri().setPath("/foo");
});
Object result = future.get();
----
The `configuration` function allows additional configuration for this request based on the {@link HttpConfig} interface.
@param configuration the additional configuration closure (delegated to {@link HttpConfig})
@return the resulting content wrapped in a {@link CompletableFuture} | [
"Executes",
"an",
"asynchronous",
"POST",
"request",
"on",
"the",
"configured",
"URI",
"(",
"asynchronous",
"alias",
"to",
"post",
"(",
"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#L827-L829 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/model/QueryParameters.java | QueryParameters.updatePosition | public QueryParameters updatePosition(String key, Integer position) {
while (this.order.size() < position + 1) {
this.order.add(null);
}
this.order.set(position, processKey(key));
return this;
} | java | public QueryParameters updatePosition(String key, Integer position) {
while (this.order.size() < position + 1) {
this.order.add(null);
}
this.order.set(position, processKey(key));
return this;
} | [
"public",
"QueryParameters",
"updatePosition",
"(",
"String",
"key",
",",
"Integer",
"position",
")",
"{",
"while",
"(",
"this",
".",
"order",
".",
"size",
"(",
")",
"<",
"position",
"+",
"1",
")",
"{",
"this",
".",
"order",
".",
"add",
"(",
"null",
... | Updates position of specified key
@param key Key
@param position Position
@return this instance of QueryParameters | [
"Updates",
"position",
"of",
"specified",
"key"
] | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/model/QueryParameters.java#L314-L322 |
IBM/ibm-cos-sdk-java | ibm-cos-java-sdk-core/src/main/java/com/ibm/cloud/objectstorage/internal/http/JsonErrorCodeParser.java | JsonErrorCodeParser.parseErrorCodeFromHeader | private String parseErrorCodeFromHeader(Map<String, String> httpHeaders) {
String headerValue = httpHeaders.get(X_AMZN_ERROR_TYPE);
if (headerValue != null) {
int separator = headerValue.indexOf(':');
if (separator != -1) {
headerValue = headerValue.substring(0, separator);
}
}
return headerValue;
} | java | private String parseErrorCodeFromHeader(Map<String, String> httpHeaders) {
String headerValue = httpHeaders.get(X_AMZN_ERROR_TYPE);
if (headerValue != null) {
int separator = headerValue.indexOf(':');
if (separator != -1) {
headerValue = headerValue.substring(0, separator);
}
}
return headerValue;
} | [
"private",
"String",
"parseErrorCodeFromHeader",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"httpHeaders",
")",
"{",
"String",
"headerValue",
"=",
"httpHeaders",
".",
"get",
"(",
"X_AMZN_ERROR_TYPE",
")",
";",
"if",
"(",
"headerValue",
"!=",
"null",
")",
... | Attempt to parse the error code from the response headers. Returns null if information is not
present in the header. | [
"Attempt",
"to",
"parse",
"the",
"error",
"code",
"from",
"the",
"response",
"headers",
".",
"Returns",
"null",
"if",
"information",
"is",
"not",
"present",
"in",
"the",
"header",
"."
] | train | https://github.com/IBM/ibm-cos-sdk-java/blob/d0bb2dd754c328a05e7dba8dc42e28b271b6daf2/ibm-cos-java-sdk-core/src/main/java/com/ibm/cloud/objectstorage/internal/http/JsonErrorCodeParser.java#L63-L72 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/reading/StreamSegmentReadIndex.java | StreamSegmentReadIndex.triggerFutureReads | private void triggerFutureReads(Collection<FutureReadResultEntry> futureReads) {
for (FutureReadResultEntry r : futureReads) {
ReadResultEntry entry = getSingleReadResultEntry(r.getStreamSegmentOffset(), r.getRequestedReadLength());
assert entry != null : "Serving a StorageReadResultEntry with a null result";
assert !(entry instanceof FutureReadResultEntry) : "Serving a FutureReadResultEntry with another FutureReadResultEntry.";
log.trace("{}: triggerFutureReads (Offset = {}, Type = {}).", this.traceObjectId, r.getStreamSegmentOffset(), entry.getType());
if (entry.getType() == ReadResultEntryType.EndOfStreamSegment) {
// We have attempted to read beyond the end of the stream. Fail the read request with the appropriate message.
r.fail(new StreamSegmentSealedException(String.format("StreamSegment has been sealed at offset %d. There can be no more reads beyond this offset.", this.metadata.getLength())));
} else {
if (!entry.getContent().isDone()) {
// Normally, all Future Reads are served from Cache, since they reflect data that has just been appended.
// However, it's possible that after recovery, we get a read for some data that we do not have in the
// cache (but it's not a tail read) - this data exists in Storage but our StorageLength has not yet been
// updated. As such, the only solution we have is to return a FutureRead which will be satisfied when
// the Writer updates the StorageLength (and trigger future reads). In that scenario, entry we get
// will likely not be auto-fetched, so we need to request the content.
entry.requestContent(this.config.getStorageReadDefaultTimeout());
}
CompletableFuture<ReadResultEntryContents> entryContent = entry.getContent();
entryContent.thenAccept(r::complete);
Futures.exceptionListener(entryContent, r::fail);
}
}
} | java | private void triggerFutureReads(Collection<FutureReadResultEntry> futureReads) {
for (FutureReadResultEntry r : futureReads) {
ReadResultEntry entry = getSingleReadResultEntry(r.getStreamSegmentOffset(), r.getRequestedReadLength());
assert entry != null : "Serving a StorageReadResultEntry with a null result";
assert !(entry instanceof FutureReadResultEntry) : "Serving a FutureReadResultEntry with another FutureReadResultEntry.";
log.trace("{}: triggerFutureReads (Offset = {}, Type = {}).", this.traceObjectId, r.getStreamSegmentOffset(), entry.getType());
if (entry.getType() == ReadResultEntryType.EndOfStreamSegment) {
// We have attempted to read beyond the end of the stream. Fail the read request with the appropriate message.
r.fail(new StreamSegmentSealedException(String.format("StreamSegment has been sealed at offset %d. There can be no more reads beyond this offset.", this.metadata.getLength())));
} else {
if (!entry.getContent().isDone()) {
// Normally, all Future Reads are served from Cache, since they reflect data that has just been appended.
// However, it's possible that after recovery, we get a read for some data that we do not have in the
// cache (but it's not a tail read) - this data exists in Storage but our StorageLength has not yet been
// updated. As such, the only solution we have is to return a FutureRead which will be satisfied when
// the Writer updates the StorageLength (and trigger future reads). In that scenario, entry we get
// will likely not be auto-fetched, so we need to request the content.
entry.requestContent(this.config.getStorageReadDefaultTimeout());
}
CompletableFuture<ReadResultEntryContents> entryContent = entry.getContent();
entryContent.thenAccept(r::complete);
Futures.exceptionListener(entryContent, r::fail);
}
}
} | [
"private",
"void",
"triggerFutureReads",
"(",
"Collection",
"<",
"FutureReadResultEntry",
">",
"futureReads",
")",
"{",
"for",
"(",
"FutureReadResultEntry",
"r",
":",
"futureReads",
")",
"{",
"ReadResultEntry",
"entry",
"=",
"getSingleReadResultEntry",
"(",
"r",
"."... | Triggers all the Future Reads in the given collection.
@param futureReads The Future Reads to trigger. | [
"Triggers",
"all",
"the",
"Future",
"Reads",
"in",
"the",
"given",
"collection",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/reading/StreamSegmentReadIndex.java#L578-L604 |
super-csv/super-csv | super-csv/src/main/java/org/supercsv/cellprocessor/ParseChar.java | ParseChar.execute | public Object execute(final Object value, final CsvContext context) {
validateInputNotNull(value, context);
final Character result;
if( value instanceof Character ) {
result = (Character) value;
} else if( value instanceof String ) {
final String stringValue = (String) value;
if( stringValue.length() == 1 ) {
result = Character.valueOf(stringValue.charAt(0));
} else {
throw new SuperCsvCellProcessorException(String.format(
"'%s' cannot be parsed as a char as it is a String longer than 1 character", stringValue), context,
this);
}
} else {
final String actualClassName = value.getClass().getName();
throw new SuperCsvCellProcessorException(String.format(
"the input value should be of type Character or String but is of type %s", actualClassName), context,
this);
}
return next.execute(result, context);
} | java | public Object execute(final Object value, final CsvContext context) {
validateInputNotNull(value, context);
final Character result;
if( value instanceof Character ) {
result = (Character) value;
} else if( value instanceof String ) {
final String stringValue = (String) value;
if( stringValue.length() == 1 ) {
result = Character.valueOf(stringValue.charAt(0));
} else {
throw new SuperCsvCellProcessorException(String.format(
"'%s' cannot be parsed as a char as it is a String longer than 1 character", stringValue), context,
this);
}
} else {
final String actualClassName = value.getClass().getName();
throw new SuperCsvCellProcessorException(String.format(
"the input value should be of type Character or String but is of type %s", actualClassName), context,
this);
}
return next.execute(result, context);
} | [
"public",
"Object",
"execute",
"(",
"final",
"Object",
"value",
",",
"final",
"CsvContext",
"context",
")",
"{",
"validateInputNotNull",
"(",
"value",
",",
"context",
")",
";",
"final",
"Character",
"result",
";",
"if",
"(",
"value",
"instanceof",
"Character",... | {@inheritDoc}
@throws SuperCsvCellProcessorException
if value is null, isn't a Character or String, or is a String of multiple characters | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv/src/main/java/org/supercsv/cellprocessor/ParseChar.java#L57-L80 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.deleteCertificateAsync | public Observable<DeletedCertificateBundle> deleteCertificateAsync(String vaultBaseUrl, String certificateName) {
return deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1<ServiceResponse<DeletedCertificateBundle>, DeletedCertificateBundle>() {
@Override
public DeletedCertificateBundle call(ServiceResponse<DeletedCertificateBundle> response) {
return response.body();
}
});
} | java | public Observable<DeletedCertificateBundle> deleteCertificateAsync(String vaultBaseUrl, String certificateName) {
return deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1<ServiceResponse<DeletedCertificateBundle>, DeletedCertificateBundle>() {
@Override
public DeletedCertificateBundle call(ServiceResponse<DeletedCertificateBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DeletedCertificateBundle",
">",
"deleteCertificateAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"certificateName",
")",
"{",
"return",
"deleteCertificateWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"certificateName",
")",
".",
... | Deletes a certificate from a specified key vault.
Deletes all versions of a certificate object along with its associated policy. Delete certificate cannot be used to remove individual versions of a certificate object. This operation requires the certificates/delete 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 DeletedCertificateBundle object | [
"Deletes",
"a",
"certificate",
"from",
"a",
"specified",
"key",
"vault",
".",
"Deletes",
"all",
"versions",
"of",
"a",
"certificate",
"object",
"along",
"with",
"its",
"associated",
"policy",
".",
"Delete",
"certificate",
"cannot",
"be",
"used",
"to",
"remove"... | 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#L5352-L5359 |
elki-project/elki | elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/arrays/DoubleIntegerArrayQuickSort.java | DoubleIntegerArrayQuickSort.sortReverse | public static void sortReverse(double[] keys, int[] values, int start, int end) {
quickSortReverse(keys, values, start, end);
} | java | public static void sortReverse(double[] keys, int[] values, int start, int end) {
quickSortReverse(keys, values, start, end);
} | [
"public",
"static",
"void",
"sortReverse",
"(",
"double",
"[",
"]",
"keys",
",",
"int",
"[",
"]",
"values",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"quickSortReverse",
"(",
"keys",
",",
"values",
",",
"start",
",",
"end",
")",
";",
"}"
] | Sort the array using the given comparator.
@param keys Keys for sorting
@param values Values for sorting
@param start First index
@param end Last index (exclusive) | [
"Sort",
"the",
"array",
"using",
"the",
"given",
"comparator",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/arrays/DoubleIntegerArrayQuickSort.java#L226-L228 |
easymock/objenesis | tck/src/main/java/org/objenesis/tck/search/ClassEnumerator.java | ClassEnumerator.getClassesForPackage | public static SortedSet<String> getClassesForPackage(Package pkg, ClassLoader classLoader) {
SortedSet<String> classes = new TreeSet<>(new Comparator<String>() {
public int compare(String o1, String o2) {
String simpleName1 = getSimpleName(o1);
String simpleName2 = getSimpleName(o2);
return simpleName1.compareTo(simpleName2);
}
private String getSimpleName(String className) {
return className.substring(className.lastIndexOf('.'));
}
});
String pkgname = pkg.getName();
String relPath = pkgname.replace('.', '/');
// Get a File object for the package
Enumeration<URL> resources;
try {
resources = classLoader.getResources(relPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
while(resources.hasMoreElements()) {
URL resource = resources.nextElement();
if (resource.toString().startsWith("jar:")) {
processJarfile(resource, pkgname, classes);
} else {
processDirectory(new File(resource.getPath()), pkgname, classes);
}
}
return classes;
} | java | public static SortedSet<String> getClassesForPackage(Package pkg, ClassLoader classLoader) {
SortedSet<String> classes = new TreeSet<>(new Comparator<String>() {
public int compare(String o1, String o2) {
String simpleName1 = getSimpleName(o1);
String simpleName2 = getSimpleName(o2);
return simpleName1.compareTo(simpleName2);
}
private String getSimpleName(String className) {
return className.substring(className.lastIndexOf('.'));
}
});
String pkgname = pkg.getName();
String relPath = pkgname.replace('.', '/');
// Get a File object for the package
Enumeration<URL> resources;
try {
resources = classLoader.getResources(relPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
while(resources.hasMoreElements()) {
URL resource = resources.nextElement();
if (resource.toString().startsWith("jar:")) {
processJarfile(resource, pkgname, classes);
} else {
processDirectory(new File(resource.getPath()), pkgname, classes);
}
}
return classes;
} | [
"public",
"static",
"SortedSet",
"<",
"String",
">",
"getClassesForPackage",
"(",
"Package",
"pkg",
",",
"ClassLoader",
"classLoader",
")",
"{",
"SortedSet",
"<",
"String",
">",
"classes",
"=",
"new",
"TreeSet",
"<>",
"(",
"new",
"Comparator",
"<",
"String",
... | Return all the classes in this package recursively.
@param pkg the searched package
@param classLoader class loader where to look for classes
@return list of full class names | [
"Return",
"all",
"the",
"classes",
"in",
"this",
"package",
"recursively",
"."
] | train | https://github.com/easymock/objenesis/blob/8f601c8ba1aa20bbc640e2c2bc48d55df52c489f/tck/src/main/java/org/objenesis/tck/search/ClassEnumerator.java#L97-L131 |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/ssh2/TransportProtocol.java | TransportProtocol.startService | public void startService(String servicename) throws SshException {
ByteArrayWriter baw = new ByteArrayWriter();
try {
baw.write(SSH_MSG_SERVICE_REQUEST);
baw.writeString(servicename);
if (Log.isDebugEnabled()) {
Log.debug(this, "Sending SSH_MSG_SERVICE_REQUEST");
}
sendMessage(baw.toByteArray(), true);
byte[] msg;
do {
msg = readMessage();
} while (processMessage(msg) || msg[0] != SSH_MSG_SERVICE_ACCEPT);
if (Log.isDebugEnabled()) {
Log.debug(this, "Received SSH_MSG_SERVICE_ACCEPT");
}
} catch (IOException ex) {
throw new SshException(ex, SshException.INTERNAL_ERROR);
} finally {
try {
baw.close();
} catch (IOException e) {
}
}
} | java | public void startService(String servicename) throws SshException {
ByteArrayWriter baw = new ByteArrayWriter();
try {
baw.write(SSH_MSG_SERVICE_REQUEST);
baw.writeString(servicename);
if (Log.isDebugEnabled()) {
Log.debug(this, "Sending SSH_MSG_SERVICE_REQUEST");
}
sendMessage(baw.toByteArray(), true);
byte[] msg;
do {
msg = readMessage();
} while (processMessage(msg) || msg[0] != SSH_MSG_SERVICE_ACCEPT);
if (Log.isDebugEnabled()) {
Log.debug(this, "Received SSH_MSG_SERVICE_ACCEPT");
}
} catch (IOException ex) {
throw new SshException(ex, SshException.INTERNAL_ERROR);
} finally {
try {
baw.close();
} catch (IOException e) {
}
}
} | [
"public",
"void",
"startService",
"(",
"String",
"servicename",
")",
"throws",
"SshException",
"{",
"ByteArrayWriter",
"baw",
"=",
"new",
"ByteArrayWriter",
"(",
")",
";",
"try",
"{",
"baw",
".",
"write",
"(",
"SSH_MSG_SERVICE_REQUEST",
")",
";",
"baw",
".",
... | Request that the remote server starts a transport protocol service. This
is only available in CLIENT_MODE.
@param servicename
@throws IOException | [
"Request",
"that",
"the",
"remote",
"server",
"starts",
"a",
"transport",
"protocol",
"service",
".",
"This",
"is",
"only",
"available",
"in",
"CLIENT_MODE",
"."
] | train | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/ssh2/TransportProtocol.java#L1383-L1415 |
denisneuling/cctrl.jar | cctrl-api-client/src/main/java/com/cloudcontrolled/api/client/util/RequestUtil.java | RequestUtil.resolveAndSetQueryPart | public static <T> WebClient resolveAndSetQueryPart(Request<T> request, WebClient webClient) {
HashMap<String, String> queryParts = resolveQueryPart(request);
Iterator<String> iterator = queryParts.keySet().iterator();
if (!iterator.hasNext()) {
return webClient;
} else {
while (iterator.hasNext()) {
String key = iterator.next();
String value = queryParts.get(key);
webClient = webClient.replaceQueryParam(key, value);
}
}
return webClient;
} | java | public static <T> WebClient resolveAndSetQueryPart(Request<T> request, WebClient webClient) {
HashMap<String, String> queryParts = resolveQueryPart(request);
Iterator<String> iterator = queryParts.keySet().iterator();
if (!iterator.hasNext()) {
return webClient;
} else {
while (iterator.hasNext()) {
String key = iterator.next();
String value = queryParts.get(key);
webClient = webClient.replaceQueryParam(key, value);
}
}
return webClient;
} | [
"public",
"static",
"<",
"T",
">",
"WebClient",
"resolveAndSetQueryPart",
"(",
"Request",
"<",
"T",
">",
"request",
",",
"WebClient",
"webClient",
")",
"{",
"HashMap",
"<",
"String",
",",
"String",
">",
"queryParts",
"=",
"resolveQueryPart",
"(",
"request",
... | <p>resolveAndSetQueryPart.</p>
@param request a {@link com.cloudcontrolled.api.request.Request} object.
@param webClient a {@link org.apache.cxf.jaxrs.client.WebClient} object.
@param <T> a T object.
@return a {@link org.apache.cxf.jaxrs.client.WebClient} object.
@since 0.1.1 | [
"<p",
">",
"resolveAndSetQueryPart",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/denisneuling/cctrl.jar/blob/37450d824f4dc5ecbcc81c61e48f1ec876ca2de8/cctrl-api-client/src/main/java/com/cloudcontrolled/api/client/util/RequestUtil.java#L114-L127 |
wildfly-extras/wildfly-camel | subsystem/core/src/main/java/org/wildfly/extension/camel/SpringCamelContextFactory.java | SpringCamelContextFactory.createCamelContextList | public static List<SpringCamelContext> createCamelContextList(byte[] bytes, ClassLoader classsLoader) throws Exception {
SpringCamelContextBootstrap bootstrap = new SpringCamelContextBootstrap(bytes, classsLoader);
return bootstrap.createSpringCamelContexts();
} | java | public static List<SpringCamelContext> createCamelContextList(byte[] bytes, ClassLoader classsLoader) throws Exception {
SpringCamelContextBootstrap bootstrap = new SpringCamelContextBootstrap(bytes, classsLoader);
return bootstrap.createSpringCamelContexts();
} | [
"public",
"static",
"List",
"<",
"SpringCamelContext",
">",
"createCamelContextList",
"(",
"byte",
"[",
"]",
"bytes",
",",
"ClassLoader",
"classsLoader",
")",
"throws",
"Exception",
"{",
"SpringCamelContextBootstrap",
"bootstrap",
"=",
"new",
"SpringCamelContextBootstra... | Create a {@link SpringCamelContext} list from the given bytes | [
"Create",
"a",
"{"
] | train | https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/subsystem/core/src/main/java/org/wildfly/extension/camel/SpringCamelContextFactory.java#L64-L67 |
couchbase/couchbase-lite-java-core | src/main/java/com/couchbase/lite/Manager.java | Manager.getExistingDatabase | @InterfaceAudience.Public
public Database getExistingDatabase(String name) throws CouchbaseLiteException {
DatabaseOptions options = getDefaultOptions(name);
return openDatabase(name, options);
} | java | @InterfaceAudience.Public
public Database getExistingDatabase(String name) throws CouchbaseLiteException {
DatabaseOptions options = getDefaultOptions(name);
return openDatabase(name, options);
} | [
"@",
"InterfaceAudience",
".",
"Public",
"public",
"Database",
"getExistingDatabase",
"(",
"String",
"name",
")",
"throws",
"CouchbaseLiteException",
"{",
"DatabaseOptions",
"options",
"=",
"getDefaultOptions",
"(",
"name",
")",
";",
"return",
"openDatabase",
"(",
"... | <p>
Returns the database with the given name, or null if it doesn't exist.
Multiple calls with the same name will return the same {@link Database} instance.
<p/>
<p>
This is equivalent to calling {@link #openDatabase(String, DatabaseOptions)}
with a default set of options.
</p> | [
"<p",
">",
"Returns",
"the",
"database",
"with",
"the",
"given",
"name",
"or",
"null",
"if",
"it",
"doesn",
"t",
"exist",
".",
"Multiple",
"calls",
"with",
"the",
"same",
"name",
"will",
"return",
"the",
"same",
"{"
] | train | https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Manager.java#L318-L322 |
Credntia/MVBarcodeReader | mvbarcodereader/src/main/java/devliving/online/mvbarcodereader/BarcodeGraphicTracker.java | BarcodeGraphicTracker.onUpdate | @Override
public void onUpdate(Detector.Detections<Barcode> detectionResults, Barcode item) {
mOverlay.add(mGraphic);
mGraphic.updateItem(item);
} | java | @Override
public void onUpdate(Detector.Detections<Barcode> detectionResults, Barcode item) {
mOverlay.add(mGraphic);
mGraphic.updateItem(item);
} | [
"@",
"Override",
"public",
"void",
"onUpdate",
"(",
"Detector",
".",
"Detections",
"<",
"Barcode",
">",
"detectionResults",
",",
"Barcode",
"item",
")",
"{",
"mOverlay",
".",
"add",
"(",
"mGraphic",
")",
";",
"mGraphic",
".",
"updateItem",
"(",
"item",
")"... | Update the position/characteristics of the item within the overlay. | [
"Update",
"the",
"position",
"/",
"characteristics",
"of",
"the",
"item",
"within",
"the",
"overlay",
"."
] | train | https://github.com/Credntia/MVBarcodeReader/blob/2a2561f1c3b4d4e3c046a341fbf23a31eabfda8d/mvbarcodereader/src/main/java/devliving/online/mvbarcodereader/BarcodeGraphicTracker.java#L59-L63 |
airlift/slice | src/main/java/io/airlift/slice/Slices.java | Slices.wrappedBooleanArray | public static Slice wrappedBooleanArray(boolean[] array, int offset, int length)
{
if (length == 0) {
return EMPTY_SLICE;
}
return new Slice(array, offset, length);
} | java | public static Slice wrappedBooleanArray(boolean[] array, int offset, int length)
{
if (length == 0) {
return EMPTY_SLICE;
}
return new Slice(array, offset, length);
} | [
"public",
"static",
"Slice",
"wrappedBooleanArray",
"(",
"boolean",
"[",
"]",
"array",
",",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"if",
"(",
"length",
"==",
"0",
")",
"{",
"return",
"EMPTY_SLICE",
";",
"}",
"return",
"new",
"Slice",
"(",
"ar... | Creates a slice over the specified array range.
@param offset the array position at which the slice begins
@param length the number of array positions to include in the slice | [
"Creates",
"a",
"slice",
"over",
"the",
"specified",
"array",
"range",
"."
] | train | https://github.com/airlift/slice/blob/7166cb0319e3655f8ba15f5a7ccf3d2f721c1242/src/main/java/io/airlift/slice/Slices.java#L171-L177 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.serviceName_serviceMonitoring_monitoringId_alert_email_alertId_PUT | public void serviceName_serviceMonitoring_monitoringId_alert_email_alertId_PUT(String serviceName, Long monitoringId, Long alertId, OvhEmailAlert body) throws IOException {
String qPath = "/dedicated/server/{serviceName}/serviceMonitoring/{monitoringId}/alert/email/{alertId}";
StringBuilder sb = path(qPath, serviceName, monitoringId, alertId);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void serviceName_serviceMonitoring_monitoringId_alert_email_alertId_PUT(String serviceName, Long monitoringId, Long alertId, OvhEmailAlert body) throws IOException {
String qPath = "/dedicated/server/{serviceName}/serviceMonitoring/{monitoringId}/alert/email/{alertId}";
StringBuilder sb = path(qPath, serviceName, monitoringId, alertId);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"serviceName_serviceMonitoring_monitoringId_alert_email_alertId_PUT",
"(",
"String",
"serviceName",
",",
"Long",
"monitoringId",
",",
"Long",
"alertId",
",",
"OvhEmailAlert",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicate... | Alter this object properties
REST: PUT /dedicated/server/{serviceName}/serviceMonitoring/{monitoringId}/alert/email/{alertId}
@param body [required] New object properties
@param serviceName [required] The internal name of your dedicated server
@param monitoringId [required] This monitoring id
@param alertId [required] This monitoring id | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L2208-L2212 |
infinispan/infinispan | server/core/src/main/java/org/infinispan/server/core/transport/ExtendedByteBuf.java | ExtendedByteBuf.readString | public static String readString(ByteBuf bf) {
byte[] bytes = readRangedBytes(bf);
return bytes.length > 0 ? new String(bytes, CharsetUtil.UTF_8) : "";
} | java | public static String readString(ByteBuf bf) {
byte[] bytes = readRangedBytes(bf);
return bytes.length > 0 ? new String(bytes, CharsetUtil.UTF_8) : "";
} | [
"public",
"static",
"String",
"readString",
"(",
"ByteBuf",
"bf",
")",
"{",
"byte",
"[",
"]",
"bytes",
"=",
"readRangedBytes",
"(",
"bf",
")",
";",
"return",
"bytes",
".",
"length",
">",
"0",
"?",
"new",
"String",
"(",
"bytes",
",",
"CharsetUtil",
".",... | Reads length of String and then returns an UTF-8 formatted String of such length.
If the length is 0, an empty String is returned. | [
"Reads",
"length",
"of",
"String",
"and",
"then",
"returns",
"an",
"UTF",
"-",
"8",
"formatted",
"String",
"of",
"such",
"length",
".",
"If",
"the",
"length",
"is",
"0",
"an",
"empty",
"String",
"is",
"returned",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/core/src/main/java/org/infinispan/server/core/transport/ExtendedByteBuf.java#L58-L61 |
eFaps/eFaps-Kernel | src/main/java/org/efaps/init/StartupDatabaseConnection.java | StartupDatabaseConnection.configureDataSource | protected static void configureDataSource(final Context _compCtx,
final String _classDSFactory,
final Map<String, String> _propConnection)
throws StartupException
{
final Reference ref = new Reference(DataSource.class.getName(), _classDSFactory, null);
for (final Entry<String, String> entry : _propConnection.entrySet()) {
ref.add(new StringRefAddr(entry.getKey(), entry.getValue()));
}
try {
Util.bind(_compCtx, "env/" + INamingBinds.RESOURCE_DATASOURCE, ref);
Util.bind(_compCtx, "test", ref);
} catch (final NamingException e) {
throw new StartupException("could not bind JDBC pooling class '" + _classDSFactory + "'", e);
// CHECKSTYLE:OFF
} catch (final Exception e) {
// CHECKSTYLE:ON
throw new StartupException("coud not get object instance of factory '" + _classDSFactory + "'", e);
}
} | java | protected static void configureDataSource(final Context _compCtx,
final String _classDSFactory,
final Map<String, String> _propConnection)
throws StartupException
{
final Reference ref = new Reference(DataSource.class.getName(), _classDSFactory, null);
for (final Entry<String, String> entry : _propConnection.entrySet()) {
ref.add(new StringRefAddr(entry.getKey(), entry.getValue()));
}
try {
Util.bind(_compCtx, "env/" + INamingBinds.RESOURCE_DATASOURCE, ref);
Util.bind(_compCtx, "test", ref);
} catch (final NamingException e) {
throw new StartupException("could not bind JDBC pooling class '" + _classDSFactory + "'", e);
// CHECKSTYLE:OFF
} catch (final Exception e) {
// CHECKSTYLE:ON
throw new StartupException("coud not get object instance of factory '" + _classDSFactory + "'", e);
}
} | [
"protected",
"static",
"void",
"configureDataSource",
"(",
"final",
"Context",
"_compCtx",
",",
"final",
"String",
"_classDSFactory",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"_propConnection",
")",
"throws",
"StartupException",
"{",
"final",
"Refer... | The class defined with parameter <code>_classDSFactory</code> initialized and bind to
{@link #RESOURCE_DATASOURCE}. The initialized class must implement interface {@link DataSource}. As JDBC
connection properties the map <code>_propConneciton</code> is used.
@param _compCtx Java root naming context
@param _classDSFactory class name of the SQL data source factory
@param _propConnection map of properties for the JDBC connection
@throws StartupException on error | [
"The",
"class",
"defined",
"with",
"parameter",
"<code",
">",
"_classDSFactory<",
"/",
"code",
">",
"initialized",
"and",
"bind",
"to",
"{",
"@link",
"#RESOURCE_DATASOURCE",
"}",
".",
"The",
"initialized",
"class",
"must",
"implement",
"interface",
"{",
"@link",... | train | https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/init/StartupDatabaseConnection.java#L374-L393 |
wildfly/wildfly-core | server/src/main/java/org/jboss/as/server/SystemExiter.java | SystemExiter.logAndExit | public static void logAndExit(ExitLogger logger, int status) {
logBeforeExit(logger);
getExiter().exit(status);
// If we get here, the exiter didn't really exit. So we
// must be embedded or something, or perhaps in a test case
// Reset the logged flag so we can log again the next time
// someone "exits"
logged.set(false);
} | java | public static void logAndExit(ExitLogger logger, int status) {
logBeforeExit(logger);
getExiter().exit(status);
// If we get here, the exiter didn't really exit. So we
// must be embedded or something, or perhaps in a test case
// Reset the logged flag so we can log again the next time
// someone "exits"
logged.set(false);
} | [
"public",
"static",
"void",
"logAndExit",
"(",
"ExitLogger",
"logger",
",",
"int",
"status",
")",
"{",
"logBeforeExit",
"(",
"logger",
")",
";",
"getExiter",
"(",
")",
".",
"exit",
"(",
"status",
")",
";",
"// If we get here, the exiter didn't really exit. So we",... | Calls {@link #logBeforeExit(ExitLogger)} and then invokes the {@link Exiter}.
@param logger logger the logger. Cannot be {@code null}
@param status the status code to provide to the exiter | [
"Calls",
"{"
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/SystemExiter.java#L96-L104 |
netty/netty | handler/src/main/java/io/netty/handler/ssl/PemPrivateKey.java | PemPrivateKey.toPEM | static PemEncoded toPEM(ByteBufAllocator allocator, boolean useDirect, PrivateKey key) {
// We can take a shortcut if the private key happens to be already
// PEM/PKCS#8 encoded. This is the ideal case and reason why all
// this exists. It allows the user to pass pre-encoded bytes straight
// into OpenSSL without having to do any of the extra work.
if (key instanceof PemEncoded) {
return ((PemEncoded) key).retain();
}
byte[] bytes = key.getEncoded();
if (bytes == null) {
throw new IllegalArgumentException(key.getClass().getName() + " does not support encoding");
}
return toPEM(allocator, useDirect, bytes);
} | java | static PemEncoded toPEM(ByteBufAllocator allocator, boolean useDirect, PrivateKey key) {
// We can take a shortcut if the private key happens to be already
// PEM/PKCS#8 encoded. This is the ideal case and reason why all
// this exists. It allows the user to pass pre-encoded bytes straight
// into OpenSSL without having to do any of the extra work.
if (key instanceof PemEncoded) {
return ((PemEncoded) key).retain();
}
byte[] bytes = key.getEncoded();
if (bytes == null) {
throw new IllegalArgumentException(key.getClass().getName() + " does not support encoding");
}
return toPEM(allocator, useDirect, bytes);
} | [
"static",
"PemEncoded",
"toPEM",
"(",
"ByteBufAllocator",
"allocator",
",",
"boolean",
"useDirect",
",",
"PrivateKey",
"key",
")",
"{",
"// We can take a shortcut if the private key happens to be already",
"// PEM/PKCS#8 encoded. This is the ideal case and reason why all",
"// this e... | Creates a {@link PemEncoded} value from the {@link PrivateKey}. | [
"Creates",
"a",
"{"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/PemPrivateKey.java#L54-L69 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/internal/AbstractPendingLinkingCandidate.java | AbstractPendingLinkingCandidate.compareByArgumentTypes | protected CandidateCompareResult compareByArgumentTypes(AbstractPendingLinkingCandidate<?> other, int leftBoxing, int rightBoxing, int leftDemand, int rightDemand) {
if (leftDemand != rightDemand) {
if (leftDemand < rightDemand)
return CandidateCompareResult.THIS;
return CandidateCompareResult.OTHER;
}
return compareByBoxing(leftBoxing, rightBoxing);
} | java | protected CandidateCompareResult compareByArgumentTypes(AbstractPendingLinkingCandidate<?> other, int leftBoxing, int rightBoxing, int leftDemand, int rightDemand) {
if (leftDemand != rightDemand) {
if (leftDemand < rightDemand)
return CandidateCompareResult.THIS;
return CandidateCompareResult.OTHER;
}
return compareByBoxing(leftBoxing, rightBoxing);
} | [
"protected",
"CandidateCompareResult",
"compareByArgumentTypes",
"(",
"AbstractPendingLinkingCandidate",
"<",
"?",
">",
"other",
",",
"int",
"leftBoxing",
",",
"int",
"rightBoxing",
",",
"int",
"leftDemand",
",",
"int",
"rightDemand",
")",
"{",
"if",
"(",
"leftDeman... | Compare this linking candidate with the given {@code other} candidate at {@code argumentIndex}
Returns {@code CandidateCompareResult#THIS} if this candidate is better, {@code CandidateCompareResult#OTHER} if the
right candidate was better, {@code CandidateCompareResult#AMBIGUOUS} if both candidates are valid
but ambiguous or {@code CandidateCompareResult#EQUALLY_INVALID} if both candidates are
ambiguous but erroneous.
@param other the other candidate (the rhs of the comparison)
@param leftBoxing the number of required boxing conversions if this candidate was chosen
@param rightBoxing the number of required boxing conversions if the other candidate was chosen
@param leftDemand the number of required demand conversions if this candidate was chosen
@param rightDemand the number of required demand conversions if the other candidate was chosen | [
"Compare",
"this",
"linking",
"candidate",
"with",
"the",
"given",
"{",
"@code",
"other",
"}",
"candidate",
"at",
"{",
"@code",
"argumentIndex",
"}"
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/internal/AbstractPendingLinkingCandidate.java#L946-L953 |
PistoiaHELM/HELM2NotationToolkit | src/main/java/org/helm/notation2/tools/HELM2NotationUtils.java | HELM2NotationUtils.changeIDs | private static String changeIDs(String text, Map<String, String> mapIds) {
String result = text;
for (String key : mapIds.keySet()) {
result = result.replace(key, mapIds.get(key));
}
return result;
} | java | private static String changeIDs(String text, Map<String, String> mapIds) {
String result = text;
for (String key : mapIds.keySet()) {
result = result.replace(key, mapIds.get(key));
}
return result;
} | [
"private",
"static",
"String",
"changeIDs",
"(",
"String",
"text",
",",
"Map",
"<",
"String",
",",
"String",
">",
"mapIds",
")",
"{",
"String",
"result",
"=",
"text",
";",
"for",
"(",
"String",
"key",
":",
"mapIds",
".",
"keySet",
"(",
")",
")",
"{",... | method to change the ids in a text according to map
@param text input text
@param mapIds Map of old Id's value and new Id's
@return text with changed ids | [
"method",
"to",
"change",
"the",
"ids",
"in",
"a",
"text",
"according",
"to",
"map"
] | train | https://github.com/PistoiaHELM/HELM2NotationToolkit/blob/ac5bb01fd5b4082134a8ef226bbe2ff0f60fcd38/src/main/java/org/helm/notation2/tools/HELM2NotationUtils.java#L341-L347 |
graphhopper/graphhopper | core/src/main/java/com/graphhopper/routing/InstructionsOutgoingEdges.java | InstructionsOutgoingEdges.isLeavingCurrentStreet | public boolean isLeavingCurrentStreet(String prevName, String name) {
if (InstructionsHelper.isNameSimilar(name, prevName)) {
return false;
}
// If flags are changing, there might be a chance we find these flags on a different edge
boolean checkFlag = currentEdge.getFlags() != prevEdge.getFlags();
for (EdgeIteratorState edge : allowedOutgoingEdges) {
String edgeName = edge.getName();
IntsRef edgeFlag = edge.getFlags();
// leave the current street || enter a different street
if (isTheSameStreet(prevName, prevEdge.getFlags(), edgeName, edgeFlag, checkFlag)
|| isTheSameStreet(name, currentEdge.getFlags(), edgeName, edgeFlag, checkFlag)) {
return true;
}
}
return false;
} | java | public boolean isLeavingCurrentStreet(String prevName, String name) {
if (InstructionsHelper.isNameSimilar(name, prevName)) {
return false;
}
// If flags are changing, there might be a chance we find these flags on a different edge
boolean checkFlag = currentEdge.getFlags() != prevEdge.getFlags();
for (EdgeIteratorState edge : allowedOutgoingEdges) {
String edgeName = edge.getName();
IntsRef edgeFlag = edge.getFlags();
// leave the current street || enter a different street
if (isTheSameStreet(prevName, prevEdge.getFlags(), edgeName, edgeFlag, checkFlag)
|| isTheSameStreet(name, currentEdge.getFlags(), edgeName, edgeFlag, checkFlag)) {
return true;
}
}
return false;
} | [
"public",
"boolean",
"isLeavingCurrentStreet",
"(",
"String",
"prevName",
",",
"String",
"name",
")",
"{",
"if",
"(",
"InstructionsHelper",
".",
"isNameSimilar",
"(",
"name",
",",
"prevName",
")",
")",
"{",
"return",
"false",
";",
"}",
"// If flags are changing,... | If the name and prevName changes this method checks if either the current street is continued on a
different edge or if the edge we are turning onto is continued on a different edge.
If either of these properties is true, we can be quite certain that a turn instruction should be provided. | [
"If",
"the",
"name",
"and",
"prevName",
"changes",
"this",
"method",
"checks",
"if",
"either",
"the",
"current",
"street",
"is",
"continued",
"on",
"a",
"different",
"edge",
"or",
"if",
"the",
"edge",
"we",
"are",
"turning",
"onto",
"is",
"continued",
"on"... | train | https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/InstructionsOutgoingEdges.java#L181-L198 |
google/closure-templates | java/src/com/google/template/soy/data/SanitizedContents.java | SanitizedContents.constantUri | public static SanitizedContent constantUri(@CompileTimeConstant final String constant) {
return fromConstant(constant, ContentKind.URI, Dir.LTR);
} | java | public static SanitizedContent constantUri(@CompileTimeConstant final String constant) {
return fromConstant(constant, ContentKind.URI, Dir.LTR);
} | [
"public",
"static",
"SanitizedContent",
"constantUri",
"(",
"@",
"CompileTimeConstant",
"final",
"String",
"constant",
")",
"{",
"return",
"fromConstant",
"(",
"constant",
",",
"ContentKind",
".",
"URI",
",",
"Dir",
".",
"LTR",
")",
";",
"}"
] | Wraps an assumed-safe URI constant.
<p>This only accepts compile-time constants, based on the assumption that URLs that are
controlled by the application (and not user input) are considered safe. | [
"Wraps",
"an",
"assumed",
"-",
"safe",
"URI",
"constant",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SanitizedContents.java#L188-L190 |
httl/httl | httl/src/main/java/httl/spi/codecs/json/JSONObject.java | JSONObject.getFloat | public float getFloat(String key, float def) {
Object tmp = objectMap.get(key);
return tmp != null && tmp instanceof Number ? ((Number) tmp)
.floatValue() : def;
} | java | public float getFloat(String key, float def) {
Object tmp = objectMap.get(key);
return tmp != null && tmp instanceof Number ? ((Number) tmp)
.floatValue() : def;
} | [
"public",
"float",
"getFloat",
"(",
"String",
"key",
",",
"float",
"def",
")",
"{",
"Object",
"tmp",
"=",
"objectMap",
".",
"get",
"(",
"key",
")",
";",
"return",
"tmp",
"!=",
"null",
"&&",
"tmp",
"instanceof",
"Number",
"?",
"(",
"(",
"Number",
")",... | get float value.
@param key key.
@param def default value.
@return value or default value. | [
"get",
"float",
"value",
"."
] | train | https://github.com/httl/httl/blob/e13e00f4ab41252a8f53d6dafd4a6610be9dcaad/httl/src/main/java/httl/spi/codecs/json/JSONObject.java#L89-L93 |
michael-rapp/AndroidMaterialValidation | library/src/main/java/de/mrapp/android/validation/Validators.java | Validators.beginsWithUppercaseLetter | public static Validator<CharSequence> beginsWithUppercaseLetter(@NonNull final Context context,
@StringRes final int resourceId) {
return new BeginsWithUppercaseLetterValidator(context, resourceId);
} | java | public static Validator<CharSequence> beginsWithUppercaseLetter(@NonNull final Context context,
@StringRes final int resourceId) {
return new BeginsWithUppercaseLetterValidator(context, resourceId);
} | [
"public",
"static",
"Validator",
"<",
"CharSequence",
">",
"beginsWithUppercaseLetter",
"(",
"@",
"NonNull",
"final",
"Context",
"context",
",",
"@",
"StringRes",
"final",
"int",
"resourceId",
")",
"{",
"return",
"new",
"BeginsWithUppercaseLetterValidator",
"(",
"co... | Creates and returns a validator, which allows to validate texts to ensure, that they begin
with an uppercase letter. Empty texts are also accepted.
@param context
The context, which should be used to retrieve the error message, as an instance of
the class {@link Context}. The context may not be null
@param resourceId
The resource ID of the string resource, which contains the error message, which
should be set, as an {@link Integer} value. The resource ID must correspond to a
valid string resource
@return The validator, which has been created, as an instance of the type {@link Validator} | [
"Creates",
"and",
"returns",
"a",
"validator",
"which",
"allows",
"to",
"validate",
"texts",
"to",
"ensure",
"that",
"they",
"begin",
"with",
"an",
"uppercase",
"letter",
".",
"Empty",
"texts",
"are",
"also",
"accepted",
"."
] | train | https://github.com/michael-rapp/AndroidMaterialValidation/blob/ac8693baeac7abddf2e38a47da4c1849d4661a8b/library/src/main/java/de/mrapp/android/validation/Validators.java#L809-L812 |
tempodb/tempodb-java | src/main/java/com/tempodb/Client.java | Client.readMultiDataPoints | public Cursor<MultiDataPoint> readMultiDataPoints(Filter filter, Interval interval, DateTimeZone timezone, Rollup rollup, Interpolation interpolation) {
checkNotNull(filter);
checkNotNull(interval);
checkNotNull(timezone);
URI uri = null;
try {
URIBuilder builder = new URIBuilder(String.format("/%s/multi/", API_VERSION));
addFilterToURI(builder, filter);
addInterpolationToURI(builder, interpolation);
addIntervalToURI(builder, interval);
addRollupToURI(builder, rollup);
addTimeZoneToURI(builder, timezone);
uri = builder.build();
} catch (URISyntaxException e) {
String message = String.format("Could not build URI with inputs: filter: %s, interval: %s, rollup: %s, timezone: %s", filter, interval, rollup, timezone);
throw new IllegalArgumentException(message, e);
}
Cursor<MultiDataPoint> cursor = new MultiDataPointCursor(uri, this);
return cursor;
} | java | public Cursor<MultiDataPoint> readMultiDataPoints(Filter filter, Interval interval, DateTimeZone timezone, Rollup rollup, Interpolation interpolation) {
checkNotNull(filter);
checkNotNull(interval);
checkNotNull(timezone);
URI uri = null;
try {
URIBuilder builder = new URIBuilder(String.format("/%s/multi/", API_VERSION));
addFilterToURI(builder, filter);
addInterpolationToURI(builder, interpolation);
addIntervalToURI(builder, interval);
addRollupToURI(builder, rollup);
addTimeZoneToURI(builder, timezone);
uri = builder.build();
} catch (URISyntaxException e) {
String message = String.format("Could not build URI with inputs: filter: %s, interval: %s, rollup: %s, timezone: %s", filter, interval, rollup, timezone);
throw new IllegalArgumentException(message, e);
}
Cursor<MultiDataPoint> cursor = new MultiDataPointCursor(uri, this);
return cursor;
} | [
"public",
"Cursor",
"<",
"MultiDataPoint",
">",
"readMultiDataPoints",
"(",
"Filter",
"filter",
",",
"Interval",
"interval",
",",
"DateTimeZone",
"timezone",
",",
"Rollup",
"rollup",
",",
"Interpolation",
"interpolation",
")",
"{",
"checkNotNull",
"(",
"filter",
"... | Returns a cursor of multi-datapoints specified by a series filter.
This endpoint allows one to request datapoints for multiple series in one call.
@param filter The series filter
@param interval An interval of time for the query (start/end datetimes)
@param timezone The time zone for the returned datapoints.
@param rollup The rollup for the read query. This can be null.
@param interpolation The interpolation for the read query. This can be null.
@return A Cursor of MultiDataPoints. The cursor.iterator().next() may throw a {@link TempoDBException} if an error occurs while making a request.
@see Cursor
@see Filter
@see Interpolation
@see MultiDataPoint
@see Rollup
@since 1.1.0 | [
"Returns",
"a",
"cursor",
"of",
"multi",
"-",
"datapoints",
"specified",
"by",
"a",
"series",
"filter",
"."
] | train | https://github.com/tempodb/tempodb-java/blob/5733f204fe4c8dda48916ba1f67cf44f5a3f9c69/src/main/java/com/tempodb/Client.java#L934-L955 |
palatable/lambda | src/main/java/com/jnape/palatable/lambda/optics/lenses/MapLens.java | MapLens.valueAt | public static <K, V> Lens.Simple<Map<K, V>, Maybe<V>> valueAt(K k) {
return adapt(valueAt(HashMap::new, k));
} | java | public static <K, V> Lens.Simple<Map<K, V>, Maybe<V>> valueAt(K k) {
return adapt(valueAt(HashMap::new, k));
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"Lens",
".",
"Simple",
"<",
"Map",
"<",
"K",
",",
"V",
">",
",",
"Maybe",
"<",
"V",
">",
">",
"valueAt",
"(",
"K",
"k",
")",
"{",
"return",
"adapt",
"(",
"valueAt",
"(",
"HashMap",
"::",
"new",
","... | A lens that focuses on a value at a key in a map, as a {@link Maybe}.
@param <K> the key type
@param <V> the value type
@param k the key to focus on
@return a lens that focuses on the value at key, as a {@link Maybe} | [
"A",
"lens",
"that",
"focuses",
"on",
"a",
"value",
"at",
"a",
"key",
"in",
"a",
"map",
"as",
"a",
"{",
"@link",
"Maybe",
"}",
"."
] | train | https://github.com/palatable/lambda/blob/b643ba836c5916d1d8193822e5efb4e7b40c489a/src/main/java/com/jnape/palatable/lambda/optics/lenses/MapLens.java#L93-L95 |
mozilla/rhino | examples/File.java | File.write0 | private static void write0(Scriptable thisObj, Object[] args, boolean eol)
throws IOException
{
File thisFile = checkInstance(thisObj);
if (thisFile.reader != null) {
throw Context.reportRuntimeError("already writing file \""
+ thisFile.name
+ "\"");
}
if (thisFile.writer == null)
thisFile.writer = new BufferedWriter(
thisFile.file == null ? new OutputStreamWriter(System.out)
: new FileWriter(thisFile.file));
for (int i=0; i < args.length; i++) {
String s = Context.toString(args[i]);
thisFile.writer.write(s, 0, s.length());
}
if (eol)
thisFile.writer.newLine();
} | java | private static void write0(Scriptable thisObj, Object[] args, boolean eol)
throws IOException
{
File thisFile = checkInstance(thisObj);
if (thisFile.reader != null) {
throw Context.reportRuntimeError("already writing file \""
+ thisFile.name
+ "\"");
}
if (thisFile.writer == null)
thisFile.writer = new BufferedWriter(
thisFile.file == null ? new OutputStreamWriter(System.out)
: new FileWriter(thisFile.file));
for (int i=0; i < args.length; i++) {
String s = Context.toString(args[i]);
thisFile.writer.write(s, 0, s.length());
}
if (eol)
thisFile.writer.newLine();
} | [
"private",
"static",
"void",
"write0",
"(",
"Scriptable",
"thisObj",
",",
"Object",
"[",
"]",
"args",
",",
"boolean",
"eol",
")",
"throws",
"IOException",
"{",
"File",
"thisFile",
"=",
"checkInstance",
"(",
"thisObj",
")",
";",
"if",
"(",
"thisFile",
".",
... | Perform the guts of write and writeLine.
Since the two functions differ only in whether they write a
newline character, move the code into a common subroutine. | [
"Perform",
"the",
"guts",
"of",
"write",
"and",
"writeLine",
"."
] | train | https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/examples/File.java#L293-L312 |
enioka/jqm | jqm-all/jqm-engine/src/main/java/com/enioka/jqm/tools/Helpers.java | Helpers.createUserIfMissing | static void createUserIfMissing(DbConn cnx, String login, String password, String description, String... roles)
{
try
{
int userId = cnx.runSelectSingle("user_select_id_by_key", Integer.class, login);
cnx.runUpdate("user_update_enable_by_id", userId);
RUser.set_roles(cnx, userId, roles);
}
catch (NoResultException e)
{
String saltS = null;
String hash = null;
if (null != password && !"".equals(password))
{
ByteSource salt = new SecureRandomNumberGenerator().nextBytes();
hash = new Sha512Hash(password, salt, 100000).toHex();
saltS = salt.toHex();
}
RUser.create(cnx, login, hash, saltS, roles);
}
} | java | static void createUserIfMissing(DbConn cnx, String login, String password, String description, String... roles)
{
try
{
int userId = cnx.runSelectSingle("user_select_id_by_key", Integer.class, login);
cnx.runUpdate("user_update_enable_by_id", userId);
RUser.set_roles(cnx, userId, roles);
}
catch (NoResultException e)
{
String saltS = null;
String hash = null;
if (null != password && !"".equals(password))
{
ByteSource salt = new SecureRandomNumberGenerator().nextBytes();
hash = new Sha512Hash(password, salt, 100000).toHex();
saltS = salt.toHex();
}
RUser.create(cnx, login, hash, saltS, roles);
}
} | [
"static",
"void",
"createUserIfMissing",
"(",
"DbConn",
"cnx",
",",
"String",
"login",
",",
"String",
"password",
",",
"String",
"description",
",",
"String",
"...",
"roles",
")",
"{",
"try",
"{",
"int",
"userId",
"=",
"cnx",
".",
"runSelectSingle",
"(",
"... | Creates a new user if does not exist. If it exists, it is unlocked and roles are reset (password is untouched).
@param cnx
@param login
@param password
the raw password. it will be hashed.
@param description
@param roles | [
"Creates",
"a",
"new",
"user",
"if",
"does",
"not",
"exist",
".",
"If",
"it",
"exists",
"it",
"is",
"unlocked",
"and",
"roles",
"are",
"reset",
"(",
"password",
"is",
"untouched",
")",
"."
] | train | https://github.com/enioka/jqm/blob/391733b8e291404b97c714c3727a241c4a861f98/jqm-all/jqm-engine/src/main/java/com/enioka/jqm/tools/Helpers.java#L441-L462 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PositionFromPairLinear2.java | PositionFromPairLinear2.process | public boolean process( DMatrixRMaj R , List<Point3D_F64> worldPts , List<Point2D_F64> observed )
{
if( worldPts.size() != observed.size() )
throw new IllegalArgumentException("Number of worldPts and observed must be the same");
if( worldPts.size() < 2 )
throw new IllegalArgumentException("A minimum of two points are required");
int N = worldPts.size();
A.reshape(3*N,3); b.reshape(A.numRows, 1);
for( int i = 0; i < N; i++ ) {
Point3D_F64 X = worldPts.get(i);
Point2D_F64 o = observed.get(i);
int indexA = i*3*3;
int indexB = i*3;
A.data[indexA+1] = -1;
A.data[indexA+2] = o.y;
A.data[indexA+3] = 1;
A.data[indexA+5] = -o.x;
A.data[indexA+6] = -o.y;
A.data[indexA+7] = o.x;
GeometryMath_F64.mult(R,X,RX);
b.data[indexB++] = 1*RX.y - o.y*RX.z;
b.data[indexB++] = -1*RX.x + o.x*RX.z;
b.data[indexB ] = o.y*RX.x - o.x*RX.y;
}
if( !solver.setA(A) )
return false;
solver.solve(b,x);
T.x = x.data[0];
T.y = x.data[1];
T.z = x.data[2];
return true;
} | java | public boolean process( DMatrixRMaj R , List<Point3D_F64> worldPts , List<Point2D_F64> observed )
{
if( worldPts.size() != observed.size() )
throw new IllegalArgumentException("Number of worldPts and observed must be the same");
if( worldPts.size() < 2 )
throw new IllegalArgumentException("A minimum of two points are required");
int N = worldPts.size();
A.reshape(3*N,3); b.reshape(A.numRows, 1);
for( int i = 0; i < N; i++ ) {
Point3D_F64 X = worldPts.get(i);
Point2D_F64 o = observed.get(i);
int indexA = i*3*3;
int indexB = i*3;
A.data[indexA+1] = -1;
A.data[indexA+2] = o.y;
A.data[indexA+3] = 1;
A.data[indexA+5] = -o.x;
A.data[indexA+6] = -o.y;
A.data[indexA+7] = o.x;
GeometryMath_F64.mult(R,X,RX);
b.data[indexB++] = 1*RX.y - o.y*RX.z;
b.data[indexB++] = -1*RX.x + o.x*RX.z;
b.data[indexB ] = o.y*RX.x - o.x*RX.y;
}
if( !solver.setA(A) )
return false;
solver.solve(b,x);
T.x = x.data[0];
T.y = x.data[1];
T.z = x.data[2];
return true;
} | [
"public",
"boolean",
"process",
"(",
"DMatrixRMaj",
"R",
",",
"List",
"<",
"Point3D_F64",
">",
"worldPts",
",",
"List",
"<",
"Point2D_F64",
">",
"observed",
")",
"{",
"if",
"(",
"worldPts",
".",
"size",
"(",
")",
"!=",
"observed",
".",
"size",
"(",
")"... | Computes the translation given two or more feature observations and the known rotation
@param R Rotation matrix. World to view.
@param worldPts Location of features in world coordinates.
@param observed Observations of point in current view. Normalized coordinates.
@return true if it succeeded. | [
"Computes",
"the",
"translation",
"given",
"two",
"or",
"more",
"feature",
"observations",
"and",
"the",
"known",
"rotation"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/PositionFromPairLinear2.java#L78-L121 |
taskadapter/redmine-java-api | src/main/java/com/taskadapter/redmineapi/bean/PropertyStorageUtil.java | PropertyStorageUtil.updateCollections | public static void updateCollections(PropertyStorage storage, Transport transport) {
storage.getProperties().forEach(e -> {
if (Collection.class.isAssignableFrom(e.getKey().getType())) {
// found a collection in properties
((Collection) e.getValue()).forEach(i -> {
if (i instanceof FluentStyle) {
((FluentStyle) i).setTransport(transport);
}
});
}
});
} | java | public static void updateCollections(PropertyStorage storage, Transport transport) {
storage.getProperties().forEach(e -> {
if (Collection.class.isAssignableFrom(e.getKey().getType())) {
// found a collection in properties
((Collection) e.getValue()).forEach(i -> {
if (i instanceof FluentStyle) {
((FluentStyle) i).setTransport(transport);
}
});
}
});
} | [
"public",
"static",
"void",
"updateCollections",
"(",
"PropertyStorage",
"storage",
",",
"Transport",
"transport",
")",
"{",
"storage",
".",
"getProperties",
"(",
")",
".",
"forEach",
"(",
"e",
"->",
"{",
"if",
"(",
"Collection",
".",
"class",
".",
"isAssign... | go over all properties in the storage and set `transport` on FluentStyle instances inside collections, if any.
only process one level, without recursion - to avoid potential cycles and such. | [
"go",
"over",
"all",
"properties",
"in",
"the",
"storage",
"and",
"set",
"transport",
"on",
"FluentStyle",
"instances",
"inside",
"collections",
"if",
"any",
".",
"only",
"process",
"one",
"level",
"without",
"recursion",
"-",
"to",
"avoid",
"potential",
"cycl... | train | https://github.com/taskadapter/redmine-java-api/blob/0bb65f27ee806ec3bd4007e1641f3e996261a04e/src/main/java/com/taskadapter/redmineapi/bean/PropertyStorageUtil.java#L12-L25 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java | JBBPBitOutputStream.writeShort | public void writeShort(final int value, final JBBPByteOrder byteOrder) throws IOException {
if (byteOrder == JBBPByteOrder.BIG_ENDIAN) {
this.write(value >>> 8);
this.write(value);
} else {
this.write(value);
this.write(value >>> 8);
}
} | java | public void writeShort(final int value, final JBBPByteOrder byteOrder) throws IOException {
if (byteOrder == JBBPByteOrder.BIG_ENDIAN) {
this.write(value >>> 8);
this.write(value);
} else {
this.write(value);
this.write(value >>> 8);
}
} | [
"public",
"void",
"writeShort",
"(",
"final",
"int",
"value",
",",
"final",
"JBBPByteOrder",
"byteOrder",
")",
"throws",
"IOException",
"{",
"if",
"(",
"byteOrder",
"==",
"JBBPByteOrder",
".",
"BIG_ENDIAN",
")",
"{",
"this",
".",
"write",
"(",
"value",
">>>"... | Write a signed short value into the output stream.
@param value a value to be written. Only two bytes will be written.
@param byteOrder the byte order of the value bytes to be used for writing.
@throws IOException it will be thrown for transport errors
@see JBBPByteOrder#BIG_ENDIAN
@see JBBPByteOrder#LITTLE_ENDIAN | [
"Write",
"a",
"signed",
"short",
"value",
"into",
"the",
"output",
"stream",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java#L92-L100 |
lessthanoptimal/ejml | main/ejml-dsparse/src/org/ejml/sparse/csc/RandomMatrices_DSCC.java | RandomMatrices_DSCC.rectangle | public static DMatrixSparseCSC rectangle(int numRows , int numCols , int nz_total ,
double min , double max , Random rand ) {
nz_total = Math.min(numCols*numRows,nz_total);
int[] selected = UtilEjml.shuffled(numRows*numCols, nz_total, rand);
Arrays.sort(selected,0,nz_total);
DMatrixSparseCSC ret = new DMatrixSparseCSC(numRows,numCols,nz_total);
ret.indicesSorted = true;
// compute the number of elements in each column
int hist[] = new int[ numCols ];
for (int i = 0; i < nz_total; i++) {
hist[selected[i]/numRows]++;
}
// define col_idx
ret.histogramToStructure(hist);
for (int i = 0; i < nz_total; i++) {
int row = selected[i]%numRows;
ret.nz_rows[i] = row;
ret.nz_values[i] = rand.nextDouble()*(max-min)+min;
}
return ret;
} | java | public static DMatrixSparseCSC rectangle(int numRows , int numCols , int nz_total ,
double min , double max , Random rand ) {
nz_total = Math.min(numCols*numRows,nz_total);
int[] selected = UtilEjml.shuffled(numRows*numCols, nz_total, rand);
Arrays.sort(selected,0,nz_total);
DMatrixSparseCSC ret = new DMatrixSparseCSC(numRows,numCols,nz_total);
ret.indicesSorted = true;
// compute the number of elements in each column
int hist[] = new int[ numCols ];
for (int i = 0; i < nz_total; i++) {
hist[selected[i]/numRows]++;
}
// define col_idx
ret.histogramToStructure(hist);
for (int i = 0; i < nz_total; i++) {
int row = selected[i]%numRows;
ret.nz_rows[i] = row;
ret.nz_values[i] = rand.nextDouble()*(max-min)+min;
}
return ret;
} | [
"public",
"static",
"DMatrixSparseCSC",
"rectangle",
"(",
"int",
"numRows",
",",
"int",
"numCols",
",",
"int",
"nz_total",
",",
"double",
"min",
",",
"double",
"max",
",",
"Random",
"rand",
")",
"{",
"nz_total",
"=",
"Math",
".",
"min",
"(",
"numCols",
"... | Randomly generates matrix with the specified number of non-zero elements filled with values from min to max.
@param numRows Number of rows
@param numCols Number of columns
@param nz_total Total number of non-zero elements in the matrix
@param min Minimum element value, inclusive
@param max Maximum element value, inclusive
@param rand Random number generator
@return Randomly generated matrix | [
"Randomly",
"generates",
"matrix",
"with",
"the",
"specified",
"number",
"of",
"non",
"-",
"zero",
"elements",
"filled",
"with",
"values",
"from",
"min",
"to",
"max",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/RandomMatrices_DSCC.java#L46-L73 |
aws/aws-sdk-java | aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/UpdateProvisioningArtifactResult.java | UpdateProvisioningArtifactResult.withInfo | public UpdateProvisioningArtifactResult withInfo(java.util.Map<String, String> info) {
setInfo(info);
return this;
} | java | public UpdateProvisioningArtifactResult withInfo(java.util.Map<String, String> info) {
setInfo(info);
return this;
} | [
"public",
"UpdateProvisioningArtifactResult",
"withInfo",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"info",
")",
"{",
"setInfo",
"(",
"info",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The URL of the CloudFormation template in Amazon S3.
</p>
@param info
The URL of the CloudFormation template in Amazon S3.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"URL",
"of",
"the",
"CloudFormation",
"template",
"in",
"Amazon",
"S3",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/UpdateProvisioningArtifactResult.java#L120-L123 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/AccountsImpl.java | AccountsImpl.listNodeAgentSkusAsync | public ServiceFuture<List<NodeAgentSku>> listNodeAgentSkusAsync(final AccountListNodeAgentSkusOptions accountListNodeAgentSkusOptions, final ListOperationCallback<NodeAgentSku> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listNodeAgentSkusSinglePageAsync(accountListNodeAgentSkusOptions),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<NodeAgentSku>, AccountListNodeAgentSkusHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<NodeAgentSku>, AccountListNodeAgentSkusHeaders>> call(String nextPageLink) {
AccountListNodeAgentSkusNextOptions accountListNodeAgentSkusNextOptions = null;
if (accountListNodeAgentSkusOptions != null) {
accountListNodeAgentSkusNextOptions = new AccountListNodeAgentSkusNextOptions();
accountListNodeAgentSkusNextOptions.withClientRequestId(accountListNodeAgentSkusOptions.clientRequestId());
accountListNodeAgentSkusNextOptions.withReturnClientRequestId(accountListNodeAgentSkusOptions.returnClientRequestId());
accountListNodeAgentSkusNextOptions.withOcpDate(accountListNodeAgentSkusOptions.ocpDate());
}
return listNodeAgentSkusNextSinglePageAsync(nextPageLink, accountListNodeAgentSkusNextOptions);
}
},
serviceCallback);
} | java | public ServiceFuture<List<NodeAgentSku>> listNodeAgentSkusAsync(final AccountListNodeAgentSkusOptions accountListNodeAgentSkusOptions, final ListOperationCallback<NodeAgentSku> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listNodeAgentSkusSinglePageAsync(accountListNodeAgentSkusOptions),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<NodeAgentSku>, AccountListNodeAgentSkusHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<NodeAgentSku>, AccountListNodeAgentSkusHeaders>> call(String nextPageLink) {
AccountListNodeAgentSkusNextOptions accountListNodeAgentSkusNextOptions = null;
if (accountListNodeAgentSkusOptions != null) {
accountListNodeAgentSkusNextOptions = new AccountListNodeAgentSkusNextOptions();
accountListNodeAgentSkusNextOptions.withClientRequestId(accountListNodeAgentSkusOptions.clientRequestId());
accountListNodeAgentSkusNextOptions.withReturnClientRequestId(accountListNodeAgentSkusOptions.returnClientRequestId());
accountListNodeAgentSkusNextOptions.withOcpDate(accountListNodeAgentSkusOptions.ocpDate());
}
return listNodeAgentSkusNextSinglePageAsync(nextPageLink, accountListNodeAgentSkusNextOptions);
}
},
serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"List",
"<",
"NodeAgentSku",
">",
">",
"listNodeAgentSkusAsync",
"(",
"final",
"AccountListNodeAgentSkusOptions",
"accountListNodeAgentSkusOptions",
",",
"final",
"ListOperationCallback",
"<",
"NodeAgentSku",
">",
"serviceCallback",
")",
"{",... | Lists all node agent SKUs supported by the Azure Batch service.
@param accountListNodeAgentSkusOptions Additional parameters for the operation
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Lists",
"all",
"node",
"agent",
"SKUs",
"supported",
"by",
"the",
"Azure",
"Batch",
"service",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/AccountsImpl.java#L233-L250 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/cookies/CookieCacheData.java | CookieCacheData.getAllCookies | public int getAllCookies(String name, List<HttpCookie> list) {
int added = 0;
if (0 < this.parsedList.size() && null != name) {
for (HttpCookie cookie : this.parsedList) {
if (cookie.getName().equals(name)) {
list.add(cookie.clone());
added++;
}
}
}
return added;
} | java | public int getAllCookies(String name, List<HttpCookie> list) {
int added = 0;
if (0 < this.parsedList.size() && null != name) {
for (HttpCookie cookie : this.parsedList) {
if (cookie.getName().equals(name)) {
list.add(cookie.clone());
added++;
}
}
}
return added;
} | [
"public",
"int",
"getAllCookies",
"(",
"String",
"name",
",",
"List",
"<",
"HttpCookie",
">",
"list",
")",
"{",
"int",
"added",
"=",
"0",
";",
"if",
"(",
"0",
"<",
"this",
".",
"parsedList",
".",
"size",
"(",
")",
"&&",
"null",
"!=",
"name",
")",
... | Find all instances of cookies in the cache with the given name and add
clones of those objects to the input list.
@param name
@param list
@return int - number of cookies added to the list | [
"Find",
"all",
"instances",
"of",
"cookies",
"in",
"the",
"cache",
"with",
"the",
"given",
"name",
"and",
"add",
"clones",
"of",
"those",
"objects",
"to",
"the",
"input",
"list",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/cookies/CookieCacheData.java#L126-L137 |
openengsb/openengsb | components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/operation/SubStringOperation.java | SubStringOperation.getSubStringParameter | private Integer getSubStringParameter(Map<String, String> parameters, String parameterName, Integer defaultValue)
throws TransformationOperationException {
String parameter = parameters.get(parameterName);
if (parameter == null) {
getLogger().debug("The {} parameter is not set, so the default value {} is taken.", parameterName,
defaultValue);
return defaultValue;
}
try {
return Integer.parseInt(parameter);
} catch (NumberFormatException e) {
throw new TransformationOperationException("The " + parameterName + " parameter is not a number");
}
} | java | private Integer getSubStringParameter(Map<String, String> parameters, String parameterName, Integer defaultValue)
throws TransformationOperationException {
String parameter = parameters.get(parameterName);
if (parameter == null) {
getLogger().debug("The {} parameter is not set, so the default value {} is taken.", parameterName,
defaultValue);
return defaultValue;
}
try {
return Integer.parseInt(parameter);
} catch (NumberFormatException e) {
throw new TransformationOperationException("The " + parameterName + " parameter is not a number");
}
} | [
"private",
"Integer",
"getSubStringParameter",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
",",
"String",
"parameterName",
",",
"Integer",
"defaultValue",
")",
"throws",
"TransformationOperationException",
"{",
"String",
"parameter",
"=",
"parameters"... | Returns the substring parameter with the given parameter or the given default value if the parameter name is not
set. | [
"Returns",
"the",
"substring",
"parameter",
"with",
"the",
"given",
"parameter",
"or",
"the",
"given",
"default",
"value",
"if",
"the",
"parameter",
"name",
"is",
"not",
"set",
"."
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/operation/SubStringOperation.java#L113-L126 |
jamesagnew/hapi-fhir | hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/utils/ProfileUtilities.java | ProfileUtilities.updateURLs | private ElementDefinition updateURLs(String url, ElementDefinition element) {
if (element != null) {
ElementDefinition defn = element;
if (defn.hasBinding() && defn.getBinding().getValueSet() instanceof Reference && ((Reference)defn.getBinding().getValueSet()).getReference().startsWith("#"))
((Reference)defn.getBinding().getValueSet()).setReference(url+((Reference)defn.getBinding().getValueSet()).getReference());
for (TypeRefComponent t : defn.getType()) {
for (UriType tp : t.getProfile()) {
if (tp.getValue().startsWith("#"))
tp.setValue(url+t.getProfile());
}
}
}
return element;
} | java | private ElementDefinition updateURLs(String url, ElementDefinition element) {
if (element != null) {
ElementDefinition defn = element;
if (defn.hasBinding() && defn.getBinding().getValueSet() instanceof Reference && ((Reference)defn.getBinding().getValueSet()).getReference().startsWith("#"))
((Reference)defn.getBinding().getValueSet()).setReference(url+((Reference)defn.getBinding().getValueSet()).getReference());
for (TypeRefComponent t : defn.getType()) {
for (UriType tp : t.getProfile()) {
if (tp.getValue().startsWith("#"))
tp.setValue(url+t.getProfile());
}
}
}
return element;
} | [
"private",
"ElementDefinition",
"updateURLs",
"(",
"String",
"url",
",",
"ElementDefinition",
"element",
")",
"{",
"if",
"(",
"element",
"!=",
"null",
")",
"{",
"ElementDefinition",
"defn",
"=",
"element",
";",
"if",
"(",
"defn",
".",
"hasBinding",
"(",
")",... | Finds internal references in an Element's Binding and StructureDefinition references (in TypeRef) and bases them on the given url
@param url - the base url to use to turn internal references into absolute references
@param element - the Element to update
@return - the updated Element | [
"Finds",
"internal",
"references",
"in",
"an",
"Element",
"s",
"Binding",
"and",
"StructureDefinition",
"references",
"(",
"in",
"TypeRef",
")",
"and",
"bases",
"them",
"on",
"the",
"given",
"url"
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/utils/ProfileUtilities.java#L1474-L1487 |
jglobus/JGlobus | gram/src/main/java/org/globus/rsl/VarRef.java | VarRef.toRSL | public void toRSL(StringBuffer buf, boolean explicitConcat) {
buf.append("$(");
buf.append( value );
if (defValue != null) {
buf.append(" ");
defValue.toRSL(buf, explicitConcat);
}
buf.append(")");
if (concatValue == null) return;
if (explicitConcat) buf.append(" # ");
concatValue.toRSL(buf, explicitConcat);
} | java | public void toRSL(StringBuffer buf, boolean explicitConcat) {
buf.append("$(");
buf.append( value );
if (defValue != null) {
buf.append(" ");
defValue.toRSL(buf, explicitConcat);
}
buf.append(")");
if (concatValue == null) return;
if (explicitConcat) buf.append(" # ");
concatValue.toRSL(buf, explicitConcat);
} | [
"public",
"void",
"toRSL",
"(",
"StringBuffer",
"buf",
",",
"boolean",
"explicitConcat",
")",
"{",
"buf",
".",
"append",
"(",
"\"$(\"",
")",
";",
"buf",
".",
"append",
"(",
"value",
")",
";",
"if",
"(",
"defValue",
"!=",
"null",
")",
"{",
"buf",
".",... | Produces a RSL representation of this variable reference.
@param buf buffer to add the RSL representation to.
@param explicitConcat if true explicit concatination will
be used in RSL strings. | [
"Produces",
"a",
"RSL",
"representation",
"of",
"this",
"variable",
"reference",
"."
] | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/gram/src/main/java/org/globus/rsl/VarRef.java#L123-L139 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyStore.java | KeyStore.getInstance | public static KeyStore getInstance(String type, String provider)
throws KeyStoreException, NoSuchProviderException
{
if (provider == null || provider.length() == 0)
throw new IllegalArgumentException("missing provider");
try {
Object[] objs = Security.getImpl(type, "KeyStore", provider);
return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
} catch (NoSuchAlgorithmException nsae) {
throw new KeyStoreException(type + " not found", nsae);
}
} | java | public static KeyStore getInstance(String type, String provider)
throws KeyStoreException, NoSuchProviderException
{
if (provider == null || provider.length() == 0)
throw new IllegalArgumentException("missing provider");
try {
Object[] objs = Security.getImpl(type, "KeyStore", provider);
return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
} catch (NoSuchAlgorithmException nsae) {
throw new KeyStoreException(type + " not found", nsae);
}
} | [
"public",
"static",
"KeyStore",
"getInstance",
"(",
"String",
"type",
",",
"String",
"provider",
")",
"throws",
"KeyStoreException",
",",
"NoSuchProviderException",
"{",
"if",
"(",
"provider",
"==",
"null",
"||",
"provider",
".",
"length",
"(",
")",
"==",
"0",... | Returns a keystore object of the specified type.
<p> A new KeyStore object encapsulating the
KeyStoreSpi 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 type the type of keystore.
See the KeyStore section in the <a href=
"{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/StandardNames.html#KeyStore">
Java Cryptography Architecture Standard Algorithm Name Documentation</a>
for information about standard keystore types.
@param provider the name of the provider.
@return a keystore object of the specified type.
@exception KeyStoreException if a KeyStoreSpi
implementation for the specified type 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",
"keystore",
"object",
"of",
"the",
"specified",
"type",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyStore.java#L697-L708 |
michel-kraemer/citeproc-java | citeproc-java/src/main/java/de/undercouch/citeproc/BibliographyFileReader.java | BibliographyFileReader.determineFileFormat | public FileFormat determineFileFormat(File bibfile)
throws FileNotFoundException, IOException {
if (!bibfile.exists()) {
throw new FileNotFoundException("Bibliography file `" +
bibfile.getName() + "' does not exist");
}
try (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(bibfile))) {
return determineFileFormat(bis, bibfile.getName());
}
} | java | public FileFormat determineFileFormat(File bibfile)
throws FileNotFoundException, IOException {
if (!bibfile.exists()) {
throw new FileNotFoundException("Bibliography file `" +
bibfile.getName() + "' does not exist");
}
try (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(bibfile))) {
return determineFileFormat(bis, bibfile.getName());
}
} | [
"public",
"FileFormat",
"determineFileFormat",
"(",
"File",
"bibfile",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
"{",
"if",
"(",
"!",
"bibfile",
".",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"FileNotFoundException",
"(",
"\"Bibliography file... | Reads the first 100 KB of the given bibliography file and tries
to determine the file format
@param bibfile the input file
@return the file format (or {@link FileFormat#UNKNOWN} if the format
could not be determined)
@throws FileNotFoundException if the input file was not found
@throws IOException if the input file could not be read | [
"Reads",
"the",
"first",
"100",
"KB",
"of",
"the",
"given",
"bibliography",
"file",
"and",
"tries",
"to",
"determine",
"the",
"file",
"format"
] | train | https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/BibliographyFileReader.java#L238-L248 |
alkacon/opencms-core | src/org/opencms/search/extractors/A_CmsTextExtractor.java | A_CmsTextExtractor.extractText | @SuppressWarnings("deprecation")
protected CmsExtractionResult extractText(InputStream in, Parser parser) throws Exception {
LinkedHashMap<String, String> contentItems = new LinkedHashMap<String, String>();
StringWriter writer = new StringWriter();
BodyContentHandler handler = new BodyContentHandler(writer);
Metadata meta = new Metadata();
ParseContext context = new ParseContext();
parser.parse(in, handler, meta, context);
in.close();
String result = writer.toString();
// add the main document text
StringBuffer content = new StringBuffer(result);
if (CmsStringUtil.isNotEmpty(result)) {
contentItems.put(I_CmsExtractionResult.ITEM_RAW, result);
}
// appends all known document meta data as content items
combineContentItem(meta.get(DublinCore.TITLE), I_CmsExtractionResult.ITEM_TITLE, content, contentItems);
combineContentItem(meta.get(MSOffice.KEYWORDS), I_CmsExtractionResult.ITEM_KEYWORDS, content, contentItems);
String subject = meta.get(I_CmsExtractionResult.ITEM_SUBJECT);
if (StringUtils.isBlank(subject)) {
subject = meta.get(DublinCore.SUBJECT);
}
combineContentItem(subject, I_CmsExtractionResult.ITEM_SUBJECT, content, contentItems);
combineContentItem(meta.get(MSOffice.AUTHOR), I_CmsExtractionResult.ITEM_AUTHOR, content, contentItems);
String creator = meta.get("xmp:CreatorTool");
if (StringUtils.isBlank(creator)) {
creator = meta.get(DublinCore.CREATOR);
}
if (StringUtils.isBlank(creator)) {
creator = meta.get(I_CmsExtractionResult.ITEM_CREATOR);
}
combineContentItem(creator, I_CmsExtractionResult.ITEM_CREATOR, content, contentItems);
//
combineContentItem(meta.get(MSOffice.CATEGORY), I_CmsExtractionResult.ITEM_CATEGORY, content, contentItems);
//
combineContentItem(meta.get(MSOffice.COMMENTS), I_CmsExtractionResult.ITEM_COMMENTS, content, contentItems);
String company = meta.get(OfficeOpenXMLExtended.COMPANY);
if (StringUtils.isBlank(company)) {
company = meta.get(MSOffice.COMPANY);
}
combineContentItem(company, I_CmsExtractionResult.ITEM_COMPANY, content, contentItems);
//
combineContentItem(meta.get(MSOffice.MANAGER), I_CmsExtractionResult.ITEM_MANAGER, content, contentItems);
// this constant seems to be missing from TIKA
combineContentItem(
meta.get(I_CmsExtractionResult.ITEM_PRODUCER),
I_CmsExtractionResult.ITEM_PRODUCER,
content,
contentItems);
// return the final result
return new CmsExtractionResult(content.toString(), contentItems);
} | java | @SuppressWarnings("deprecation")
protected CmsExtractionResult extractText(InputStream in, Parser parser) throws Exception {
LinkedHashMap<String, String> contentItems = new LinkedHashMap<String, String>();
StringWriter writer = new StringWriter();
BodyContentHandler handler = new BodyContentHandler(writer);
Metadata meta = new Metadata();
ParseContext context = new ParseContext();
parser.parse(in, handler, meta, context);
in.close();
String result = writer.toString();
// add the main document text
StringBuffer content = new StringBuffer(result);
if (CmsStringUtil.isNotEmpty(result)) {
contentItems.put(I_CmsExtractionResult.ITEM_RAW, result);
}
// appends all known document meta data as content items
combineContentItem(meta.get(DublinCore.TITLE), I_CmsExtractionResult.ITEM_TITLE, content, contentItems);
combineContentItem(meta.get(MSOffice.KEYWORDS), I_CmsExtractionResult.ITEM_KEYWORDS, content, contentItems);
String subject = meta.get(I_CmsExtractionResult.ITEM_SUBJECT);
if (StringUtils.isBlank(subject)) {
subject = meta.get(DublinCore.SUBJECT);
}
combineContentItem(subject, I_CmsExtractionResult.ITEM_SUBJECT, content, contentItems);
combineContentItem(meta.get(MSOffice.AUTHOR), I_CmsExtractionResult.ITEM_AUTHOR, content, contentItems);
String creator = meta.get("xmp:CreatorTool");
if (StringUtils.isBlank(creator)) {
creator = meta.get(DublinCore.CREATOR);
}
if (StringUtils.isBlank(creator)) {
creator = meta.get(I_CmsExtractionResult.ITEM_CREATOR);
}
combineContentItem(creator, I_CmsExtractionResult.ITEM_CREATOR, content, contentItems);
//
combineContentItem(meta.get(MSOffice.CATEGORY), I_CmsExtractionResult.ITEM_CATEGORY, content, contentItems);
//
combineContentItem(meta.get(MSOffice.COMMENTS), I_CmsExtractionResult.ITEM_COMMENTS, content, contentItems);
String company = meta.get(OfficeOpenXMLExtended.COMPANY);
if (StringUtils.isBlank(company)) {
company = meta.get(MSOffice.COMPANY);
}
combineContentItem(company, I_CmsExtractionResult.ITEM_COMPANY, content, contentItems);
//
combineContentItem(meta.get(MSOffice.MANAGER), I_CmsExtractionResult.ITEM_MANAGER, content, contentItems);
// this constant seems to be missing from TIKA
combineContentItem(
meta.get(I_CmsExtractionResult.ITEM_PRODUCER),
I_CmsExtractionResult.ITEM_PRODUCER,
content,
contentItems);
// return the final result
return new CmsExtractionResult(content.toString(), contentItems);
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"protected",
"CmsExtractionResult",
"extractText",
"(",
"InputStream",
"in",
",",
"Parser",
"parser",
")",
"throws",
"Exception",
"{",
"LinkedHashMap",
"<",
"String",
",",
"String",
">",
"contentItems",
"=",
"n... | Parses the given input stream with the provided parser and returns the result as a map of content items.<p>
@param in the input stream for the content to parse
@param parser the parser to use
@return the result of the parsing as a map of content items
@throws Exception in case something goes wrong | [
"Parses",
"the",
"given",
"input",
"stream",
"with",
"the",
"provided",
"parser",
"and",
"returns",
"the",
"result",
"as",
"a",
"map",
"of",
"content",
"items",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/extractors/A_CmsTextExtractor.java#L126-L184 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/util/Utils.java | Utils.createNameForHiddenGuardEvaluatorMethod | public static String createNameForHiddenGuardEvaluatorMethod(String eventId, int handlerIndex) {
return PREFIX_GUARD + fixHiddenMember(eventId)
+ HIDDEN_MEMBER_CHARACTER + handlerIndex;
} | java | public static String createNameForHiddenGuardEvaluatorMethod(String eventId, int handlerIndex) {
return PREFIX_GUARD + fixHiddenMember(eventId)
+ HIDDEN_MEMBER_CHARACTER + handlerIndex;
} | [
"public",
"static",
"String",
"createNameForHiddenGuardEvaluatorMethod",
"(",
"String",
"eventId",
",",
"int",
"handlerIndex",
")",
"{",
"return",
"PREFIX_GUARD",
"+",
"fixHiddenMember",
"(",
"eventId",
")",
"+",
"HIDDEN_MEMBER_CHARACTER",
"+",
"handlerIndex",
";",
"}... | Create the name of the hidden method that is containing the event guard evaluation.
@param eventId the id of the event.
@param handlerIndex the index of the handler in the container type.
@return the method name. | [
"Create",
"the",
"name",
"of",
"the",
"hidden",
"method",
"that",
"is",
"containing",
"the",
"event",
"guard",
"evaluation",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/util/Utils.java#L463-L466 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/util/Position.java | Position.makeLineMap | public static LineMap makeLineMap(char[] src, int max, boolean expandTabs) {
LineMapImpl lineMap = expandTabs ?
new LineTabMapImpl(max) : new LineMapImpl();
lineMap.build(src, max);
return lineMap;
} | java | public static LineMap makeLineMap(char[] src, int max, boolean expandTabs) {
LineMapImpl lineMap = expandTabs ?
new LineTabMapImpl(max) : new LineMapImpl();
lineMap.build(src, max);
return lineMap;
} | [
"public",
"static",
"LineMap",
"makeLineMap",
"(",
"char",
"[",
"]",
"src",
",",
"int",
"max",
",",
"boolean",
"expandTabs",
")",
"{",
"LineMapImpl",
"lineMap",
"=",
"expandTabs",
"?",
"new",
"LineTabMapImpl",
"(",
"max",
")",
":",
"new",
"LineMapImpl",
"(... | A two-way map between line/column numbers and positions,
derived from a scan done at creation time. Tab expansion is
optionally supported via a character map. Text content
is not retained.
<p>
Notes: The first character position FIRSTPOS is at
(FIRSTLINE,FIRSTCOLUMN). No account is taken of Unicode escapes.
@param src Source characters
@param max Number of characters to read
@param expandTabs If true, expand tabs when calculating columns | [
"A",
"two",
"-",
"way",
"map",
"between",
"line",
"/",
"column",
"numbers",
"and",
"positions",
"derived",
"from",
"a",
"scan",
"done",
"at",
"creation",
"time",
".",
"Tab",
"expansion",
"is",
"optionally",
"supported",
"via",
"a",
"character",
"map",
".",... | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/util/Position.java#L74-L79 |
whizzosoftware/WZWave | src/main/java/com/whizzosoftware/wzwave/commandclass/MeterCommandClass.java | MeterCommandClass.createGet | public DataFrame createGet(byte nodeId, Scale s) {
switch (getVersion()) {
case 1:
return createSendDataFrame("METER_GET", nodeId, new byte[]{MeterCommandClass.ID, METER_GET}, true);
default: {
byte scale = scaleToByte(s);
byte b = (byte) ((scale << 3) & 0x18);
return createSendDataFrame("METER_GET", nodeId, new byte[]{MeterCommandClass.ID, METER_GET, b}, true);
}
}
} | java | public DataFrame createGet(byte nodeId, Scale s) {
switch (getVersion()) {
case 1:
return createSendDataFrame("METER_GET", nodeId, new byte[]{MeterCommandClass.ID, METER_GET}, true);
default: {
byte scale = scaleToByte(s);
byte b = (byte) ((scale << 3) & 0x18);
return createSendDataFrame("METER_GET", nodeId, new byte[]{MeterCommandClass.ID, METER_GET, b}, true);
}
}
} | [
"public",
"DataFrame",
"createGet",
"(",
"byte",
"nodeId",
",",
"Scale",
"s",
")",
"{",
"switch",
"(",
"getVersion",
"(",
")",
")",
"{",
"case",
"1",
":",
"return",
"createSendDataFrame",
"(",
"\"METER_GET\"",
",",
"nodeId",
",",
"new",
"byte",
"[",
"]",... | Create a Get data frame.
@param nodeId the target node ID
@param s the scale (null for version 1)
@return a DataFrame instance | [
"Create",
"a",
"Get",
"data",
"frame",
"."
] | train | https://github.com/whizzosoftware/WZWave/blob/b9dfec6b55515226edf9d772a89933b336397501/src/main/java/com/whizzosoftware/wzwave/commandclass/MeterCommandClass.java#L180-L191 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/XlsMapper.java | XlsMapper.save | public void save(final InputStream templateXlsIn, final OutputStream xlsOut, final Object beanObj) throws XlsMapperException, IOException {
saver.save(templateXlsIn, xlsOut, beanObj);
} | java | public void save(final InputStream templateXlsIn, final OutputStream xlsOut, final Object beanObj) throws XlsMapperException, IOException {
saver.save(templateXlsIn, xlsOut, beanObj);
} | [
"public",
"void",
"save",
"(",
"final",
"InputStream",
"templateXlsIn",
",",
"final",
"OutputStream",
"xlsOut",
",",
"final",
"Object",
"beanObj",
")",
"throws",
"XlsMapperException",
",",
"IOException",
"{",
"saver",
".",
"save",
"(",
"templateXlsIn",
",",
"xls... | JavaのオブジェクトをExeclファイルに出力する。
<p>出力するファイルは、引数で指定した雛形となるテンプレート用のExcelファイルをもとに出力する。</p>
@param templateXlsIn 雛形となるExcelファイルの入力
@param xlsOut 出力先のストリーム
@param beanObj 書き込むBeanオブジェクト
@throws IllegalArgumentException {@literal templateXlsIn == null or xlsOut == null or beanObj == null}
@throws XlsMapperException マッピングに失敗した場合
@throws IOException テンプレートのファイルの読み込みやファイルの出力に失敗した場合 | [
"JavaのオブジェクトをExeclファイルに出力する。",
"<p",
">",
"出力するファイルは、引数で指定した雛形となるテンプレート用のExcelファイルをもとに出力する。<",
"/",
"p",
">"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/XlsMapper.java#L332-L334 |
finmath/finmath-lib | src/main/java6/net/finmath/montecarlo/interestrate/products/Caplet.java | Caplet.getValue | @Override
public RandomVariableInterface getValue(double evaluationTime, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {
// This is on the LIBOR discretization
double paymentDate = maturity+periodLength;
// Get random variables
RandomVariableInterface libor = model.getLIBOR(maturity, maturity, maturity+periodLength);
RandomVariableInterface numeraire = model.getNumeraire(paymentDate);
RandomVariableInterface monteCarloProbabilities = model.getMonteCarloWeights(paymentDate);
/*
* Calculate the payoff, which is
* max(L-K,0) * periodLength for caplet or
* -min(L-K,0) * periodLength for floorlet.
*/
RandomVariableInterface values = libor;
if(!isFloorlet) {
values = values.sub(strike).floor(0.0).mult(daycountFraction);
} else {
values = values.sub(strike).cap(0.0).mult(-1.0 * daycountFraction);
}
values = values.div(numeraire).mult(monteCarloProbabilities);
RandomVariableInterface numeraireAtValuationTime = model.getNumeraire(evaluationTime);
RandomVariableInterface monteCarloProbabilitiesAtValuationTime = model.getMonteCarloWeights(evaluationTime);
values = values.mult(numeraireAtValuationTime).div(monteCarloProbabilitiesAtValuationTime);
if(valueUnit == ValueUnit.VALUE) {
return values;
}
else if(valueUnit == ValueUnit.LOGNORMALVOLATILITY || valueUnit == ValueUnit.VOLATILITY) {
/*
* This calculation makes sense only if the value is an unconditional one.
*/
double forward = libor.div(numeraire).mult(monteCarloProbabilities).mult(numeraireAtValuationTime).div(monteCarloProbabilitiesAtValuationTime).getAverage();
double optionMaturity = maturity-evaluationTime;
double optionStrike = strike;
double payoffUnit = daycountFraction;
return model.getRandomVariableForConstant(AnalyticFormulas.blackScholesOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, values.getAverage()));
}
else if(valueUnit == ValueUnit.NORMALVOLATILITY) {
/*
* This calculation makes sense only if the value is an unconditional one.
*/
double forward = libor.div(numeraire).mult(monteCarloProbabilities).mult(numeraireAtValuationTime).div(monteCarloProbabilitiesAtValuationTime).getAverage();
double optionMaturity = maturity-evaluationTime;
double optionStrike = strike;
double payoffUnit = daycountFraction;
return model.getRandomVariableForConstant(AnalyticFormulas.bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, values.getAverage()));
}
else {
throw new IllegalArgumentException("Value unit " + valueUnit + " unsupported.");
}
} | java | @Override
public RandomVariableInterface getValue(double evaluationTime, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {
// This is on the LIBOR discretization
double paymentDate = maturity+periodLength;
// Get random variables
RandomVariableInterface libor = model.getLIBOR(maturity, maturity, maturity+periodLength);
RandomVariableInterface numeraire = model.getNumeraire(paymentDate);
RandomVariableInterface monteCarloProbabilities = model.getMonteCarloWeights(paymentDate);
/*
* Calculate the payoff, which is
* max(L-K,0) * periodLength for caplet or
* -min(L-K,0) * periodLength for floorlet.
*/
RandomVariableInterface values = libor;
if(!isFloorlet) {
values = values.sub(strike).floor(0.0).mult(daycountFraction);
} else {
values = values.sub(strike).cap(0.0).mult(-1.0 * daycountFraction);
}
values = values.div(numeraire).mult(monteCarloProbabilities);
RandomVariableInterface numeraireAtValuationTime = model.getNumeraire(evaluationTime);
RandomVariableInterface monteCarloProbabilitiesAtValuationTime = model.getMonteCarloWeights(evaluationTime);
values = values.mult(numeraireAtValuationTime).div(monteCarloProbabilitiesAtValuationTime);
if(valueUnit == ValueUnit.VALUE) {
return values;
}
else if(valueUnit == ValueUnit.LOGNORMALVOLATILITY || valueUnit == ValueUnit.VOLATILITY) {
/*
* This calculation makes sense only if the value is an unconditional one.
*/
double forward = libor.div(numeraire).mult(monteCarloProbabilities).mult(numeraireAtValuationTime).div(monteCarloProbabilitiesAtValuationTime).getAverage();
double optionMaturity = maturity-evaluationTime;
double optionStrike = strike;
double payoffUnit = daycountFraction;
return model.getRandomVariableForConstant(AnalyticFormulas.blackScholesOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, values.getAverage()));
}
else if(valueUnit == ValueUnit.NORMALVOLATILITY) {
/*
* This calculation makes sense only if the value is an unconditional one.
*/
double forward = libor.div(numeraire).mult(monteCarloProbabilities).mult(numeraireAtValuationTime).div(monteCarloProbabilitiesAtValuationTime).getAverage();
double optionMaturity = maturity-evaluationTime;
double optionStrike = strike;
double payoffUnit = daycountFraction;
return model.getRandomVariableForConstant(AnalyticFormulas.bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, values.getAverage()));
}
else {
throw new IllegalArgumentException("Value unit " + valueUnit + " unsupported.");
}
} | [
"@",
"Override",
"public",
"RandomVariableInterface",
"getValue",
"(",
"double",
"evaluationTime",
",",
"LIBORModelMonteCarloSimulationInterface",
"model",
")",
"throws",
"CalculationException",
"{",
"// This is on the LIBOR discretization",
"double",
"paymentDate",
"=",
"matur... | This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime.
Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time.
Cashflows prior evaluationTime are not considered.
@param evaluationTime The time on which this products value should be observed.
@param model The model used to price the product.
@return The random variable representing the value of the product discounted to evaluation time
@throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. | [
"This",
"method",
"returns",
"the",
"value",
"random",
"variable",
"of",
"the",
"product",
"within",
"the",
"specified",
"model",
"evaluated",
"at",
"a",
"given",
"evalutationTime",
".",
"Note",
":",
"For",
"a",
"lattice",
"this",
"is",
"often",
"the",
"valu... | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/interestrate/products/Caplet.java#L114-L168 |
igniterealtime/Smack | smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebugger.java | EnhancedDebugger.addSentPacketToTable | private void addSentPacketToTable(final SimpleDateFormat dateFormatter, final TopLevelStreamElement packet) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String messageType;
Jid to;
String stanzaId;
if (packet instanceof Stanza) {
Stanza stanza = (Stanza) packet;
to = stanza.getTo();
stanzaId = stanza.getStanzaId();
} else {
to = null;
stanzaId = "(Nonza)";
}
String type = "";
Icon packetTypeIcon;
sentPackets++;
if (packet instanceof IQ) {
packetTypeIcon = iqPacketIcon;
messageType = "IQ Sent (class=" + packet.getClass().getName() + ")";
type = ((IQ) packet).getType().toString();
sentIQPackets++;
}
else if (packet instanceof Message) {
packetTypeIcon = messagePacketIcon;
messageType = "Message Sent";
type = ((Message) packet).getType().toString();
sentMessagePackets++;
}
else if (packet instanceof Presence) {
packetTypeIcon = presencePacketIcon;
messageType = "Presence Sent";
type = ((Presence) packet).getType().toString();
sentPresencePackets++;
}
else {
packetTypeIcon = unknownPacketTypeIcon;
messageType = packet.getClass().getName() + " Sent";
sentOtherPackets++;
}
// Check if we need to remove old rows from the table to keep memory consumption low
if (EnhancedDebuggerWindow.MAX_TABLE_ROWS > 0 &&
messagesTable.getRowCount() >= EnhancedDebuggerWindow.MAX_TABLE_ROWS) {
messagesTable.removeRow(0);
}
messagesTable.addRow(
new Object[] {
XmlUtil.prettyFormatXml(packet.toXML().toString()),
dateFormatter.format(new Date()),
packetSentIcon,
packetTypeIcon,
messageType,
stanzaId,
type,
to,
""});
// Update the statistics table
updateStatistics();
}
});
} | java | private void addSentPacketToTable(final SimpleDateFormat dateFormatter, final TopLevelStreamElement packet) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String messageType;
Jid to;
String stanzaId;
if (packet instanceof Stanza) {
Stanza stanza = (Stanza) packet;
to = stanza.getTo();
stanzaId = stanza.getStanzaId();
} else {
to = null;
stanzaId = "(Nonza)";
}
String type = "";
Icon packetTypeIcon;
sentPackets++;
if (packet instanceof IQ) {
packetTypeIcon = iqPacketIcon;
messageType = "IQ Sent (class=" + packet.getClass().getName() + ")";
type = ((IQ) packet).getType().toString();
sentIQPackets++;
}
else if (packet instanceof Message) {
packetTypeIcon = messagePacketIcon;
messageType = "Message Sent";
type = ((Message) packet).getType().toString();
sentMessagePackets++;
}
else if (packet instanceof Presence) {
packetTypeIcon = presencePacketIcon;
messageType = "Presence Sent";
type = ((Presence) packet).getType().toString();
sentPresencePackets++;
}
else {
packetTypeIcon = unknownPacketTypeIcon;
messageType = packet.getClass().getName() + " Sent";
sentOtherPackets++;
}
// Check if we need to remove old rows from the table to keep memory consumption low
if (EnhancedDebuggerWindow.MAX_TABLE_ROWS > 0 &&
messagesTable.getRowCount() >= EnhancedDebuggerWindow.MAX_TABLE_ROWS) {
messagesTable.removeRow(0);
}
messagesTable.addRow(
new Object[] {
XmlUtil.prettyFormatXml(packet.toXML().toString()),
dateFormatter.format(new Date()),
packetSentIcon,
packetTypeIcon,
messageType,
stanzaId,
type,
to,
""});
// Update the statistics table
updateStatistics();
}
});
} | [
"private",
"void",
"addSentPacketToTable",
"(",
"final",
"SimpleDateFormat",
"dateFormatter",
",",
"final",
"TopLevelStreamElement",
"packet",
")",
"{",
"SwingUtilities",
".",
"invokeLater",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
... | Adds the sent stanza detail to the messages table.
@param dateFormatter the SimpleDateFormat to use to format Dates
@param packet the sent stanza to add to the table | [
"Adds",
"the",
"sent",
"stanza",
"detail",
"to",
"the",
"messages",
"table",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-debug/src/main/java/org/jivesoftware/smackx/debugger/EnhancedDebugger.java#L835-L899 |
james-hu/jabb-core | src/main/java/net/sf/jabb/util/text/StartWithMatcher.java | StartWithMatcher.setAttachmentByExample | protected void setAttachmentByExample(String example, Object att, String exp){
int p = getLastAcceptedState(example, 0);
if (p != -1){
this.attachments[p] = att;
}else{
// 说明精确匹配示范字符串有错误
throw new IllegalArgumentException("\"" + example + "\" can not match \"" + exp + "\"");
}
} | java | protected void setAttachmentByExample(String example, Object att, String exp){
int p = getLastAcceptedState(example, 0);
if (p != -1){
this.attachments[p] = att;
}else{
// 说明精确匹配示范字符串有错误
throw new IllegalArgumentException("\"" + example + "\" can not match \"" + exp + "\"");
}
} | [
"protected",
"void",
"setAttachmentByExample",
"(",
"String",
"example",
",",
"Object",
"att",
",",
"String",
"exp",
")",
"{",
"int",
"p",
"=",
"getLastAcceptedState",
"(",
"example",
",",
"0",
")",
";",
"if",
"(",
"p",
"!=",
"-",
"1",
")",
"{",
"this"... | Set attachment object for each state, by testing which state the example string can run into.<br>
根据示范字符串,设置各状态所对应的附件对象。
@param example Example string.<br>示范字符串
@param att Attachment object.<br>附件对象
@param exp Regular expression which will only be used within the exception message.<br>
正则表达式字符串(仅被用在抛出的异常消息中) | [
"Set",
"attachment",
"object",
"for",
"each",
"state",
"by",
"testing",
"which",
"state",
"the",
"example",
"string",
"can",
"run",
"into",
".",
"<br",
">",
"根据示范字符串,设置各状态所对应的附件对象。"
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/text/StartWithMatcher.java#L184-L192 |
btrplace/scheduler | api/src/main/java/org/btrplace/model/view/ShareableResource.java | ShareableResource.sumCapacities | public int sumCapacities(Collection<Node> ids, boolean undef) {
int s = 0;
for (Node u: ids) {
if (capacityDefined(u) || undef) {
s += nodesCapacity.get(u);
}
}
return s;
} | java | public int sumCapacities(Collection<Node> ids, boolean undef) {
int s = 0;
for (Node u: ids) {
if (capacityDefined(u) || undef) {
s += nodesCapacity.get(u);
}
}
return s;
} | [
"public",
"int",
"sumCapacities",
"(",
"Collection",
"<",
"Node",
">",
"ids",
",",
"boolean",
"undef",
")",
"{",
"int",
"s",
"=",
"0",
";",
"for",
"(",
"Node",
"u",
":",
"ids",
")",
"{",
"if",
"(",
"capacityDefined",
"(",
"u",
")",
"||",
"undef",
... | Get the cumulative nodes capacity.
@param ids the nodes.
@param undef {@code true} to include the undefined elements using the default value
@return the value | [
"Get",
"the",
"cumulative",
"nodes",
"capacity",
"."
] | train | https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/model/view/ShareableResource.java#L384-L392 |
LGoodDatePicker/LGoodDatePicker | Project/src/main/java/com/github/lgooddatepicker/components/TimePicker.java | TimePicker.zInternalSetLastValidTimeAndNotifyListeners | private void zInternalSetLastValidTimeAndNotifyListeners(LocalTime newTime) {
LocalTime oldTime = lastValidTime;
lastValidTime = newTime;
if (!PickerUtilities.isSameLocalTime(oldTime, newTime)) {
for (TimeChangeListener timeChangeListener : timeChangeListeners) {
TimeChangeEvent timeChangeEvent = new TimeChangeEvent(this, oldTime, newTime);
timeChangeListener.timeChanged(timeChangeEvent);
}
// Fire a change event for beans binding.
firePropertyChange("time", oldTime, newTime);
}
} | java | private void zInternalSetLastValidTimeAndNotifyListeners(LocalTime newTime) {
LocalTime oldTime = lastValidTime;
lastValidTime = newTime;
if (!PickerUtilities.isSameLocalTime(oldTime, newTime)) {
for (TimeChangeListener timeChangeListener : timeChangeListeners) {
TimeChangeEvent timeChangeEvent = new TimeChangeEvent(this, oldTime, newTime);
timeChangeListener.timeChanged(timeChangeEvent);
}
// Fire a change event for beans binding.
firePropertyChange("time", oldTime, newTime);
}
} | [
"private",
"void",
"zInternalSetLastValidTimeAndNotifyListeners",
"(",
"LocalTime",
"newTime",
")",
"{",
"LocalTime",
"oldTime",
"=",
"lastValidTime",
";",
"lastValidTime",
"=",
"newTime",
";",
"if",
"(",
"!",
"PickerUtilities",
".",
"isSameLocalTime",
"(",
"oldTime",... | zInternalSetLastValidTimeAndNotifyListeners, This should be called whenever we need to change
the last valid time variable. This will store the supplied last valid time. If needed, this
will notify all time change listeners that the time has been changed. This does not perform
any other tasks besides those described here. | [
"zInternalSetLastValidTimeAndNotifyListeners",
"This",
"should",
"be",
"called",
"whenever",
"we",
"need",
"to",
"change",
"the",
"last",
"valid",
"time",
"variable",
".",
"This",
"will",
"store",
"the",
"supplied",
"last",
"valid",
"time",
".",
"If",
"needed",
... | train | https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/github/lgooddatepicker/components/TimePicker.java#L975-L986 |
getsentry/sentry-java | sentry/src/main/java/io/sentry/connection/HttpConnection.java | HttpConnection.getSentryApiUrl | public static URL getSentryApiUrl(URI sentryUri, String projectId) {
try {
String url = sentryUri.toString() + "api/" + projectId + "/store/";
return new URL(url);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Couldn't build a valid URL from the Sentry API.", e);
}
} | java | public static URL getSentryApiUrl(URI sentryUri, String projectId) {
try {
String url = sentryUri.toString() + "api/" + projectId + "/store/";
return new URL(url);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Couldn't build a valid URL from the Sentry API.", e);
}
} | [
"public",
"static",
"URL",
"getSentryApiUrl",
"(",
"URI",
"sentryUri",
",",
"String",
"projectId",
")",
"{",
"try",
"{",
"String",
"url",
"=",
"sentryUri",
".",
"toString",
"(",
")",
"+",
"\"api/\"",
"+",
"projectId",
"+",
"\"/store/\"",
";",
"return",
"ne... | Automatically determines the URL to the HTTP API of Sentry.
@param sentryUri URI of the Sentry server.
@param projectId unique identifier of the current project.
@return an URL to the HTTP API of Sentry. | [
"Automatically",
"determines",
"the",
"URL",
"to",
"the",
"HTTP",
"API",
"of",
"Sentry",
"."
] | train | https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/connection/HttpConnection.java#L113-L120 |
opendatatrentino/smatch-webapi-client | src/main/java/it/unitn/disi/smatch/webapi/client/WebApiClient.java | WebApiClient.match | @Override
public Correspondence match(String sourceName, List<String> sourceNodes,
String targetName, List<String> targetNodes) {
MatchMethods method = new MatchMethods(httpClient, locale, serverPath);
Correspondence correspondace = null;
try {
correspondace = method.match(sourceName, sourceNodes, targetName, targetNodes);
} catch (WebApiException ex) {
java.util.logging.Logger.getLogger(WebApiClient.class.getName()).log(Level.SEVERE, null, ex);
}
return correspondace;
} | java | @Override
public Correspondence match(String sourceName, List<String> sourceNodes,
String targetName, List<String> targetNodes) {
MatchMethods method = new MatchMethods(httpClient, locale, serverPath);
Correspondence correspondace = null;
try {
correspondace = method.match(sourceName, sourceNodes, targetName, targetNodes);
} catch (WebApiException ex) {
java.util.logging.Logger.getLogger(WebApiClient.class.getName()).log(Level.SEVERE, null, ex);
}
return correspondace;
} | [
"@",
"Override",
"public",
"Correspondence",
"match",
"(",
"String",
"sourceName",
",",
"List",
"<",
"String",
">",
"sourceNodes",
",",
"String",
"targetName",
",",
"List",
"<",
"String",
">",
"targetNodes",
")",
"{",
"MatchMethods",
"method",
"=",
"new",
"M... | Returns the correspondence between the source and the target contexts
@param sourceName - The name of the root node in the source tree
@param sourceNodes - Names of the source nodes under the source root node
@param targetName - The name of the root node in the target tree
@param targetNodes -Names of the target nodes under the target root node
@return - the correspondence | [
"Returns",
"the",
"correspondence",
"between",
"the",
"source",
"and",
"the",
"target",
"contexts"
] | train | https://github.com/opendatatrentino/smatch-webapi-client/blob/d74fc41ab5bdc29afafd11c9001ac25dff20f965/src/main/java/it/unitn/disi/smatch/webapi/client/WebApiClient.java#L173-L187 |
JavaMoney/jsr354-ri-bp | src/main/java/org/javamoney/moneta/spi/base/BaseMonetaryRoundingsSingletonSpi.java | BaseMonetaryRoundingsSingletonSpi.getRounding | public MonetaryRounding getRounding(String roundingName, String... providers) {
MonetaryRounding op =
getRounding(RoundingQueryBuilder.of().setProviderNames(providers).setRoundingName(roundingName).build());
if(op==null) {
throw new MonetaryException("No rounding provided with rounding name: " + roundingName);
}
return op;
} | java | public MonetaryRounding getRounding(String roundingName, String... providers) {
MonetaryRounding op =
getRounding(RoundingQueryBuilder.of().setProviderNames(providers).setRoundingName(roundingName).build());
if(op==null) {
throw new MonetaryException("No rounding provided with rounding name: " + roundingName);
}
return op;
} | [
"public",
"MonetaryRounding",
"getRounding",
"(",
"String",
"roundingName",
",",
"String",
"...",
"providers",
")",
"{",
"MonetaryRounding",
"op",
"=",
"getRounding",
"(",
"RoundingQueryBuilder",
".",
"of",
"(",
")",
".",
"setProviderNames",
"(",
"providers",
")",... | Access a {@link javax.money.MonetaryRounding} using the rounding name.
@param roundingName The rounding name, not null.
@param providers the optional provider list and ordering to be used
@return the corresponding {@link javax.money.MonetaryOperator} implementing the
rounding, never {@code null}.
@throws IllegalArgumentException if no such rounding is registered using a
{@link javax.money.spi.RoundingProviderSpi} instance. | [
"Access",
"a",
"{",
"@link",
"javax",
".",
"money",
".",
"MonetaryRounding",
"}",
"using",
"the",
"rounding",
"name",
"."
] | train | https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/spi/base/BaseMonetaryRoundingsSingletonSpi.java#L65-L72 |
shrinkwrap/resolver | maven/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/repository/MavenRemoteRepositories.java | MavenRemoteRepositories.createRemoteRepository | public static MavenRemoteRepository createRemoteRepository(final String id, final URL url, final String layout) {
// Argument tests are inside the impl constructor
return new MavenRemoteRepositoryImpl(id, url, layout);
} | java | public static MavenRemoteRepository createRemoteRepository(final String id, final URL url, final String layout) {
// Argument tests are inside the impl constructor
return new MavenRemoteRepositoryImpl(id, url, layout);
} | [
"public",
"static",
"MavenRemoteRepository",
"createRemoteRepository",
"(",
"final",
"String",
"id",
",",
"final",
"URL",
"url",
",",
"final",
"String",
"layout",
")",
"{",
"// Argument tests are inside the impl constructor",
"return",
"new",
"MavenRemoteRepositoryImpl",
... | Creates a new <code>MavenRemoteRepository</code> with ID and URL. Please note that the repository layout should always be set to default.
@param id The unique ID of the repository to create (arbitrary name)
@param url The base URL of the Maven repository
@param layout he repository layout. Should always be "default"
@return A new <code>MavenRemoteRepository</code> with the given ID and URL.
@throws IllegalArgumentException for null or empty id
@throws RuntimeException if an error occurred during <code>MavenRemoteRepository</code> instance creation | [
"Creates",
"a",
"new",
"<code",
">",
"MavenRemoteRepository<",
"/",
"code",
">",
"with",
"ID",
"and",
"URL",
".",
"Please",
"note",
"that",
"the",
"repository",
"layout",
"should",
"always",
"be",
"set",
"to",
"default",
"."
] | train | https://github.com/shrinkwrap/resolver/blob/e881a84b8cff5b0a014f2a5ebf612be3eb9db01f/maven/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/repository/MavenRemoteRepositories.java#L25-L28 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java | XmlUtil.getNodeByXPath | public static Node getNodeByXPath(String expression, Object source) {
return (Node) getByXPath(expression, source, XPathConstants.NODE);
} | java | public static Node getNodeByXPath(String expression, Object source) {
return (Node) getByXPath(expression, source, XPathConstants.NODE);
} | [
"public",
"static",
"Node",
"getNodeByXPath",
"(",
"String",
"expression",
",",
"Object",
"source",
")",
"{",
"return",
"(",
"Node",
")",
"getByXPath",
"(",
"expression",
",",
"source",
",",
"XPathConstants",
".",
"NODE",
")",
";",
"}"
] | 通过XPath方式读取XML节点等信息<br>
Xpath相关文章:https://www.ibm.com/developerworks/cn/xml/x-javaxpathapi.html
@param expression XPath表达式
@param source 资源,可以是Docunent、Node节点等
@return 匹配返回类型的值
@since 4.0.9 | [
"通过XPath方式读取XML节点等信息<br",
">",
"Xpath相关文章:https",
":",
"//",
"www",
".",
"ibm",
".",
"com",
"/",
"developerworks",
"/",
"cn",
"/",
"xml",
"/",
"x",
"-",
"javaxpathapi",
".",
"html"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java#L598-L600 |
alkacon/opencms-core | src-gwt/org/opencms/ade/galleries/client/CmsGalleryController.java | CmsGalleryController.openPreview | public void openPreview(String resourcePath, String resourceType) {
if (m_currentPreview != null) {
m_currentPreview.removePreview();
}
String provider = getProviderName(resourceType);
if (m_previewFactoryRegistration.containsKey(provider)) {
m_handler.m_galleryDialog.useMaxDimensions();
m_currentPreview = m_previewFactoryRegistration.get(provider).getPreview(m_handler.m_galleryDialog);
m_currentPreview.openPreview(resourcePath, !m_resultsSelectable);
m_handler.hideShowPreviewButton(false);
} else {
CmsDebugLog.getInstance().printLine(
"Preview provider \"" + provider + "\" has not been registered properly.");
}
} | java | public void openPreview(String resourcePath, String resourceType) {
if (m_currentPreview != null) {
m_currentPreview.removePreview();
}
String provider = getProviderName(resourceType);
if (m_previewFactoryRegistration.containsKey(provider)) {
m_handler.m_galleryDialog.useMaxDimensions();
m_currentPreview = m_previewFactoryRegistration.get(provider).getPreview(m_handler.m_galleryDialog);
m_currentPreview.openPreview(resourcePath, !m_resultsSelectable);
m_handler.hideShowPreviewButton(false);
} else {
CmsDebugLog.getInstance().printLine(
"Preview provider \"" + provider + "\" has not been registered properly.");
}
} | [
"public",
"void",
"openPreview",
"(",
"String",
"resourcePath",
",",
"String",
"resourceType",
")",
"{",
"if",
"(",
"m_currentPreview",
"!=",
"null",
")",
"{",
"m_currentPreview",
".",
"removePreview",
"(",
")",
";",
"}",
"String",
"provider",
"=",
"getProvide... | Opens the preview for the given resource by the given resource type.<p>
@param resourcePath the resource path
@param resourceType the resource type name | [
"Opens",
"the",
"preview",
"for",
"the",
"given",
"resource",
"by",
"the",
"given",
"resource",
"type",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/CmsGalleryController.java#L1009-L1024 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.setCertificateIssuer | public IssuerBundle setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) {
return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).toBlocking().single().body();
} | java | public IssuerBundle setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) {
return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).toBlocking().single().body();
} | [
"public",
"IssuerBundle",
"setCertificateIssuer",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"issuerName",
",",
"String",
"provider",
",",
"IssuerCredentials",
"credentials",
",",
"OrganizationDetails",
"organizationDetails",
",",
"IssuerAttributes",
"attributes",
")",
... | Sets the specified certificate issuer.
The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the certificates/setissuers permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param issuerName The name of the issuer.
@param provider The issuer provider.
@param credentials The credentials to be used for the issuer.
@param organizationDetails Details of the organization as provided to the issuer.
@param attributes Attributes of the issuer object.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws KeyVaultErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the IssuerBundle object if successful. | [
"Sets",
"the",
"specified",
"certificate",
"issuer",
".",
"The",
"SetCertificateIssuer",
"operation",
"adds",
"or",
"updates",
"the",
"specified",
"certificate",
"issuer",
".",
"This",
"operation",
"requires",
"the",
"certificates",
"/",
"setissuers",
"permission",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L5999-L6001 |
vigna/Sux4J | src/it/unimi/dsi/sux4j/io/ChunkedHashStore.java | ChunkedHashStore.addAll | public void addAll(final Iterator<? extends T> elements, final LongIterator values, final boolean requiresValue2CountMap) throws IOException {
if (pl != null) {
pl.expectedUpdates = -1;
pl.start("Adding elements...");
}
final long[] triple = new long[3];
while(elements.hasNext()) {
Hashes.spooky4(transform.toBitVector(elements.next()), seed, triple);
add(triple, values != null ? values.nextLong() : filteredSize);
if (pl != null) pl.lightUpdate();
}
if (values != null && values.hasNext()) throw new IllegalStateException("The iterator on values contains more entries than the iterator on keys");
if (pl != null) pl.done();
} | java | public void addAll(final Iterator<? extends T> elements, final LongIterator values, final boolean requiresValue2CountMap) throws IOException {
if (pl != null) {
pl.expectedUpdates = -1;
pl.start("Adding elements...");
}
final long[] triple = new long[3];
while(elements.hasNext()) {
Hashes.spooky4(transform.toBitVector(elements.next()), seed, triple);
add(triple, values != null ? values.nextLong() : filteredSize);
if (pl != null) pl.lightUpdate();
}
if (values != null && values.hasNext()) throw new IllegalStateException("The iterator on values contains more entries than the iterator on keys");
if (pl != null) pl.done();
} | [
"public",
"void",
"addAll",
"(",
"final",
"Iterator",
"<",
"?",
"extends",
"T",
">",
"elements",
",",
"final",
"LongIterator",
"values",
",",
"final",
"boolean",
"requiresValue2CountMap",
")",
"throws",
"IOException",
"{",
"if",
"(",
"pl",
"!=",
"null",
")",... | Adds the elements returned by an iterator to this store, associating them with specified values,
possibly building the associated value frequency map.
@param elements an iterator returning elements.
@param values an iterator on values parallel to {@code elements}.
@param requiresValue2CountMap whether to build the value frequency map (associating with each value its frequency). | [
"Adds",
"the",
"elements",
"returned",
"by",
"an",
"iterator",
"to",
"this",
"store",
"associating",
"them",
"with",
"specified",
"values",
"possibly",
"building",
"the",
"associated",
"value",
"frequency",
"map",
"."
] | train | https://github.com/vigna/Sux4J/blob/d57de8fa897c7d273e0e6dae7a3274174f175a5f/src/it/unimi/dsi/sux4j/io/ChunkedHashStore.java#L345-L358 |
alibaba/jstorm | jstorm-core/src/main/java/com/alibaba/jstorm/transactional/TransactionTopologyBuilder.java | TransactionTopologyBuilder.setSpoutWithAck | public SpoutDeclarer setSpoutWithAck(String id, IRichSpout spout, Number parallelismHint) {
return setSpout(id, new AckTransactionSpout(spout), parallelismHint);
} | java | public SpoutDeclarer setSpoutWithAck(String id, IRichSpout spout, Number parallelismHint) {
return setSpout(id, new AckTransactionSpout(spout), parallelismHint);
} | [
"public",
"SpoutDeclarer",
"setSpoutWithAck",
"(",
"String",
"id",
",",
"IRichSpout",
"spout",
",",
"Number",
"parallelismHint",
")",
"{",
"return",
"setSpout",
"(",
"id",
",",
"new",
"AckTransactionSpout",
"(",
"spout",
")",
",",
"parallelismHint",
")",
";",
... | Build spout to provide the compatibility with Storm's ack mechanism
@param id spout Id
@param spout
@return | [
"Build",
"spout",
"to",
"provide",
"the",
"compatibility",
"with",
"Storm",
"s",
"ack",
"mechanism"
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/transactional/TransactionTopologyBuilder.java#L117-L119 |
gresrun/jesque | src/main/java/net/greghaines/jesque/worker/WorkerImpl.java | WorkerImpl.recoverFromException | protected void recoverFromException(final String curQueue, final Exception ex) {
final RecoveryStrategy recoveryStrategy = this.exceptionHandlerRef.get().onException(this, ex, curQueue);
switch (recoveryStrategy) {
case RECONNECT:
LOG.info("Reconnecting to Redis in response to exception", ex);
final int reconAttempts = getReconnectAttempts();
if (!JedisUtils.reconnect(this.jedis, reconAttempts, RECONNECT_SLEEP_TIME)) {
LOG.warn("Terminating in response to exception after " + reconAttempts + " to reconnect", ex);
end(false);
} else {
authenticateAndSelectDB();
LOG.info("Reconnected to Redis");
try {
loadRedisScripts();
} catch (IOException e) {
LOG.error("Failed to reload Lua scripts after reconnect", e);
}
}
break;
case TERMINATE:
LOG.warn("Terminating in response to exception", ex);
end(false);
break;
case PROCEED:
this.listenerDelegate.fireEvent(WORKER_ERROR, this, curQueue, null, null, null, ex);
break;
default:
LOG.error("Unknown RecoveryStrategy: " + recoveryStrategy
+ " while attempting to recover from the following exception; worker proceeding...", ex);
break;
}
} | java | protected void recoverFromException(final String curQueue, final Exception ex) {
final RecoveryStrategy recoveryStrategy = this.exceptionHandlerRef.get().onException(this, ex, curQueue);
switch (recoveryStrategy) {
case RECONNECT:
LOG.info("Reconnecting to Redis in response to exception", ex);
final int reconAttempts = getReconnectAttempts();
if (!JedisUtils.reconnect(this.jedis, reconAttempts, RECONNECT_SLEEP_TIME)) {
LOG.warn("Terminating in response to exception after " + reconAttempts + " to reconnect", ex);
end(false);
} else {
authenticateAndSelectDB();
LOG.info("Reconnected to Redis");
try {
loadRedisScripts();
} catch (IOException e) {
LOG.error("Failed to reload Lua scripts after reconnect", e);
}
}
break;
case TERMINATE:
LOG.warn("Terminating in response to exception", ex);
end(false);
break;
case PROCEED:
this.listenerDelegate.fireEvent(WORKER_ERROR, this, curQueue, null, null, null, ex);
break;
default:
LOG.error("Unknown RecoveryStrategy: " + recoveryStrategy
+ " while attempting to recover from the following exception; worker proceeding...", ex);
break;
}
} | [
"protected",
"void",
"recoverFromException",
"(",
"final",
"String",
"curQueue",
",",
"final",
"Exception",
"ex",
")",
"{",
"final",
"RecoveryStrategy",
"recoveryStrategy",
"=",
"this",
".",
"exceptionHandlerRef",
".",
"get",
"(",
")",
".",
"onException",
"(",
"... | Handle an exception that was thrown from inside {@link #poll()}.
@param curQueue the name of the queue that was being processed when the exception was thrown
@param ex the exception that was thrown | [
"Handle",
"an",
"exception",
"that",
"was",
"thrown",
"from",
"inside",
"{",
"@link",
"#poll",
"()",
"}",
"."
] | train | https://github.com/gresrun/jesque/blob/44749183dccc40962a94c2af547ea7d0d880b5d1/src/main/java/net/greghaines/jesque/worker/WorkerImpl.java#L527-L558 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/event/WriteOnChangeHandler.java | WriteOnChangeHandler.syncClonedListener | public boolean syncClonedListener(BaseField field, FieldListener listener, boolean bInitCalled)
{
if (!bInitCalled)
((WriteOnChangeHandler)listener).init(null, m_bRefreshAfterWrite);
return super.syncClonedListener(field, listener, true);
} | java | public boolean syncClonedListener(BaseField field, FieldListener listener, boolean bInitCalled)
{
if (!bInitCalled)
((WriteOnChangeHandler)listener).init(null, m_bRefreshAfterWrite);
return super.syncClonedListener(field, listener, true);
} | [
"public",
"boolean",
"syncClonedListener",
"(",
"BaseField",
"field",
",",
"FieldListener",
"listener",
",",
"boolean",
"bInitCalled",
")",
"{",
"if",
"(",
"!",
"bInitCalled",
")",
"(",
"(",
"WriteOnChangeHandler",
")",
"listener",
")",
".",
"init",
"(",
"null... | Set this cloned listener to the same state at this listener.
@param field The field this new listener will be added to.
@param The new listener to sync to this.
@param Has the init method been called?
@return True if I called init. | [
"Set",
"this",
"cloned",
"listener",
"to",
"the",
"same",
"state",
"at",
"this",
"listener",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/WriteOnChangeHandler.java#L69-L74 |
JoeKerouac/utils | src/main/java/com/joe/utils/img/ImgUtil.java | ImgUtil.compression | public static BufferedImage compression(BufferedImage src, int widthScale, int heightScale) {
int oldWidth = src.getWidth();
int oldHeight = src.getHeight();
int width = oldWidth / widthScale + ((oldWidth % widthScale) > 0 ? 1 : 0);
int height = oldHeight / heightScale + ((oldHeight % heightScale) > 0 ? 1 : 0);
BufferedImage dest = new BufferedImage(width, height, src.getType());
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = src.getRGB(x * widthScale, y * heightScale);
dest.setRGB(x, y, rgb);
}
}
return dest;
} | java | public static BufferedImage compression(BufferedImage src, int widthScale, int heightScale) {
int oldWidth = src.getWidth();
int oldHeight = src.getHeight();
int width = oldWidth / widthScale + ((oldWidth % widthScale) > 0 ? 1 : 0);
int height = oldHeight / heightScale + ((oldHeight % heightScale) > 0 ? 1 : 0);
BufferedImage dest = new BufferedImage(width, height, src.getType());
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = src.getRGB(x * widthScale, y * heightScale);
dest.setRGB(x, y, rgb);
}
}
return dest;
} | [
"public",
"static",
"BufferedImage",
"compression",
"(",
"BufferedImage",
"src",
",",
"int",
"widthScale",
",",
"int",
"heightScale",
")",
"{",
"int",
"oldWidth",
"=",
"src",
".",
"getWidth",
"(",
")",
";",
"int",
"oldHeight",
"=",
"src",
".",
"getHeight",
... | 缩放图片
@param src 图片源
@param widthScale 宽度缩放比例
@param heightScale 高度缩放比列
@return 缩放后的图片(会变模糊) | [
"缩放图片"
] | train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/img/ImgUtil.java#L177-L193 |
Metatavu/edelphi | edelphi-persistence/src/main/java/fi/metatavu/edelphi/dao/querydata/QueryQuestionOptionAnswerDAO.java | QueryQuestionOptionAnswerDAO.findTextByQueryReplyAndQueryField | public String findTextByQueryReplyAndQueryField(QueryReply queryReply, QueryField queryField) {
EntityManager entityManager = getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<String> criteria = criteriaBuilder.createQuery(String.class);
Root<QueryQuestionOptionAnswer> root = criteria.from(QueryQuestionOptionAnswer.class);
Join<QueryQuestionOptionAnswer, QueryOptionFieldOption> option = root.join(QueryQuestionOptionAnswer_.option);
criteria.select(option.get(QueryOptionFieldOption_.text));
criteria.where(
criteriaBuilder.and(
criteriaBuilder.equal(root.get(QueryQuestionOptionAnswer_.queryField), queryField),
criteriaBuilder.equal(root.get(QueryQuestionOptionAnswer_.queryReply), queryReply)
)
);
return getSingleResult(entityManager.createQuery(criteria));
} | java | public String findTextByQueryReplyAndQueryField(QueryReply queryReply, QueryField queryField) {
EntityManager entityManager = getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<String> criteria = criteriaBuilder.createQuery(String.class);
Root<QueryQuestionOptionAnswer> root = criteria.from(QueryQuestionOptionAnswer.class);
Join<QueryQuestionOptionAnswer, QueryOptionFieldOption> option = root.join(QueryQuestionOptionAnswer_.option);
criteria.select(option.get(QueryOptionFieldOption_.text));
criteria.where(
criteriaBuilder.and(
criteriaBuilder.equal(root.get(QueryQuestionOptionAnswer_.queryField), queryField),
criteriaBuilder.equal(root.get(QueryQuestionOptionAnswer_.queryReply), queryReply)
)
);
return getSingleResult(entityManager.createQuery(criteria));
} | [
"public",
"String",
"findTextByQueryReplyAndQueryField",
"(",
"QueryReply",
"queryReply",
",",
"QueryField",
"queryField",
")",
"{",
"EntityManager",
"entityManager",
"=",
"getEntityManager",
"(",
")",
";",
"CriteriaBuilder",
"criteriaBuilder",
"=",
"entityManager",
".",
... | Finds answer text by query reply and query field
@param queryReply reply
@param queryField field
@return answer text | [
"Finds",
"answer",
"text",
"by",
"query",
"reply",
"and",
"query",
"field"
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi-persistence/src/main/java/fi/metatavu/edelphi/dao/querydata/QueryQuestionOptionAnswerDAO.java#L45-L63 |
dihedron/dihedron-commons | src/main/java/org/dihedron/core/reflection/Reflector.java | Reflector.translateArrayIndex | private int translateArrayIndex(int index, int length) throws ReflectorException {
if(!(index > 0 ? index < length : Math.abs(index) <= Math.abs(length))) {
logger.error("index ({}) must be less than number of elements ({})", index, length);
throw new ReflectorException("index must be less than number of elements");
}
int translated = index;
if(!(translated > 0 ? translated < length : Math.abs(translated) <= Math.abs(length))){
logger.error("index {} is out of bounds", translated);
throw new ArrayIndexOutOfBoundsException();
}
if(translated < 0) {
translated = length + translated;
}
return translated;
} | java | private int translateArrayIndex(int index, int length) throws ReflectorException {
if(!(index > 0 ? index < length : Math.abs(index) <= Math.abs(length))) {
logger.error("index ({}) must be less than number of elements ({})", index, length);
throw new ReflectorException("index must be less than number of elements");
}
int translated = index;
if(!(translated > 0 ? translated < length : Math.abs(translated) <= Math.abs(length))){
logger.error("index {} is out of bounds", translated);
throw new ArrayIndexOutOfBoundsException();
}
if(translated < 0) {
translated = length + translated;
}
return translated;
} | [
"private",
"int",
"translateArrayIndex",
"(",
"int",
"index",
",",
"int",
"length",
")",
"throws",
"ReflectorException",
"{",
"if",
"(",
"!",
"(",
"index",
">",
"0",
"?",
"index",
"<",
"length",
":",
"Math",
".",
"abs",
"(",
"index",
")",
"<=",
"Math",... | Utility method that translates an array index, either positive or negative,
into its positive representation. The method ensures that the index is within
array bounds, then it translates negative indexes to their positive
counterparts according to the simple rule that element at index -1 is the
last element in the array, index -2 is the one before the last, and so on.
@param index
the element offset within the array or the list.
@param length
the length of the array or the list.
@return
the actual (positive) index of the element.
@throws ReflectorException | [
"Utility",
"method",
"that",
"translates",
"an",
"array",
"index",
"either",
"positive",
"or",
"negative",
"into",
"its",
"positive",
"representation",
".",
"The",
"method",
"ensures",
"that",
"the",
"index",
"is",
"within",
"array",
"bounds",
"then",
"it",
"t... | train | https://github.com/dihedron/dihedron-commons/blob/a5194cdaa0d6417ef4aade6ea407a1cad6e8458e/src/main/java/org/dihedron/core/reflection/Reflector.java#L463-L478 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java | SDBaseOps.segmentMax | public SDVariable segmentMax(String name, SDVariable data, SDVariable segmentIds) {
validateNumerical("segmentMax", "data", data);
validateInteger("segmentMax", "segmentIds", segmentIds);
SDVariable ret = f().segmentMax(data, segmentIds);
return updateVariableNameAndReference(ret, name);
} | java | public SDVariable segmentMax(String name, SDVariable data, SDVariable segmentIds) {
validateNumerical("segmentMax", "data", data);
validateInteger("segmentMax", "segmentIds", segmentIds);
SDVariable ret = f().segmentMax(data, segmentIds);
return updateVariableNameAndReference(ret, name);
} | [
"public",
"SDVariable",
"segmentMax",
"(",
"String",
"name",
",",
"SDVariable",
"data",
",",
"SDVariable",
"segmentIds",
")",
"{",
"validateNumerical",
"(",
"\"segmentMax\"",
",",
"\"data\"",
",",
"data",
")",
";",
"validateInteger",
"(",
"\"segmentMax\"",
",",
... | Segment max operation.<br>
If data = [3, 6, 1, 4, 9, 2, 8]<br>
segmentIds = [0, 0, 1, 1, 1, 2, 2]<br>
then output = [6, 9, 8] = [max(3,6), max(1,4,9), max(2,8)]<br>
Note that the segment IDs must be sorted from smallest to largest segment.
See {@link #unsortedSegmentMax(String, SDVariable, SDVariable, int)}
for the same op without this sorted requirement
@param name Name of the output variable. May be null
@param data Data to perform segment max on
@param segmentIds Variable for the segment IDs
@return Segment max output | [
"Segment",
"max",
"operation",
".",
"<br",
">",
"If",
"data",
"=",
"[",
"3",
"6",
"1",
"4",
"9",
"2",
"8",
"]",
"<br",
">",
"segmentIds",
"=",
"[",
"0",
"0",
"1",
"1",
"1",
"2",
"2",
"]",
"<br",
">",
"then",
"output",
"=",
"[",
"6",
"9",
... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L2214-L2219 |
jenkinsci/github-plugin | src/main/java/com/cloudbees/jenkins/GitHubWebHook.java | GitHubWebHook.doIndex | @SuppressWarnings("unused")
@RequirePostWithGHHookPayload
public void doIndex(@Nonnull @GHEventHeader GHEvent event, @Nonnull @GHEventPayload String payload) {
GHSubscriberEvent subscriberEvent =
new GHSubscriberEvent(SCMEvent.originOf(Stapler.getCurrentRequest()), event, payload);
from(GHEventsSubscriber.all())
.filter(isInterestedIn(event))
.transform(processEvent(subscriberEvent)).toList();
} | java | @SuppressWarnings("unused")
@RequirePostWithGHHookPayload
public void doIndex(@Nonnull @GHEventHeader GHEvent event, @Nonnull @GHEventPayload String payload) {
GHSubscriberEvent subscriberEvent =
new GHSubscriberEvent(SCMEvent.originOf(Stapler.getCurrentRequest()), event, payload);
from(GHEventsSubscriber.all())
.filter(isInterestedIn(event))
.transform(processEvent(subscriberEvent)).toList();
} | [
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"@",
"RequirePostWithGHHookPayload",
"public",
"void",
"doIndex",
"(",
"@",
"Nonnull",
"@",
"GHEventHeader",
"GHEvent",
"event",
",",
"@",
"Nonnull",
"@",
"GHEventPayload",
"String",
"payload",
")",
"{",
"GHSubscrib... | Receives the webhook call
@param event GH event type. Never null
@param payload Payload from hook. Never blank | [
"Receives",
"the",
"webhook",
"call"
] | train | https://github.com/jenkinsci/github-plugin/blob/4e05b9aeb488af5342c78f78aa3c55114e8d462a/src/main/java/com/cloudbees/jenkins/GitHubWebHook.java#L117-L125 |
bwkimmel/jdcp | jdcp-console/src/main/java/ca/eandb/jdcp/client/ScriptFacade.java | ScriptFacade.submitJob | public UUID submitJob(ParallelizableJob job, String description) throws Exception {
return config.getJobService().submitJob(
new Serialized<ParallelizableJob>(job), description);
} | java | public UUID submitJob(ParallelizableJob job, String description) throws Exception {
return config.getJobService().submitJob(
new Serialized<ParallelizableJob>(job), description);
} | [
"public",
"UUID",
"submitJob",
"(",
"ParallelizableJob",
"job",
",",
"String",
"description",
")",
"throws",
"Exception",
"{",
"return",
"config",
".",
"getJobService",
"(",
")",
".",
"submitJob",
"(",
"new",
"Serialized",
"<",
"ParallelizableJob",
">",
"(",
"... | Submits a job to be processed.
@param job The <code>ParallelizableJob</code> to submit.
@param description A description of the job.
@return The <code>UUID</code> identifying the submitted job.
@throws Exception if an error occurs in delegating the request to the
configured job service | [
"Submits",
"a",
"job",
"to",
"be",
"processed",
"."
] | train | https://github.com/bwkimmel/jdcp/blob/630c5150c245054e2556ff370f4bad2ec793dfb7/jdcp-console/src/main/java/ca/eandb/jdcp/client/ScriptFacade.java#L115-L118 |
spring-projects/spring-social | spring-social-core/src/main/java/org/springframework/social/oauth1/SigningSupport.java | SigningSupport.buildAuthorizationHeaderValue | public String buildAuthorizationHeaderValue(HttpRequest request, byte[] body, OAuth1Credentials oauth1Credentials) {
Map<String, String> oauthParameters = commonOAuthParameters(oauth1Credentials.getConsumerKey());
oauthParameters.put("oauth_token", oauth1Credentials.getAccessToken());
MultiValueMap<String, String> additionalParameters = union(readFormParameters(request.getHeaders().getContentType(), body), parseFormParameters(request.getURI().getRawQuery()));
return buildAuthorizationHeaderValue(request.getMethod(), request.getURI(), oauthParameters, additionalParameters, oauth1Credentials.getConsumerSecret(), oauth1Credentials.getAccessTokenSecret());
} | java | public String buildAuthorizationHeaderValue(HttpRequest request, byte[] body, OAuth1Credentials oauth1Credentials) {
Map<String, String> oauthParameters = commonOAuthParameters(oauth1Credentials.getConsumerKey());
oauthParameters.put("oauth_token", oauth1Credentials.getAccessToken());
MultiValueMap<String, String> additionalParameters = union(readFormParameters(request.getHeaders().getContentType(), body), parseFormParameters(request.getURI().getRawQuery()));
return buildAuthorizationHeaderValue(request.getMethod(), request.getURI(), oauthParameters, additionalParameters, oauth1Credentials.getConsumerSecret(), oauth1Credentials.getAccessTokenSecret());
} | [
"public",
"String",
"buildAuthorizationHeaderValue",
"(",
"HttpRequest",
"request",
",",
"byte",
"[",
"]",
"body",
",",
"OAuth1Credentials",
"oauth1Credentials",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"oauthParameters",
"=",
"commonOAuthParameters",
"("... | Builds an authorization header from a request.
Expects that the request's query parameters are form-encoded. | [
"Builds",
"an",
"authorization",
"header",
"from",
"a",
"request",
".",
"Expects",
"that",
"the",
"request",
"s",
"query",
"parameters",
"are",
"form",
"-",
"encoded",
"."
] | train | https://github.com/spring-projects/spring-social/blob/e41cfecb288022b83c79413b58f52511c3c9d4fc/spring-social-core/src/main/java/org/springframework/social/oauth1/SigningSupport.java#L75-L80 |
jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/ContactsApi.java | ContactsApi.getListRecentlyUploaded | public Contacts getListRecentlyUploaded(Date dateLastUpload, JinxConstants.Contacts filter) throws JinxException {
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.contacts.getListRecentlyUploaded");
if (dateLastUpload != null) {
params.put("date_lastupload", JinxUtils.formatDateAsUnixTimestamp(dateLastUpload));
}
if (filter != null) {
params.put("filter", filter.toString());
}
return jinx.flickrGet(params, Contacts.class);
} | java | public Contacts getListRecentlyUploaded(Date dateLastUpload, JinxConstants.Contacts filter) throws JinxException {
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.contacts.getListRecentlyUploaded");
if (dateLastUpload != null) {
params.put("date_lastupload", JinxUtils.formatDateAsUnixTimestamp(dateLastUpload));
}
if (filter != null) {
params.put("filter", filter.toString());
}
return jinx.flickrGet(params, Contacts.class);
} | [
"public",
"Contacts",
"getListRecentlyUploaded",
"(",
"Date",
"dateLastUpload",
",",
"JinxConstants",
".",
"Contacts",
"filter",
")",
"throws",
"JinxException",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"params",
"=",
"new",
"TreeMap",
"<>",
"(",
")",
";"... | Return a list of contacts for a user who have recently uploaded photos along with the total count of photos uploaded.
<br>
Flickr documentation states:
"This method is still considered experimental. We don't plan for it to change or to go away but so long as this notice
is present you should write your code accordingly."
<br>
This method requires authentication with 'read' permission.
<br>
@param dateLastUpload Optional. Limits the resultset to contacts that have uploaded photos since this date. The default offset is (1) hour and the maximum (24) hours.
@param filter Optional. Limit the result set to all contacts or only those who are friends or family.
@return object containing contacts matching the parameters.
@throws JinxException if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.contacts.getListRecentlyUploaded.html">flickr.contacts.getListRecentlyUploaded</a> | [
"Return",
"a",
"list",
"of",
"contacts",
"for",
"a",
"user",
"who",
"have",
"recently",
"uploaded",
"photos",
"along",
"with",
"the",
"total",
"count",
"of",
"photos",
"uploaded",
".",
"<br",
">",
"Flickr",
"documentation",
"states",
":",
"This",
"method",
... | train | https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/ContactsApi.java#L92-L102 |
apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/AsyncDataStream.java | AsyncDataStream.orderedWait | public static <IN, OUT> SingleOutputStreamOperator<OUT> orderedWait(
DataStream<IN> in,
AsyncFunction<IN, OUT> func,
long timeout,
TimeUnit timeUnit,
int capacity) {
return addOperator(in, func, timeUnit.toMillis(timeout), capacity, OutputMode.ORDERED);
} | java | public static <IN, OUT> SingleOutputStreamOperator<OUT> orderedWait(
DataStream<IN> in,
AsyncFunction<IN, OUT> func,
long timeout,
TimeUnit timeUnit,
int capacity) {
return addOperator(in, func, timeUnit.toMillis(timeout), capacity, OutputMode.ORDERED);
} | [
"public",
"static",
"<",
"IN",
",",
"OUT",
">",
"SingleOutputStreamOperator",
"<",
"OUT",
">",
"orderedWait",
"(",
"DataStream",
"<",
"IN",
">",
"in",
",",
"AsyncFunction",
"<",
"IN",
",",
"OUT",
">",
"func",
",",
"long",
"timeout",
",",
"TimeUnit",
"tim... | Add an AsyncWaitOperator. The order to process input records is guaranteed to be the same as
input ones.
@param in Input {@link DataStream}
@param func {@link AsyncFunction}
@param timeout for the asynchronous operation to complete
@param timeUnit of the given timeout
@param capacity The max number of async i/o operation that can be triggered
@param <IN> Type of input record
@param <OUT> Type of output record
@return A new {@link SingleOutputStreamOperator}. | [
"Add",
"an",
"AsyncWaitOperator",
".",
"The",
"order",
"to",
"process",
"input",
"records",
"is",
"guaranteed",
"to",
"be",
"the",
"same",
"as",
"input",
"ones",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/AsyncDataStream.java#L147-L154 |
mapbox/mapbox-java | services-geojson/src/main/java/com/mapbox/geojson/LineString.java | LineString.fromLngLats | public static LineString fromLngLats(@NonNull List<Point> points) {
return new LineString(TYPE, null, points);
} | java | public static LineString fromLngLats(@NonNull List<Point> points) {
return new LineString(TYPE, null, points);
} | [
"public",
"static",
"LineString",
"fromLngLats",
"(",
"@",
"NonNull",
"List",
"<",
"Point",
">",
"points",
")",
"{",
"return",
"new",
"LineString",
"(",
"TYPE",
",",
"null",
",",
"points",
")",
";",
"}"
] | Create a new instance of this class by defining a list of {@link Point}s which follow the
correct specifications described in the Point documentation. Note that there should not be any
duplicate points inside the list and the points combined should create a LineString with a
distance greater than 0.
<p>
Note that if less than 2 points are passed in, a runtime exception will occur.
</p>
@param points a list of {@link Point}s which make up the LineString geometry
@return a new instance of this class defined by the values passed inside this static factory
method
@since 3.0.0 | [
"Create",
"a",
"new",
"instance",
"of",
"this",
"class",
"by",
"defining",
"a",
"list",
"of",
"{",
"@link",
"Point",
"}",
"s",
"which",
"follow",
"the",
"correct",
"specifications",
"described",
"in",
"the",
"Point",
"documentation",
".",
"Note",
"that",
"... | train | https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/LineString.java#L108-L110 |
baratine/baratine | framework/src/main/java/com/caucho/v5/bartender/heartbeat/RootHeartbeat.java | RootHeartbeat.createCluster | ClusterHeartbeat createCluster(String clusterName)
{
ClusterHeartbeat cluster = _clusterMap.get(clusterName);
if (cluster == null) {
cluster = new ClusterHeartbeat(clusterName, this);
_clusterMap.putIfAbsent(clusterName, cluster);
cluster = _clusterMap.get(clusterName);
}
return cluster;
} | java | ClusterHeartbeat createCluster(String clusterName)
{
ClusterHeartbeat cluster = _clusterMap.get(clusterName);
if (cluster == null) {
cluster = new ClusterHeartbeat(clusterName, this);
_clusterMap.putIfAbsent(clusterName, cluster);
cluster = _clusterMap.get(clusterName);
}
return cluster;
} | [
"ClusterHeartbeat",
"createCluster",
"(",
"String",
"clusterName",
")",
"{",
"ClusterHeartbeat",
"cluster",
"=",
"_clusterMap",
".",
"get",
"(",
"clusterName",
")",
";",
"if",
"(",
"cluster",
"==",
"null",
")",
"{",
"cluster",
"=",
"new",
"ClusterHeartbeat",
"... | Returns the cluster with the given name, creating it if necessary. | [
"Returns",
"the",
"cluster",
"with",
"the",
"given",
"name",
"creating",
"it",
"if",
"necessary",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/bartender/heartbeat/RootHeartbeat.java#L197-L210 |
virgo47/javasimon | core/src/main/java/org/javasimon/utils/bean/ClassUtils.java | ClassUtils.getGetter | static Method getGetter(Class<?> targetClass, String propertyName) {
if (targetClass == null) {
return null;
}
final String getterName = getterName(propertyName, false);
Method result = findPublicGetter(targetClass, getterName, propertyName, false);
if (result == null) {
final String booleanGetterName = getterName(propertyName, true);
result = findPublicGetter(targetClass, booleanGetterName, propertyName, true);
if (result == null) {
do {
result = findNonPublicGetter(targetClass, getterName, propertyName, false);
if (result == null) {
result = findNonPublicGetter(targetClass, booleanGetterName, propertyName, true);
}
} while (result == null && (targetClass = targetClass.getSuperclass()) != null);
}
}
return result;
} | java | static Method getGetter(Class<?> targetClass, String propertyName) {
if (targetClass == null) {
return null;
}
final String getterName = getterName(propertyName, false);
Method result = findPublicGetter(targetClass, getterName, propertyName, false);
if (result == null) {
final String booleanGetterName = getterName(propertyName, true);
result = findPublicGetter(targetClass, booleanGetterName, propertyName, true);
if (result == null) {
do {
result = findNonPublicGetter(targetClass, getterName, propertyName, false);
if (result == null) {
result = findNonPublicGetter(targetClass, booleanGetterName, propertyName, true);
}
} while (result == null && (targetClass = targetClass.getSuperclass()) != null);
}
}
return result;
} | [
"static",
"Method",
"getGetter",
"(",
"Class",
"<",
"?",
">",
"targetClass",
",",
"String",
"propertyName",
")",
"{",
"if",
"(",
"targetClass",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"final",
"String",
"getterName",
"=",
"getterName",
"(",
"... | Get getter method for a specified property.
@param targetClass class for which a getter will be returned
@param propertyName name of the property for which a getter will be returned
@return getter of a specified property if one exists, null otherwise | [
"Get",
"getter",
"method",
"for",
"a",
"specified",
"property",
"."
] | train | https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/core/src/main/java/org/javasimon/utils/bean/ClassUtils.java#L128-L148 |
sai-pullabhotla/catatumbo | src/main/java/com/jmethods/catatumbo/impl/Unmarshaller.java | Unmarshaller.unmarshalProperty | private void unmarshalProperty(PropertyMetadata propertyMetadata, Object target)
throws Throwable {
unmarshalProperty(propertyMetadata, target, nativeEntity);
} | java | private void unmarshalProperty(PropertyMetadata propertyMetadata, Object target)
throws Throwable {
unmarshalProperty(propertyMetadata, target, nativeEntity);
} | [
"private",
"void",
"unmarshalProperty",
"(",
"PropertyMetadata",
"propertyMetadata",
",",
"Object",
"target",
")",
"throws",
"Throwable",
"{",
"unmarshalProperty",
"(",
"propertyMetadata",
",",
"target",
",",
"nativeEntity",
")",
";",
"}"
] | Unmarshals the property represented by the given property metadata and updates the target
object with the property value.
@param propertyMetadata
the property metadata
@param target
the target object to update
@throws Throwable
propagated | [
"Unmarshals",
"the",
"property",
"represented",
"by",
"the",
"given",
"property",
"metadata",
"and",
"updates",
"the",
"target",
"object",
"with",
"the",
"property",
"value",
"."
] | train | https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/Unmarshaller.java#L309-L312 |
allure-framework/allure1 | allure-java-adaptor-api/src/main/java/ru/yandex/qatools/allure/utils/AllureResultsUtils.java | AllureResultsUtils.createResultsDirectory | private static File createResultsDirectory() {
File resultsDirectory = CONFIG.getResultsDirectory();
if (createDirectories(resultsDirectory)) {
return resultsDirectory;
}
LOGGER.error(String.format(
"Results directory <%s> doesn't exists and can't be created, using default directory",
resultsDirectory.getAbsolutePath()
));
resultsDirectory = getDefaultResultsDirectory();
if (createDirectories(resultsDirectory)) {
return resultsDirectory;
}
LOGGER.error(String.format(
"Default results directory <%s> doesn't exists and can't be created, using temp directory",
resultsDirectory.getAbsolutePath()
));
try {
return Files.createTempDirectory("allure-results").toFile();
} catch (IOException e) {
throw new AllureException("Can't create results directory", e);
}
} | java | private static File createResultsDirectory() {
File resultsDirectory = CONFIG.getResultsDirectory();
if (createDirectories(resultsDirectory)) {
return resultsDirectory;
}
LOGGER.error(String.format(
"Results directory <%s> doesn't exists and can't be created, using default directory",
resultsDirectory.getAbsolutePath()
));
resultsDirectory = getDefaultResultsDirectory();
if (createDirectories(resultsDirectory)) {
return resultsDirectory;
}
LOGGER.error(String.format(
"Default results directory <%s> doesn't exists and can't be created, using temp directory",
resultsDirectory.getAbsolutePath()
));
try {
return Files.createTempDirectory("allure-results").toFile();
} catch (IOException e) {
throw new AllureException("Can't create results directory", e);
}
} | [
"private",
"static",
"File",
"createResultsDirectory",
"(",
")",
"{",
"File",
"resultsDirectory",
"=",
"CONFIG",
".",
"getResultsDirectory",
"(",
")",
";",
"if",
"(",
"createDirectories",
"(",
"resultsDirectory",
")",
")",
"{",
"return",
"resultsDirectory",
";",
... | Create results directory. First step try to create {@link #CONFIG#getResultsDirectory()},
if cannot, try to create {@link ru.yandex.qatools.allure.config.AllureConfig#getDefaultResultsDirectory},
and if cannot, returns a new <code>File</code> instance by converting the "allure-results"
pathname string into an abstract pathname.
@return created results directory | [
"Create",
"results",
"directory",
".",
"First",
"step",
"try",
"to",
"create",
"{",
"@link",
"#CONFIG#getResultsDirectory",
"()",
"}",
"if",
"cannot",
"try",
"to",
"create",
"{",
"@link",
"ru",
".",
"yandex",
".",
"qatools",
".",
"allure",
".",
"config",
"... | train | https://github.com/allure-framework/allure1/blob/9a816fa05d8b894a917b7ebb7fd1a4056dee4693/allure-java-adaptor-api/src/main/java/ru/yandex/qatools/allure/utils/AllureResultsUtils.java#L80-L107 |
mikepenz/FastAdapter | library/src/main/java/com/mikepenz/fastadapter/commons/utils/FastAdapterDiffUtil.java | FastAdapterDiffUtil.calculateDiff | public static <A extends ModelAdapter<Model, Item>, Model, Item extends IItem> DiffUtil.DiffResult calculateDiff(final A adapter, final List<Item> items, final DiffCallback<Item> callback, final boolean detectMoves) {
if (adapter.isUseIdDistributor()) {
adapter.getIdDistributor().checkIds(items);
}
// The FastAdapterDiffUtil does not handle expanded items. Call collapse if possible
collapseIfPossible(adapter.getFastAdapter());
//if we have a comparator then sort
if (adapter.getItemList() instanceof ComparableItemListImpl) {
Collections.sort(items, ((ComparableItemListImpl) adapter.getItemList()).getComparator());
}
//map the types
adapter.mapPossibleTypes(items);
//remember the old items
final List<Item> adapterItems = adapter.getAdapterItems();
final List<Item> oldItems = new ArrayList<>(adapterItems);
//pass in the oldItem list copy as we will update the one in the adapter itself
DiffUtil.DiffResult result = DiffUtil.calculateDiff(new FastAdapterCallback<>(oldItems, items, callback), detectMoves);
//make sure the new items list is not a reference of the already mItems list
if (items != adapterItems) {
//remove all previous items
if (!adapterItems.isEmpty()) {
adapterItems.clear();
}
//add all new items to the list
adapterItems.addAll(items);
}
return result;
} | java | public static <A extends ModelAdapter<Model, Item>, Model, Item extends IItem> DiffUtil.DiffResult calculateDiff(final A adapter, final List<Item> items, final DiffCallback<Item> callback, final boolean detectMoves) {
if (adapter.isUseIdDistributor()) {
adapter.getIdDistributor().checkIds(items);
}
// The FastAdapterDiffUtil does not handle expanded items. Call collapse if possible
collapseIfPossible(adapter.getFastAdapter());
//if we have a comparator then sort
if (adapter.getItemList() instanceof ComparableItemListImpl) {
Collections.sort(items, ((ComparableItemListImpl) adapter.getItemList()).getComparator());
}
//map the types
adapter.mapPossibleTypes(items);
//remember the old items
final List<Item> adapterItems = adapter.getAdapterItems();
final List<Item> oldItems = new ArrayList<>(adapterItems);
//pass in the oldItem list copy as we will update the one in the adapter itself
DiffUtil.DiffResult result = DiffUtil.calculateDiff(new FastAdapterCallback<>(oldItems, items, callback), detectMoves);
//make sure the new items list is not a reference of the already mItems list
if (items != adapterItems) {
//remove all previous items
if (!adapterItems.isEmpty()) {
adapterItems.clear();
}
//add all new items to the list
adapterItems.addAll(items);
}
return result;
} | [
"public",
"static",
"<",
"A",
"extends",
"ModelAdapter",
"<",
"Model",
",",
"Item",
">",
",",
"Model",
",",
"Item",
"extends",
"IItem",
">",
"DiffUtil",
".",
"DiffResult",
"calculateDiff",
"(",
"final",
"A",
"adapter",
",",
"final",
"List",
"<",
"Item",
... | This method will compute a {@link androidx.recyclerview.widget.DiffUtil.DiffResult} based on the given adapter, and the list of new items.
<p>
It automatically collapses all expandables (if enabled) as they are not supported by the diff util,
pre sort the items based on the comparator if available,
map the new item types for the FastAdapter then calculates the {@link androidx.recyclerview.widget.DiffUtil.DiffResult} using the {@link DiffUtil}.
<p>
As the last step it will replace the items inside the adapter with the new set of items provided.
@param adapter the adapter containing the current items.
@param items the new set of items we want to put into the adapter
@param callback the callback used to implement the required checks to identify changes of items.
@param detectMoves configuration for the {@link DiffUtil#calculateDiff(DiffUtil.Callback, boolean)} method
@param <A> The adapter type, whereas A extends {@link ModelAdapter}
@param <Model> The model type we work with
@param <Item> The item type kept in the adapter
@return the {@link androidx.recyclerview.widget.DiffUtil.DiffResult} computed. | [
"This",
"method",
"will",
"compute",
"a",
"{",
"@link",
"androidx",
".",
"recyclerview",
".",
"widget",
".",
"DiffUtil",
".",
"DiffResult",
"}",
"based",
"on",
"the",
"given",
"adapter",
"and",
"the",
"list",
"of",
"new",
"items",
".",
"<p",
">",
"It",
... | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library/src/main/java/com/mikepenz/fastadapter/commons/utils/FastAdapterDiffUtil.java#L43-L78 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.