repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 204 | func_name stringlengths 5 103 | whole_func_string stringlengths 87 3.44k | language stringclasses 1
value | func_code_string stringlengths 87 3.44k | func_code_tokens listlengths 21 714 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 482 | split_name stringclasses 1
value | func_code_url stringlengths 102 309 |
|---|---|---|---|---|---|---|---|---|---|---|
apache/incubator-gobblin | gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/ingestion/google/webmaster/TrieBasedProducerJob.java | TrieBasedProducerJob.partitionJobs | @Override
public List<? extends ProducerJob> partitionJobs() {
UrlTrieNode root = _jobNode.getRight();
if (isOperatorEquals() || root.getSize() == 1) {
//Either at an Equals-Node or a Leaf-Node, both of which actually has actual size 1.
return super.partitionJobs();
} else {
if (_groupSize <= 1) {
throw new RuntimeException("This is impossible. When group size is 1, the operator must be equals");
}
UrlTrie trie = new UrlTrie(getPage(), root);
int gs = Math.min(root.getSize(), _groupSize);
UrlTriePrefixGrouper grouper = new UrlTriePrefixGrouper(trie, (int) Math.ceil(gs / 2.0));
List<TrieBasedProducerJob> jobs = new ArrayList<>();
while (grouper.hasNext()) {
jobs.add(new TrieBasedProducerJob(_startDate, _endDate, grouper.next(), grouper.getGroupSize()));
}
return jobs;
}
} | java | @Override
public List<? extends ProducerJob> partitionJobs() {
UrlTrieNode root = _jobNode.getRight();
if (isOperatorEquals() || root.getSize() == 1) {
//Either at an Equals-Node or a Leaf-Node, both of which actually has actual size 1.
return super.partitionJobs();
} else {
if (_groupSize <= 1) {
throw new RuntimeException("This is impossible. When group size is 1, the operator must be equals");
}
UrlTrie trie = new UrlTrie(getPage(), root);
int gs = Math.min(root.getSize(), _groupSize);
UrlTriePrefixGrouper grouper = new UrlTriePrefixGrouper(trie, (int) Math.ceil(gs / 2.0));
List<TrieBasedProducerJob> jobs = new ArrayList<>();
while (grouper.hasNext()) {
jobs.add(new TrieBasedProducerJob(_startDate, _endDate, grouper.next(), grouper.getGroupSize()));
}
return jobs;
}
} | [
"@",
"Override",
"public",
"List",
"<",
"?",
"extends",
"ProducerJob",
">",
"partitionJobs",
"(",
")",
"{",
"UrlTrieNode",
"root",
"=",
"_jobNode",
".",
"getRight",
"(",
")",
";",
"if",
"(",
"isOperatorEquals",
"(",
")",
"||",
"root",
".",
"getSize",
"("... | The implementation here will first partition the job by pages, and then by dates.
@return | [
"The",
"implementation",
"here",
"will",
"first",
"partition",
"the",
"job",
"by",
"pages",
"and",
"then",
"by",
"dates",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/ingestion/google/webmaster/TrieBasedProducerJob.java#L73-L95 |
jamesagnew/hapi-fhir | hapi-fhir-base/src/main/java/ca/uhn/fhir/util/FhirTerser.java | FhirTerser.getValues | public List<Object> getValues(IBaseResource theResource, String thePath) {
Class<Object> wantedClass = Object.class;
return getValues(theResource, thePath, wantedClass);
} | java | public List<Object> getValues(IBaseResource theResource, String thePath) {
Class<Object> wantedClass = Object.class;
return getValues(theResource, thePath, wantedClass);
} | [
"public",
"List",
"<",
"Object",
">",
"getValues",
"(",
"IBaseResource",
"theResource",
",",
"String",
"thePath",
")",
"{",
"Class",
"<",
"Object",
">",
"wantedClass",
"=",
"Object",
".",
"class",
";",
"return",
"getValues",
"(",
"theResource",
",",
"thePath... | Returns values stored in an element identified by its path. The list of values is of
type {@link Object}.
@param theResource The resource instance to be accessed. Must not be null.
@param thePath The path for the element to be accessed.
@return A list of values of type {@link Object}. | [
"Returns",
"values",
"stored",
"in",
"an",
"element",
"identified",
"by",
"its",
"path",
".",
"The",
"list",
"of",
"values",
"is",
"of",
"type",
"{",
"@link",
"Object",
"}",
"."
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/FhirTerser.java#L485-L489 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/io/network/netty/PartitionRequestQueue.java | PartitionRequestQueue.addCredit | void addCredit(InputChannelID receiverId, int credit) throws Exception {
if (fatalError) {
return;
}
NetworkSequenceViewReader reader = allReaders.get(receiverId);
if (reader != null) {
reader.addCredit(credit);
enqueueAvailableReader(reader);
} else {
throw new IllegalStateException("No reader for receiverId = " + receiverId + " exists.");
}
} | java | void addCredit(InputChannelID receiverId, int credit) throws Exception {
if (fatalError) {
return;
}
NetworkSequenceViewReader reader = allReaders.get(receiverId);
if (reader != null) {
reader.addCredit(credit);
enqueueAvailableReader(reader);
} else {
throw new IllegalStateException("No reader for receiverId = " + receiverId + " exists.");
}
} | [
"void",
"addCredit",
"(",
"InputChannelID",
"receiverId",
",",
"int",
"credit",
")",
"throws",
"Exception",
"{",
"if",
"(",
"fatalError",
")",
"{",
"return",
";",
"}",
"NetworkSequenceViewReader",
"reader",
"=",
"allReaders",
".",
"get",
"(",
"receiverId",
")"... | Adds unannounced credits from the consumer and enqueues the corresponding reader for this
consumer (if not enqueued yet).
@param receiverId The input channel id to identify the consumer.
@param credit The unannounced credits of the consumer. | [
"Adds",
"unannounced",
"credits",
"from",
"the",
"consumer",
"and",
"enqueues",
"the",
"corresponding",
"reader",
"for",
"this",
"consumer",
"(",
"if",
"not",
"enqueued",
"yet",
")",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/netty/PartitionRequestQueue.java#L155-L168 |
mapsforge/mapsforge | sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java | DatabaseUtils.getCollationKey | public static String getCollationKey(String name) {
byte [] arr = getCollationKeyInBytes(name);
try {
return new String(arr, 0, getKeyLen(arr), "ISO8859_1");
} catch (Exception ex) {
return "";
}
} | java | public static String getCollationKey(String name) {
byte [] arr = getCollationKeyInBytes(name);
try {
return new String(arr, 0, getKeyLen(arr), "ISO8859_1");
} catch (Exception ex) {
return "";
}
} | [
"public",
"static",
"String",
"getCollationKey",
"(",
"String",
"name",
")",
"{",
"byte",
"[",
"]",
"arr",
"=",
"getCollationKeyInBytes",
"(",
"name",
")",
";",
"try",
"{",
"return",
"new",
"String",
"(",
"arr",
",",
"0",
",",
"getKeyLen",
"(",
"arr",
... | return the collation key
@param name
@return the collation key | [
"return",
"the",
"collation",
"key"
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java#L407-L414 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/DurableOutputHandler.java | DurableOutputHandler.initializeControlMessage | protected static void initializeControlMessage(SIBUuid8 sourceME, ControlMessage msg, SIBUuid8 remoteMEId)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "initializeControlMessage", new Object[] {msg, remoteMEId});
SIMPUtils.setGuaranteedDeliveryProperties(msg,
sourceME,
remoteMEId,
null,
null,
null,
ProtocolType.DURABLEINPUT,
GDConfig.PROTOCOL_VERSION);
msg.setPriority(SIMPConstants.CONTROL_MESSAGE_PRIORITY);
msg.setReliability(SIMPConstants.CONTROL_MESSAGE_RELIABILITY);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "initializeControlMessage");
} | java | protected static void initializeControlMessage(SIBUuid8 sourceME, ControlMessage msg, SIBUuid8 remoteMEId)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "initializeControlMessage", new Object[] {msg, remoteMEId});
SIMPUtils.setGuaranteedDeliveryProperties(msg,
sourceME,
remoteMEId,
null,
null,
null,
ProtocolType.DURABLEINPUT,
GDConfig.PROTOCOL_VERSION);
msg.setPriority(SIMPConstants.CONTROL_MESSAGE_PRIORITY);
msg.setReliability(SIMPConstants.CONTROL_MESSAGE_RELIABILITY);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "initializeControlMessage");
} | [
"protected",
"static",
"void",
"initializeControlMessage",
"(",
"SIBUuid8",
"sourceME",
",",
"ControlMessage",
"msg",
",",
"SIBUuid8",
"remoteMEId",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"("... | Common initialization for all messages sent by the DurableOutputHandler.
@param msg Message to initialize.
@param remoteMEId The ME the message will be sent to. | [
"Common",
"initialization",
"for",
"all",
"messages",
"sent",
"by",
"the",
"DurableOutputHandler",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/DurableOutputHandler.java#L547-L566 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java | CommerceWarehousePersistenceImpl.findByG_A_C | @Override
public List<CommerceWarehouse> findByG_A_C(long groupId, boolean active,
long commerceCountryId, int start, int end) {
return findByG_A_C(groupId, active, commerceCountryId, start, end, null);
} | java | @Override
public List<CommerceWarehouse> findByG_A_C(long groupId, boolean active,
long commerceCountryId, int start, int end) {
return findByG_A_C(groupId, active, commerceCountryId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceWarehouse",
">",
"findByG_A_C",
"(",
"long",
"groupId",
",",
"boolean",
"active",
",",
"long",
"commerceCountryId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByG_A_C",
"(",
"groupId",
",... | Returns a range of all the commerce warehouses where groupId = ? and active = ? and commerceCountryId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceWarehouseModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param groupId the group ID
@param active the active
@param commerceCountryId the commerce country ID
@param start the lower bound of the range of commerce warehouses
@param end the upper bound of the range of commerce warehouses (not inclusive)
@return the range of matching commerce warehouses | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"warehouses",
"where",
"groupId",
"=",
"?",
";",
"and",
"active",
"=",
"?",
";",
"and",
"commerceCountryId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java#L2308-L2312 |
alkacon/opencms-core | src/org/opencms/jsp/CmsJspTagDisplay.java | CmsJspTagDisplay.getFormatterForType | private I_CmsFormatterBean getFormatterForType(CmsObject cms, CmsResource resource, boolean isOnline) {
String typeName = OpenCms.getResourceManager().getResourceType(resource).getTypeName();
I_CmsFormatterBean result = null;
if (m_displayFormatterPaths.containsKey(typeName)) {
try {
CmsResource res = cms.readResource(m_displayFormatterPaths.get(typeName));
result = OpenCms.getADEManager().getCachedFormatters(isOnline).getFormatters().get(
res.getStructureId());
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
} else if (m_displayFormatterIds.containsKey(typeName)) {
result = OpenCms.getADEManager().getCachedFormatters(isOnline).getFormatters().get(
m_displayFormatterIds.get(typeName));
} else {
CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(
cms,
cms.addSiteRoot(cms.getRequestContext().getFolderUri()));
if (config != null) {
CmsFormatterConfiguration formatters = config.getFormatters(cms, resource);
if (formatters != null) {
result = formatters.getDisplayFormatter();
}
}
}
return result;
} | java | private I_CmsFormatterBean getFormatterForType(CmsObject cms, CmsResource resource, boolean isOnline) {
String typeName = OpenCms.getResourceManager().getResourceType(resource).getTypeName();
I_CmsFormatterBean result = null;
if (m_displayFormatterPaths.containsKey(typeName)) {
try {
CmsResource res = cms.readResource(m_displayFormatterPaths.get(typeName));
result = OpenCms.getADEManager().getCachedFormatters(isOnline).getFormatters().get(
res.getStructureId());
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
} else if (m_displayFormatterIds.containsKey(typeName)) {
result = OpenCms.getADEManager().getCachedFormatters(isOnline).getFormatters().get(
m_displayFormatterIds.get(typeName));
} else {
CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(
cms,
cms.addSiteRoot(cms.getRequestContext().getFolderUri()));
if (config != null) {
CmsFormatterConfiguration formatters = config.getFormatters(cms, resource);
if (formatters != null) {
result = formatters.getDisplayFormatter();
}
}
}
return result;
} | [
"private",
"I_CmsFormatterBean",
"getFormatterForType",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
",",
"boolean",
"isOnline",
")",
"{",
"String",
"typeName",
"=",
"OpenCms",
".",
"getResourceManager",
"(",
")",
".",
"getResourceType",
"(",
"resource",... | Returns the config for the requested resource, or <code>null</code> if not available.<p>
@param cms the cms context
@param resource the resource
@param isOnline the is online flag
@return the formatter configuration bean | [
"Returns",
"the",
"config",
"for",
"the",
"requested",
"resource",
"or",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"not",
"available",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagDisplay.java#L586-L613 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/internal/RowSetUtil.java | RowSetUtil.shard | @Nonnull
public static List<RowSet> shard(
@Nonnull RowSet rowSet, @Nonnull SortedSet<ByteString> splitPoints) {
return split(rowSet, splitPoints, false);
} | java | @Nonnull
public static List<RowSet> shard(
@Nonnull RowSet rowSet, @Nonnull SortedSet<ByteString> splitPoints) {
return split(rowSet, splitPoints, false);
} | [
"@",
"Nonnull",
"public",
"static",
"List",
"<",
"RowSet",
">",
"shard",
"(",
"@",
"Nonnull",
"RowSet",
"rowSet",
",",
"@",
"Nonnull",
"SortedSet",
"<",
"ByteString",
">",
"splitPoints",
")",
"{",
"return",
"split",
"(",
"rowSet",
",",
"splitPoints",
",",
... | Splits the provided {@link RowSet} into segments partitioned by the provided {@code
splitPoints}. Each split point represents the last row of the corresponding segment. The row
keys contained in the provided {@link RowSet} will be distributed across the segments. Each
range in the {@link RowSet} will be split up across each segment.
@see #split(RowSet, SortedSet, boolean) for more details. | [
"Splits",
"the",
"provided",
"{",
"@link",
"RowSet",
"}",
"into",
"segments",
"partitioned",
"by",
"the",
"provided",
"{",
"@code",
"splitPoints",
"}",
".",
"Each",
"split",
"point",
"represents",
"the",
"last",
"row",
"of",
"the",
"corresponding",
"segment",
... | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/internal/RowSetUtil.java#L75-L79 |
Hygieia/Hygieia | collectors/scm/github-graphql/src/main/java/com/capitalone/dashboard/collector/DefaultGitHubClient.java | DefaultGitHubClient.getRunDate | private String getRunDate(GitHubRepo repo, boolean firstRun, boolean missingCommits) {
if (missingCommits) {
long repoOffsetTime = getRepoOffsetTime(repo);
if (repoOffsetTime > 0) {
return getDate(new DateTime(getRepoOffsetTime(repo)), 0, settings.getOffsetMinutes()).toString();
} else {
return getDate(new DateTime(repo.getLastUpdated()), 0, settings.getOffsetMinutes()).toString();
}
}
if (firstRun) {
int firstRunDaysHistory = settings.getFirstRunHistoryDays();
if (firstRunDaysHistory > 0) {
return getDate(new DateTime(), firstRunDaysHistory, 0).toString();
} else {
return getDate(new DateTime(), FIRST_RUN_HISTORY_DEFAULT, 0).toString();
}
} else {
return getDate(new DateTime(repo.getLastUpdated()), 0, settings.getOffsetMinutes()).toString();
}
} | java | private String getRunDate(GitHubRepo repo, boolean firstRun, boolean missingCommits) {
if (missingCommits) {
long repoOffsetTime = getRepoOffsetTime(repo);
if (repoOffsetTime > 0) {
return getDate(new DateTime(getRepoOffsetTime(repo)), 0, settings.getOffsetMinutes()).toString();
} else {
return getDate(new DateTime(repo.getLastUpdated()), 0, settings.getOffsetMinutes()).toString();
}
}
if (firstRun) {
int firstRunDaysHistory = settings.getFirstRunHistoryDays();
if (firstRunDaysHistory > 0) {
return getDate(new DateTime(), firstRunDaysHistory, 0).toString();
} else {
return getDate(new DateTime(), FIRST_RUN_HISTORY_DEFAULT, 0).toString();
}
} else {
return getDate(new DateTime(repo.getLastUpdated()), 0, settings.getOffsetMinutes()).toString();
}
} | [
"private",
"String",
"getRunDate",
"(",
"GitHubRepo",
"repo",
",",
"boolean",
"firstRun",
",",
"boolean",
"missingCommits",
")",
"{",
"if",
"(",
"missingCommits",
")",
"{",
"long",
"repoOffsetTime",
"=",
"getRepoOffsetTime",
"(",
"repo",
")",
";",
"if",
"(",
... | Get run date based off of firstRun boolean
@param repo
@param firstRun
@return | [
"Get",
"run",
"date",
"based",
"off",
"of",
"firstRun",
"boolean"
] | train | https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/scm/github-graphql/src/main/java/com/capitalone/dashboard/collector/DefaultGitHubClient.java#L1013-L1032 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapred/MapTaskStatus.java | MapTaskStatus.calculateRate | private double calculateRate(long cumulative, long currentTime) {
long timeSinceMapStart = 0;
assert getPhase() == Phase.MAP : "MapTaskStatus not in map phase!";
long startTime = getStartTime();
timeSinceMapStart = currentTime - startTime;
if (timeSinceMapStart <= 0) {
LOG.error("Current time is " + currentTime +
" but start time is " + startTime);
return 0;
}
return cumulative/timeSinceMapStart;
} | java | private double calculateRate(long cumulative, long currentTime) {
long timeSinceMapStart = 0;
assert getPhase() == Phase.MAP : "MapTaskStatus not in map phase!";
long startTime = getStartTime();
timeSinceMapStart = currentTime - startTime;
if (timeSinceMapStart <= 0) {
LOG.error("Current time is " + currentTime +
" but start time is " + startTime);
return 0;
}
return cumulative/timeSinceMapStart;
} | [
"private",
"double",
"calculateRate",
"(",
"long",
"cumulative",
",",
"long",
"currentTime",
")",
"{",
"long",
"timeSinceMapStart",
"=",
"0",
";",
"assert",
"getPhase",
"(",
")",
"==",
"Phase",
".",
"MAP",
":",
"\"MapTaskStatus not in map phase!\"",
";",
"long",... | Helper function that calculate the rate, given the total so far and the
current time
@param cumulative
@param currentTime
@return | [
"Helper",
"function",
"that",
"calculate",
"the",
"rate",
"given",
"the",
"total",
"so",
"far",
"and",
"the",
"current",
"time"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/MapTaskStatus.java#L65-L78 |
prestodb/presto | presto-orc/src/main/java/com/facebook/presto/orc/OrcDataSourceUtils.java | OrcDataSourceUtils.mergeAdjacentDiskRanges | public static List<DiskRange> mergeAdjacentDiskRanges(Collection<DiskRange> diskRanges, DataSize maxMergeDistance, DataSize maxReadSize)
{
// sort ranges by start offset
List<DiskRange> ranges = new ArrayList<>(diskRanges);
Collections.sort(ranges, new Comparator<DiskRange>()
{
@Override
public int compare(DiskRange o1, DiskRange o2)
{
return Long.compare(o1.getOffset(), o2.getOffset());
}
});
// merge overlapping ranges
long maxReadSizeBytes = maxReadSize.toBytes();
long maxMergeDistanceBytes = maxMergeDistance.toBytes();
ImmutableList.Builder<DiskRange> result = ImmutableList.builder();
DiskRange last = ranges.get(0);
for (int i = 1; i < ranges.size(); i++) {
DiskRange current = ranges.get(i);
DiskRange merged = last.span(current);
if (merged.getLength() <= maxReadSizeBytes && last.getEnd() + maxMergeDistanceBytes >= current.getOffset()) {
last = merged;
}
else {
result.add(last);
last = current;
}
}
result.add(last);
return result.build();
} | java | public static List<DiskRange> mergeAdjacentDiskRanges(Collection<DiskRange> diskRanges, DataSize maxMergeDistance, DataSize maxReadSize)
{
// sort ranges by start offset
List<DiskRange> ranges = new ArrayList<>(diskRanges);
Collections.sort(ranges, new Comparator<DiskRange>()
{
@Override
public int compare(DiskRange o1, DiskRange o2)
{
return Long.compare(o1.getOffset(), o2.getOffset());
}
});
// merge overlapping ranges
long maxReadSizeBytes = maxReadSize.toBytes();
long maxMergeDistanceBytes = maxMergeDistance.toBytes();
ImmutableList.Builder<DiskRange> result = ImmutableList.builder();
DiskRange last = ranges.get(0);
for (int i = 1; i < ranges.size(); i++) {
DiskRange current = ranges.get(i);
DiskRange merged = last.span(current);
if (merged.getLength() <= maxReadSizeBytes && last.getEnd() + maxMergeDistanceBytes >= current.getOffset()) {
last = merged;
}
else {
result.add(last);
last = current;
}
}
result.add(last);
return result.build();
} | [
"public",
"static",
"List",
"<",
"DiskRange",
">",
"mergeAdjacentDiskRanges",
"(",
"Collection",
"<",
"DiskRange",
">",
"diskRanges",
",",
"DataSize",
"maxMergeDistance",
",",
"DataSize",
"maxReadSize",
")",
"{",
"// sort ranges by start offset",
"List",
"<",
"DiskRan... | Merge disk ranges that are closer than {@code maxMergeDistance}. | [
"Merge",
"disk",
"ranges",
"that",
"are",
"closer",
"than",
"{"
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-orc/src/main/java/com/facebook/presto/orc/OrcDataSourceUtils.java#L40-L72 |
netplex/json-smart-v2 | json-smart/src/main/java/net/minidev/json/reader/JsonWriter.java | JsonWriter.registerWriterInterfaceLast | public void registerWriterInterfaceLast(Class<?> interFace, JsonWriterI<?> writer) {
writerInterfaces.addLast(new WriterByInterface(interFace, writer));
} | java | public void registerWriterInterfaceLast(Class<?> interFace, JsonWriterI<?> writer) {
writerInterfaces.addLast(new WriterByInterface(interFace, writer));
} | [
"public",
"void",
"registerWriterInterfaceLast",
"(",
"Class",
"<",
"?",
">",
"interFace",
",",
"JsonWriterI",
"<",
"?",
">",
"writer",
")",
"{",
"writerInterfaces",
".",
"addLast",
"(",
"new",
"WriterByInterface",
"(",
"interFace",
",",
"writer",
")",
")",
... | associate an Writer to a interface With Low priority
@param interFace interface to map
@param writer writer Object | [
"associate",
"an",
"Writer",
"to",
"a",
"interface",
"With",
"Low",
"priority"
] | train | https://github.com/netplex/json-smart-v2/blob/bfb3daef039e22a7bbff5f76bf14ea23330cd70e/json-smart/src/main/java/net/minidev/json/reader/JsonWriter.java#L343-L345 |
hdecarne/java-default | src/main/java/de/carne/util/SystemProperties.java | SystemProperties.longValue | public static long longValue(String key, long defaultValue) {
String value = System.getProperty(key);
long longValue = defaultValue;
if (value != null) {
try {
longValue = Long.parseLong(value);
} catch (NumberFormatException e) {
LOG.warning(e, "Ignoring invalid long system propert: ''{0}'' = ''{1}''", key, value);
}
}
return longValue;
} | java | public static long longValue(String key, long defaultValue) {
String value = System.getProperty(key);
long longValue = defaultValue;
if (value != null) {
try {
longValue = Long.parseLong(value);
} catch (NumberFormatException e) {
LOG.warning(e, "Ignoring invalid long system propert: ''{0}'' = ''{1}''", key, value);
}
}
return longValue;
} | [
"public",
"static",
"long",
"longValue",
"(",
"String",
"key",
",",
"long",
"defaultValue",
")",
"{",
"String",
"value",
"=",
"System",
".",
"getProperty",
"(",
"key",
")",
";",
"long",
"longValue",
"=",
"defaultValue",
";",
"if",
"(",
"value",
"!=",
"nu... | Gets a {@code long} system property value.
@param key the property key to retrieve.
@param defaultValue the default value to return in case the property is not defined.
@return the property value or the submitted default value if the property is not defined. | [
"Gets",
"a",
"{",
"@code",
"long",
"}",
"system",
"property",
"value",
"."
] | train | https://github.com/hdecarne/java-default/blob/ca16f6fdb0436e90e9e2df3106055e320bb3c9e3/src/main/java/de/carne/util/SystemProperties.java#L189-L201 |
beihaifeiwu/dolphin | dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/plugin/ContentMergePlugin.java | ContentMergePlugin.mergeExistedElement | protected void mergeExistedElement(XmlElement src, XmlElement dest) {
// 合并属性
List<Attribute> srcAttributes = src.getAttributes();
List<Attribute> destAttributes = dest.getAttributes();
for (Attribute srcAttr : srcAttributes) {
Attribute matched = null;
for (Attribute destAttr : destAttributes) {
if (StringUtils.equals(srcAttr.getName(), destAttr.getName()) &&
StringUtils.equals(srcAttr.getValue(), destAttr.getValue())) {
matched = destAttr;
}
}
// 不存在则添加到目标元素的属性列表中
if (matched == null) {
destAttributes.add(srcAttributes.indexOf(srcAttr), srcAttr);
}
}
// 重组子节点
// reformationTheElementChilds(src);
// reformationTheElementChilds(dest);
// 暂时不做处理 ---留待后续添加
} | java | protected void mergeExistedElement(XmlElement src, XmlElement dest) {
// 合并属性
List<Attribute> srcAttributes = src.getAttributes();
List<Attribute> destAttributes = dest.getAttributes();
for (Attribute srcAttr : srcAttributes) {
Attribute matched = null;
for (Attribute destAttr : destAttributes) {
if (StringUtils.equals(srcAttr.getName(), destAttr.getName()) &&
StringUtils.equals(srcAttr.getValue(), destAttr.getValue())) {
matched = destAttr;
}
}
// 不存在则添加到目标元素的属性列表中
if (matched == null) {
destAttributes.add(srcAttributes.indexOf(srcAttr), srcAttr);
}
}
// 重组子节点
// reformationTheElementChilds(src);
// reformationTheElementChilds(dest);
// 暂时不做处理 ---留待后续添加
} | [
"protected",
"void",
"mergeExistedElement",
"(",
"XmlElement",
"src",
",",
"XmlElement",
"dest",
")",
"{",
"// 合并属性",
"List",
"<",
"Attribute",
">",
"srcAttributes",
"=",
"src",
".",
"getAttributes",
"(",
")",
";",
"List",
"<",
"Attribute",
">",
"destAttribute... | 合并已经存在的Xml元素
@param src The source xml element for merging
@param dest The dest xml element for merging | [
"合并已经存在的Xml元素"
] | train | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/plugin/ContentMergePlugin.java#L132-L156 |
OpenLiberty/open-liberty | dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/adaptor/ESAAdaptor.java | ESAAdaptor.isScript | private static boolean isScript(String base, ZipFile zip) {
Enumeration<? extends ZipEntry> files = zip.entries();
while (files.hasMoreElements()) {
ZipEntry f = files.nextElement();
if ((f.getName()).equals(base + ".bat") || (f.getName()).contains("/" + base + ".bat")) {
return true;
}
}
return false;
} | java | private static boolean isScript(String base, ZipFile zip) {
Enumeration<? extends ZipEntry> files = zip.entries();
while (files.hasMoreElements()) {
ZipEntry f = files.nextElement();
if ((f.getName()).equals(base + ".bat") || (f.getName()).contains("/" + base + ".bat")) {
return true;
}
}
return false;
} | [
"private",
"static",
"boolean",
"isScript",
"(",
"String",
"base",
",",
"ZipFile",
"zip",
")",
"{",
"Enumeration",
"<",
"?",
"extends",
"ZipEntry",
">",
"files",
"=",
"zip",
".",
"entries",
"(",
")",
";",
"while",
"(",
"files",
".",
"hasMoreElements",
"(... | Look for matching *.bat files in zip file. If there is then assume it is a script
@return true if matching *.bat file is found, false otherwise. | [
"Look",
"for",
"matching",
"*",
".",
"bat",
"files",
"in",
"zip",
"file",
".",
"If",
"there",
"is",
"then",
"assume",
"it",
"is",
"a",
"script"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/adaptor/ESAAdaptor.java#L682-L691 |
geomajas/geomajas-project-server | plugin/print/print/src/main/java/org/geomajas/plugin/printing/component/PdfContext.java | PdfContext.getTextSize | public Rectangle getTextSize(String text, Font font) {
template.saveState();
// get the font
DefaultFontMapper mapper = new DefaultFontMapper();
BaseFont bf = mapper.awtToPdf(font);
template.setFontAndSize(bf, font.getSize());
// calculate text width and height
float textWidth = template.getEffectiveStringWidth(text, false);
float ascent = bf.getAscentPoint(text, font.getSize());
float descent = bf.getDescentPoint(text, font.getSize());
float textHeight = ascent - descent;
template.restoreState();
return new Rectangle(0, 0, textWidth, textHeight);
} | java | public Rectangle getTextSize(String text, Font font) {
template.saveState();
// get the font
DefaultFontMapper mapper = new DefaultFontMapper();
BaseFont bf = mapper.awtToPdf(font);
template.setFontAndSize(bf, font.getSize());
// calculate text width and height
float textWidth = template.getEffectiveStringWidth(text, false);
float ascent = bf.getAscentPoint(text, font.getSize());
float descent = bf.getDescentPoint(text, font.getSize());
float textHeight = ascent - descent;
template.restoreState();
return new Rectangle(0, 0, textWidth, textHeight);
} | [
"public",
"Rectangle",
"getTextSize",
"(",
"String",
"text",
",",
"Font",
"font",
")",
"{",
"template",
".",
"saveState",
"(",
")",
";",
"// get the font",
"DefaultFontMapper",
"mapper",
"=",
"new",
"DefaultFontMapper",
"(",
")",
";",
"BaseFont",
"bf",
"=",
... | Return the text box for the specified text and font.
@param text text
@param font font
@return text box | [
"Return",
"the",
"text",
"box",
"for",
"the",
"specified",
"text",
"and",
"font",
"."
] | train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/plugin/print/print/src/main/java/org/geomajas/plugin/printing/component/PdfContext.java#L137-L150 |
cubedtear/aritzh | aritzh-core/src/main/java/io/github/aritzhack/aritzh/config/Configuration.java | Configuration.setProperty | public void setProperty(String category, String key, Object value) {
this.setProperty(category, key, value.toString());
} | java | public void setProperty(String category, String key, Object value) {
this.setProperty(category, key, value.toString());
} | [
"public",
"void",
"setProperty",
"(",
"String",
"category",
",",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"this",
".",
"setProperty",
"(",
"category",
",",
"key",
",",
"value",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Sets a property in the configuration
@param category The category of the property
@param key The key to identify the property
@param value The value associated with it | [
"Sets",
"a",
"property",
"in",
"the",
"configuration"
] | train | https://github.com/cubedtear/aritzh/blob/bc7493447a1a6088c4a7306ca4d0f0c20278364f/aritzh-core/src/main/java/io/github/aritzhack/aritzh/config/Configuration.java#L215-L217 |
i-net-software/jlessc | src/com/inet/lib/less/Operation.java | Operation.putConvertion | private static void putConvertion( HashMap<String, Double> group, String unit, double factor ) {
UNIT_CONVERSIONS.put(unit, group );
group.put( unit, factor );
} | java | private static void putConvertion( HashMap<String, Double> group, String unit, double factor ) {
UNIT_CONVERSIONS.put(unit, group );
group.put( unit, factor );
} | [
"private",
"static",
"void",
"putConvertion",
"(",
"HashMap",
"<",
"String",
",",
"Double",
">",
"group",
",",
"String",
"unit",
",",
"double",
"factor",
")",
"{",
"UNIT_CONVERSIONS",
".",
"put",
"(",
"unit",
",",
"group",
")",
";",
"group",
".",
"put",
... | Helper for creating static unit conversions.
@param group the unit group like length, duration or angles. Units of one group can convert in another.
@param unit the unit name
@param factor the convert factor | [
"Helper",
"for",
"creating",
"static",
"unit",
"conversions",
"."
] | train | https://github.com/i-net-software/jlessc/blob/15b13e1637f6cc2e4d72df021e23ee0ca8d5e629/src/com/inet/lib/less/Operation.java#L74-L77 |
osglworks/java-tool-ext | src/main/java/org/osgl/util/Token.java | Token.generateToken | @Deprecated
public static String generateToken(String secret, Life tl, String oid, String... payload) {
return generateToken(secret, tl.seconds, oid, payload);
} | java | @Deprecated
public static String generateToken(String secret, Life tl, String oid, String... payload) {
return generateToken(secret, tl.seconds, oid, payload);
} | [
"@",
"Deprecated",
"public",
"static",
"String",
"generateToken",
"(",
"String",
"secret",
",",
"Life",
"tl",
",",
"String",
"oid",
",",
"String",
"...",
"payload",
")",
"{",
"return",
"generateToken",
"(",
"secret",
",",
"tl",
".",
"seconds",
",",
"oid",
... | This method is deprecated, please use {@link #generateToken(byte[], Life, String, String...)} instead
Generate a token string with secret key, ID and optionally payloads
@param secret the secret to encrypt to token string
@param tl the expiration of the token
@param oid the ID of the token (could be customer ID etc)
@param payload the payload optionally indicate more information
@return an encrypted token string that is expiring in {@link Life#SHORT} time period | [
"This",
"method",
"is",
"deprecated",
"please",
"use",
"{",
"@link",
"#generateToken",
"(",
"byte",
"[]",
"Life",
"String",
"String",
"...",
")",
"}",
"instead"
] | train | https://github.com/osglworks/java-tool-ext/blob/43f034bd0a42e571e437f44aa20487d45248a30b/src/main/java/org/osgl/util/Token.java#L296-L299 |
TheHortonMachine/hortonmachine | gui/src/main/java/org/hortonmachine/gui/utils/GuiUtilities.java | GuiUtilities.colorButton | public static void colorButton( JButton button, Color color, Integer size ) {
if (size == null)
size = 15;
BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
Graphics2D gr = (Graphics2D) bi.getGraphics();
gr.setColor(color);
gr.fillRect(0, 0, size, size);
gr.dispose();
button.setIcon(new ImageIcon(bi));
} | java | public static void colorButton( JButton button, Color color, Integer size ) {
if (size == null)
size = 15;
BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
Graphics2D gr = (Graphics2D) bi.getGraphics();
gr.setColor(color);
gr.fillRect(0, 0, size, size);
gr.dispose();
button.setIcon(new ImageIcon(bi));
} | [
"public",
"static",
"void",
"colorButton",
"(",
"JButton",
"button",
",",
"Color",
"color",
",",
"Integer",
"size",
")",
"{",
"if",
"(",
"size",
"==",
"null",
")",
"size",
"=",
"15",
";",
"BufferedImage",
"bi",
"=",
"new",
"BufferedImage",
"(",
"size",
... | Create an image to make a color picker button.
@param button the button.
@param color the color to set.
@param size the optional size of the image. | [
"Create",
"an",
"image",
"to",
"make",
"a",
"color",
"picker",
"button",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gui/src/main/java/org/hortonmachine/gui/utils/GuiUtilities.java#L484-L494 |
wisdom-framework/wisdom | extensions/wisdom-filters/src/main/java/org/wisdom/framework/csrf/CSRFServiceImpl.java | CSRFServiceImpl.clearTokenIfInvalid | @Override
public Result clearTokenIfInvalid(Context context, String msg) {
Result error = handler.onError(context, msg);
final String cookieName = getCookieName();
if (cookieName != null) {
Cookie cookie = context.cookie(cookieName);
if (cookie != null) {
return error.without(cookieName);
}
} else {
context.session().remove(getTokenName());
}
return error;
} | java | @Override
public Result clearTokenIfInvalid(Context context, String msg) {
Result error = handler.onError(context, msg);
final String cookieName = getCookieName();
if (cookieName != null) {
Cookie cookie = context.cookie(cookieName);
if (cookie != null) {
return error.without(cookieName);
}
} else {
context.session().remove(getTokenName());
}
return error;
} | [
"@",
"Override",
"public",
"Result",
"clearTokenIfInvalid",
"(",
"Context",
"context",
",",
"String",
"msg",
")",
"{",
"Result",
"error",
"=",
"handler",
".",
"onError",
"(",
"context",
",",
"msg",
")",
";",
"final",
"String",
"cookieName",
"=",
"getCookieNa... | Clears the token from the request
@param context the context
@param msg the error message
@return the result | [
"Clears",
"the",
"token",
"from",
"the",
"request"
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/extensions/wisdom-filters/src/main/java/org/wisdom/framework/csrf/CSRFServiceImpl.java#L264-L277 |
RestComm/sipunit | src/main/java/org/cafesip/sipunit/SipAssert.java | SipAssert.assertBodyNotContains | public static void assertBodyNotContains(String msg, SipMessage sipMessage, String value) {
assertNotNull("Null assert object passed in", sipMessage);
if (sipMessage.getContentLength() > 0) {
String body = new String(sipMessage.getRawContent());
if (body.indexOf(value) != -1) {
fail(msg);
}
}
assertTrue(true);
} | java | public static void assertBodyNotContains(String msg, SipMessage sipMessage, String value) {
assertNotNull("Null assert object passed in", sipMessage);
if (sipMessage.getContentLength() > 0) {
String body = new String(sipMessage.getRawContent());
if (body.indexOf(value) != -1) {
fail(msg);
}
}
assertTrue(true);
} | [
"public",
"static",
"void",
"assertBodyNotContains",
"(",
"String",
"msg",
",",
"SipMessage",
"sipMessage",
",",
"String",
"value",
")",
"{",
"assertNotNull",
"(",
"\"Null assert object passed in\"",
",",
"sipMessage",
")",
";",
"if",
"(",
"sipMessage",
".",
"getC... | Asserts that the body in the given SIP message does not contain the value given, or that there
is no body in the message. The assertion fails if the body is present and contains the value.
Assertion failure output includes the given message text.
@param msg message text to output if the assertion fails.
@param sipMessage the SIP message.
@param value the string value to look for in the body. An exact string match is done against
the entire contents of the body. The assertion will fail if any part of the body matches
the value given. | [
"Asserts",
"that",
"the",
"body",
"in",
"the",
"given",
"SIP",
"message",
"does",
"not",
"contain",
"the",
"value",
"given",
"or",
"that",
"there",
"is",
"no",
"body",
"in",
"the",
"message",
".",
"The",
"assertion",
"fails",
"if",
"the",
"body",
"is",
... | train | https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipAssert.java#L735-L746 |
opsmatters/opsmatters-core | src/main/java/com/opsmatters/core/documents/XlsWorkbook.java | XlsWorkbook.createWorkbook | public static XlsWorkbook createWorkbook(OutputStream os, Workbook existing)
throws IOException
{
try
{
if(existing != null)
return new XlsWorkbook(jxl.Workbook.createWorkbook(os,
(jxl.Workbook)existing.getWorkbook(), settings));
else
return new XlsWorkbook(jxl.Workbook.createWorkbook(os, settings));
}
catch(jxl.read.biff.BiffException e)
{
throw new IOException(e);
}
} | java | public static XlsWorkbook createWorkbook(OutputStream os, Workbook existing)
throws IOException
{
try
{
if(existing != null)
return new XlsWorkbook(jxl.Workbook.createWorkbook(os,
(jxl.Workbook)existing.getWorkbook(), settings));
else
return new XlsWorkbook(jxl.Workbook.createWorkbook(os, settings));
}
catch(jxl.read.biff.BiffException e)
{
throw new IOException(e);
}
} | [
"public",
"static",
"XlsWorkbook",
"createWorkbook",
"(",
"OutputStream",
"os",
",",
"Workbook",
"existing",
")",
"throws",
"IOException",
"{",
"try",
"{",
"if",
"(",
"existing",
"!=",
"null",
")",
"return",
"new",
"XlsWorkbook",
"(",
"jxl",
".",
"Workbook",
... | Creates a new workbook object.
@param os The output stream for the workbook
@param existing An existing workbook to add to
@return The new workbook object
@throws IOException if the workbook cannot be written | [
"Creates",
"a",
"new",
"workbook",
"object",
"."
] | train | https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/documents/XlsWorkbook.java#L213-L228 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.deleteUser | protected void deleteUser(CmsRequestContext context, CmsUser user, CmsUser replacement)
throws CmsException, CmsSecurityException, CmsRoleViolationException {
if (OpenCms.getDefaultUsers().isDefaultUser(user.getName())) {
throw new CmsSecurityException(
org.opencms.security.Messages.get().container(
org.opencms.security.Messages.ERR_CANT_DELETE_DEFAULT_USER_1,
user.getName()));
}
if (context.getCurrentUser().equals(user)) {
throw new CmsSecurityException(Messages.get().container(Messages.ERR_USER_CANT_DELETE_ITSELF_USER_0));
}
CmsDbContext dbc = null;
try {
dbc = getDbContextForDeletePrincipal(context);
CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(user.getName()));
checkRoleForUserModification(dbc, user.getName(), role);
m_driverManager.deleteUser(
dbc,
dbc.getRequestContext().getCurrentProject(),
user.getName(),
null == replacement ? null : replacement.getName());
} catch (Exception e) {
CmsDbContext dbcForException = m_dbContextFactory.getDbContext(context);
dbcForException.report(null, Messages.get().container(Messages.ERR_DELETE_USER_1, user.getName()), e);
dbcForException.clear();
} finally {
if (null != dbc) {
dbc.clear();
}
}
} | java | protected void deleteUser(CmsRequestContext context, CmsUser user, CmsUser replacement)
throws CmsException, CmsSecurityException, CmsRoleViolationException {
if (OpenCms.getDefaultUsers().isDefaultUser(user.getName())) {
throw new CmsSecurityException(
org.opencms.security.Messages.get().container(
org.opencms.security.Messages.ERR_CANT_DELETE_DEFAULT_USER_1,
user.getName()));
}
if (context.getCurrentUser().equals(user)) {
throw new CmsSecurityException(Messages.get().container(Messages.ERR_USER_CANT_DELETE_ITSELF_USER_0));
}
CmsDbContext dbc = null;
try {
dbc = getDbContextForDeletePrincipal(context);
CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(user.getName()));
checkRoleForUserModification(dbc, user.getName(), role);
m_driverManager.deleteUser(
dbc,
dbc.getRequestContext().getCurrentProject(),
user.getName(),
null == replacement ? null : replacement.getName());
} catch (Exception e) {
CmsDbContext dbcForException = m_dbContextFactory.getDbContext(context);
dbcForException.report(null, Messages.get().container(Messages.ERR_DELETE_USER_1, user.getName()), e);
dbcForException.clear();
} finally {
if (null != dbc) {
dbc.clear();
}
}
} | [
"protected",
"void",
"deleteUser",
"(",
"CmsRequestContext",
"context",
",",
"CmsUser",
"user",
",",
"CmsUser",
"replacement",
")",
"throws",
"CmsException",
",",
"CmsSecurityException",
",",
"CmsRoleViolationException",
"{",
"if",
"(",
"OpenCms",
".",
"getDefaultUser... | Deletes a user, where all permissions and resources attributes of the user
were transfered to a replacement user, if given.<p>
@param context the current request context
@param user the user to be deleted
@param replacement the user to be transfered, can be <code>null</code>
@throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#ACCOUNT_MANAGER}
@throws CmsSecurityException in case the user is a default user
@throws CmsException if something goes wrong | [
"Deletes",
"a",
"user",
"where",
"all",
"permissions",
"and",
"resources",
"attributes",
"of",
"the",
"user",
"were",
"transfered",
"to",
"a",
"replacement",
"user",
"if",
"given",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L7192-L7224 |
otto-de/edison-hal | src/main/java/de/otto/edison/hal/paging/SkipLimitPaging.java | SkipLimitPaging.calcLastPageSkip | private int calcLastPageSkip(int total, int skip, int limit) {
if (skip > total - limit) {
return skip;
}
if (total % limit > 0) {
return total - total % limit;
}
return total - limit;
} | java | private int calcLastPageSkip(int total, int skip, int limit) {
if (skip > total - limit) {
return skip;
}
if (total % limit > 0) {
return total - total % limit;
}
return total - limit;
} | [
"private",
"int",
"calcLastPageSkip",
"(",
"int",
"total",
",",
"int",
"skip",
",",
"int",
"limit",
")",
"{",
"if",
"(",
"skip",
">",
"total",
"-",
"limit",
")",
"{",
"return",
"skip",
";",
"}",
"if",
"(",
"total",
"%",
"limit",
">",
"0",
")",
"{... | Calculate the number of items to skip for the last page.
@param total total number of items.
@param skip number of items to skip for the current page.
@param limit page size
@return skipped items | [
"Calculate",
"the",
"number",
"of",
"items",
"to",
"skip",
"for",
"the",
"last",
"page",
"."
] | train | https://github.com/otto-de/edison-hal/blob/1582d2b49d1f0d9103e03bf742f18afa9d166992/src/main/java/de/otto/edison/hal/paging/SkipLimitPaging.java#L278-L286 |
google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java | ThreadSafety.getInheritedAnnotation | public AnnotationInfo getInheritedAnnotation(Symbol sym, VisitorState state) {
return getAnnotation(sym, markerAnnotations, state);
} | java | public AnnotationInfo getInheritedAnnotation(Symbol sym, VisitorState state) {
return getAnnotation(sym, markerAnnotations, state);
} | [
"public",
"AnnotationInfo",
"getInheritedAnnotation",
"(",
"Symbol",
"sym",
",",
"VisitorState",
"state",
")",
"{",
"return",
"getAnnotation",
"(",
"sym",
",",
"markerAnnotations",
",",
"state",
")",
";",
"}"
] | Gets the possibly inherited marker annotation on the given symbol, and reverse-propagates
containerOf spec's from super-classes. | [
"Gets",
"the",
"possibly",
"inherited",
"marker",
"annotation",
"on",
"the",
"given",
"symbol",
"and",
"reverse",
"-",
"propagates",
"containerOf",
"spec",
"s",
"from",
"super",
"-",
"classes",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java#L796-L798 |
CenturyLinkCloud/clc-java-sdk | sdk/src/main/java/com/centurylink/cloud/sdk/server/services/dsl/GroupService.java | GroupService.createSubgroups | private void createSubgroups(GroupHierarchyConfig config, String groupId) {
config.getSubitems().forEach(cfg -> {
if (cfg instanceof GroupHierarchyConfig) {
GroupMetadata curGroup = findGroup((GroupHierarchyConfig) cfg, groupId);
String subGroupId;
if (curGroup != null) {
subGroupId = curGroup.getId();
} else {
subGroupId = create(converter.createGroupConfig((GroupHierarchyConfig) cfg, groupId))
.getResult()
.as(GroupByIdRef.class)
.getId();
}
createSubgroups((GroupHierarchyConfig) cfg, subGroupId);
} else if (cfg instanceof CreateServerConfig) {
((CreateServerConfig) cfg).group(Group.refById(groupId));
} else {
((CompositeServerConfig) cfg).getServer().group(Group.refById(groupId));
}
});
} | java | private void createSubgroups(GroupHierarchyConfig config, String groupId) {
config.getSubitems().forEach(cfg -> {
if (cfg instanceof GroupHierarchyConfig) {
GroupMetadata curGroup = findGroup((GroupHierarchyConfig) cfg, groupId);
String subGroupId;
if (curGroup != null) {
subGroupId = curGroup.getId();
} else {
subGroupId = create(converter.createGroupConfig((GroupHierarchyConfig) cfg, groupId))
.getResult()
.as(GroupByIdRef.class)
.getId();
}
createSubgroups((GroupHierarchyConfig) cfg, subGroupId);
} else if (cfg instanceof CreateServerConfig) {
((CreateServerConfig) cfg).group(Group.refById(groupId));
} else {
((CompositeServerConfig) cfg).getServer().group(Group.refById(groupId));
}
});
} | [
"private",
"void",
"createSubgroups",
"(",
"GroupHierarchyConfig",
"config",
",",
"String",
"groupId",
")",
"{",
"config",
".",
"getSubitems",
"(",
")",
".",
"forEach",
"(",
"cfg",
"->",
"{",
"if",
"(",
"cfg",
"instanceof",
"GroupHierarchyConfig",
")",
"{",
... | Create sub groups in group with {@code groupId}
@param config group hierarchy config
@param groupId group id | [
"Create",
"sub",
"groups",
"in",
"group",
"with",
"{"
] | train | https://github.com/CenturyLinkCloud/clc-java-sdk/blob/c026322f077dea71b1acf9f2d665253d79d9bf85/sdk/src/main/java/com/centurylink/cloud/sdk/server/services/dsl/GroupService.java#L265-L285 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java | AnnotationUtility.extractAsBoolean | public static <E extends ModelEntity<?>> boolean extractAsBoolean(E item, ModelAnnotation annotation, AnnotationAttributeType attribute) {
final Elements elementUtils=BaseProcessor.elementUtils;
final One<Boolean> result = new One<Boolean>(false);
extractAttributeValue(elementUtils, item.getElement(), annotation.getName(), attribute, new OnAttributeFoundListener() {
@Override
public void onFound(String value) {
result.value0 = Boolean.valueOf(value);
}
});
return result.value0;
} | java | public static <E extends ModelEntity<?>> boolean extractAsBoolean(E item, ModelAnnotation annotation, AnnotationAttributeType attribute) {
final Elements elementUtils=BaseProcessor.elementUtils;
final One<Boolean> result = new One<Boolean>(false);
extractAttributeValue(elementUtils, item.getElement(), annotation.getName(), attribute, new OnAttributeFoundListener() {
@Override
public void onFound(String value) {
result.value0 = Boolean.valueOf(value);
}
});
return result.value0;
} | [
"public",
"static",
"<",
"E",
"extends",
"ModelEntity",
"<",
"?",
">",
">",
"boolean",
"extractAsBoolean",
"(",
"E",
"item",
",",
"ModelAnnotation",
"annotation",
",",
"AnnotationAttributeType",
"attribute",
")",
"{",
"final",
"Elements",
"elementUtils",
"=",
"B... | Estract from an annotation of a method the attribute value specified.
@param <E> the element type
@param item entity to analyze
@param annotation annotation to analyze
@param attribute the attribute
@return true, if successful | [
"Estract",
"from",
"an",
"annotation",
"of",
"a",
"method",
"the",
"attribute",
"value",
"specified",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java#L580-L593 |
Shusshu/Android-RecurrencePicker | library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java | Utils.isEmailableFrom | public static boolean isEmailableFrom(String email, String syncAccountName) {
return Utils.isValidEmail(email) && !email.equals(syncAccountName);
} | java | public static boolean isEmailableFrom(String email, String syncAccountName) {
return Utils.isValidEmail(email) && !email.equals(syncAccountName);
} | [
"public",
"static",
"boolean",
"isEmailableFrom",
"(",
"String",
"email",
",",
"String",
"syncAccountName",
")",
"{",
"return",
"Utils",
".",
"isValidEmail",
"(",
"email",
")",
"&&",
"!",
"email",
".",
"equals",
"(",
"syncAccountName",
")",
";",
"}"
] | Returns true if:
(1) the email is not a resource like a conference room or another calendar.
Catch most of these by filtering out suffix calendar.google.com.
(2) the email is not equal to the sync account to prevent mailing himself. | [
"Returns",
"true",
"if",
":",
"(",
"1",
")",
"the",
"email",
"is",
"not",
"a",
"resource",
"like",
"a",
"conference",
"room",
"or",
"another",
"calendar",
".",
"Catch",
"most",
"of",
"these",
"by",
"filtering",
"out",
"suffix",
"calendar",
".",
"google",... | train | https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java#L876-L878 |
j256/ormlite-core | src/main/java/com/j256/ormlite/stmt/QueryBuilder.java | QueryBuilder.addJoinInfo | private void addJoinInfo(JoinType type, String localColumnName, String joinedColumnName,
QueryBuilder<?, ?> joinedQueryBuilder, JoinWhereOperation operation) throws SQLException {
JoinInfo joinInfo = new JoinInfo(type, joinedQueryBuilder, operation);
if (localColumnName == null) {
matchJoinedFields(joinInfo, joinedQueryBuilder);
} else {
matchJoinedFieldsByName(joinInfo, localColumnName, joinedColumnName, joinedQueryBuilder);
}
if (joinList == null) {
joinList = new ArrayList<JoinInfo>();
}
joinList.add(joinInfo);
} | java | private void addJoinInfo(JoinType type, String localColumnName, String joinedColumnName,
QueryBuilder<?, ?> joinedQueryBuilder, JoinWhereOperation operation) throws SQLException {
JoinInfo joinInfo = new JoinInfo(type, joinedQueryBuilder, operation);
if (localColumnName == null) {
matchJoinedFields(joinInfo, joinedQueryBuilder);
} else {
matchJoinedFieldsByName(joinInfo, localColumnName, joinedColumnName, joinedQueryBuilder);
}
if (joinList == null) {
joinList = new ArrayList<JoinInfo>();
}
joinList.add(joinInfo);
} | [
"private",
"void",
"addJoinInfo",
"(",
"JoinType",
"type",
",",
"String",
"localColumnName",
",",
"String",
"joinedColumnName",
",",
"QueryBuilder",
"<",
"?",
",",
"?",
">",
"joinedQueryBuilder",
",",
"JoinWhereOperation",
"operation",
")",
"throws",
"SQLException",... | Add join info to the query. This can be called multiple times to join with more than one table. | [
"Add",
"join",
"info",
"to",
"the",
"query",
".",
"This",
"can",
"be",
"called",
"multiple",
"times",
"to",
"join",
"with",
"more",
"than",
"one",
"table",
"."
] | train | https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/stmt/QueryBuilder.java#L578-L590 |
jMotif/GI | src/main/java/net/seninp/gi/rulepruner/RulePrunerFactory.java | RulePrunerFactory.computeGrammarSize | public static Integer computeGrammarSize(GrammarRules rules, Integer paaSize) {
// The final grammar's size in BYTES
//
int res = 0;
// The final size is the sum of the sizes of all rules
//
for (GrammarRuleRecord r : rules) {
String ruleStr = r.getRuleString();
String[] tokens = ruleStr.split("\\s+");
int ruleSize = computeRuleSize(paaSize, tokens);
res += ruleSize;
}
return res;
} | java | public static Integer computeGrammarSize(GrammarRules rules, Integer paaSize) {
// The final grammar's size in BYTES
//
int res = 0;
// The final size is the sum of the sizes of all rules
//
for (GrammarRuleRecord r : rules) {
String ruleStr = r.getRuleString();
String[] tokens = ruleStr.split("\\s+");
int ruleSize = computeRuleSize(paaSize, tokens);
res += ruleSize;
}
return res;
} | [
"public",
"static",
"Integer",
"computeGrammarSize",
"(",
"GrammarRules",
"rules",
",",
"Integer",
"paaSize",
")",
"{",
"// The final grammar's size in BYTES",
"//",
"int",
"res",
"=",
"0",
";",
"// The final size is the sum of the sizes of all rules",
"//",
"for",
"(",
... | Computes the size of a normal, i.e. unpruned grammar.
@param rules the grammar rules.
@param paaSize the SAX transform word size.
@return the grammar size, in BYTES. | [
"Computes",
"the",
"size",
"of",
"a",
"normal",
"i",
".",
"e",
".",
"unpruned",
"grammar",
"."
] | train | https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/rulepruner/RulePrunerFactory.java#L26-L42 |
wcm-io/wcm-io-handler | url/src/main/java/io/wcm/handler/url/impl/Externalizer.java | Externalizer.externalizeUrlWithoutMapping | public static @NotNull String externalizeUrlWithoutMapping(@NotNull String url, @Nullable SlingHttpServletRequest request) {
// apply externalization only path part
String path = url;
// split off query string or fragment that may be appended to the URL
String urlRemainder = null;
int urlRemainderPos = StringUtils.indexOfAny(path, '?', '#');
if (urlRemainderPos >= 0) {
urlRemainder = path.substring(urlRemainderPos);
path = path.substring(0, urlRemainderPos);
}
// apply namespace mangling (e.g. replace jcr: with _jcr_)
path = mangleNamespaces(path);
// add webapp context path
if (request != null) {
path = StringUtils.defaultString(request.getContextPath()) + path; //NOPMD
}
// url-encode path
path = Escape.urlEncode(path);
path = StringUtils.replace(path, "+", "%20");
// replace %2F back to / for better readability
path = StringUtils.replace(path, "%2F", "/");
// build full URL again
return path + (urlRemainder != null ? urlRemainder : "");
} | java | public static @NotNull String externalizeUrlWithoutMapping(@NotNull String url, @Nullable SlingHttpServletRequest request) {
// apply externalization only path part
String path = url;
// split off query string or fragment that may be appended to the URL
String urlRemainder = null;
int urlRemainderPos = StringUtils.indexOfAny(path, '?', '#');
if (urlRemainderPos >= 0) {
urlRemainder = path.substring(urlRemainderPos);
path = path.substring(0, urlRemainderPos);
}
// apply namespace mangling (e.g. replace jcr: with _jcr_)
path = mangleNamespaces(path);
// add webapp context path
if (request != null) {
path = StringUtils.defaultString(request.getContextPath()) + path; //NOPMD
}
// url-encode path
path = Escape.urlEncode(path);
path = StringUtils.replace(path, "+", "%20");
// replace %2F back to / for better readability
path = StringUtils.replace(path, "%2F", "/");
// build full URL again
return path + (urlRemainder != null ? urlRemainder : "");
} | [
"public",
"static",
"@",
"NotNull",
"String",
"externalizeUrlWithoutMapping",
"(",
"@",
"NotNull",
"String",
"url",
",",
"@",
"Nullable",
"SlingHttpServletRequest",
"request",
")",
"{",
"// apply externalization only path part",
"String",
"path",
"=",
"url",
";",
"// ... | Externalizes an URL without applying Sling Mapping. Instead the servlet context path is added and sling namespace
mangling is applied manually.
Hostname and scheme are not added because they are added by the link handler depending on site URL configuration
and secure/non-secure mode. URLs that are already externalized remain untouched.
@param url Unexternalized URL (without scheme or hostname)
@param request Request
@return Exernalized URL without scheme or hostname, the path is URL-encoded if it contains special chars. | [
"Externalizes",
"an",
"URL",
"without",
"applying",
"Sling",
"Mapping",
".",
"Instead",
"the",
"servlet",
"context",
"path",
"is",
"added",
"and",
"sling",
"namespace",
"mangling",
"is",
"applied",
"manually",
".",
"Hostname",
"and",
"scheme",
"are",
"not",
"a... | train | https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/url/src/main/java/io/wcm/handler/url/impl/Externalizer.java#L111-L140 |
ag-gipp/MathMLTools | mathml-core/src/main/java/com/formulasearchengine/mathmltools/querygenerator/NtcirTopicReader.java | NtcirTopicReader.extractPatterns | public final List<NtcirPattern> extractPatterns() throws XPathExpressionException {
final XPath xpath = XMLHelper.namespaceAwareXpath("t", NS_NII);
final XPathExpression xNum = xpath.compile("./t:num");
final XPathExpression xFormula = xpath.compile("./t:query/t:formula");
final NonWhitespaceNodeList topicList = new NonWhitespaceNodeList(
topics.getElementsByTagNameNS(NS_NII, "topic"));
for (final Node node : topicList) {
final String num = xNum.evaluate(node);
final NonWhitespaceNodeList formulae = new NonWhitespaceNodeList((NodeList)
xFormula.evaluate(node, XPathConstants.NODESET));
for (final Node formula : formulae) {
final String id = formula.getAttributes().getNamedItem("id").getTextContent();
final Node mathMLNode = NonWhitespaceNodeList.getFirstChild(formula);
queryGenerator.setMainElement(NonWhitespaceNodeList.getFirstChild(mathMLNode));
patterns.add(new NtcirPattern(num, id, queryGenerator.toString(), mathMLNode));
}
}
return patterns;
} | java | public final List<NtcirPattern> extractPatterns() throws XPathExpressionException {
final XPath xpath = XMLHelper.namespaceAwareXpath("t", NS_NII);
final XPathExpression xNum = xpath.compile("./t:num");
final XPathExpression xFormula = xpath.compile("./t:query/t:formula");
final NonWhitespaceNodeList topicList = new NonWhitespaceNodeList(
topics.getElementsByTagNameNS(NS_NII, "topic"));
for (final Node node : topicList) {
final String num = xNum.evaluate(node);
final NonWhitespaceNodeList formulae = new NonWhitespaceNodeList((NodeList)
xFormula.evaluate(node, XPathConstants.NODESET));
for (final Node formula : formulae) {
final String id = formula.getAttributes().getNamedItem("id").getTextContent();
final Node mathMLNode = NonWhitespaceNodeList.getFirstChild(formula);
queryGenerator.setMainElement(NonWhitespaceNodeList.getFirstChild(mathMLNode));
patterns.add(new NtcirPattern(num, id, queryGenerator.toString(), mathMLNode));
}
}
return patterns;
} | [
"public",
"final",
"List",
"<",
"NtcirPattern",
">",
"extractPatterns",
"(",
")",
"throws",
"XPathExpressionException",
"{",
"final",
"XPath",
"xpath",
"=",
"XMLHelper",
".",
"namespaceAwareXpath",
"(",
"\"t\"",
",",
"NS_NII",
")",
";",
"final",
"XPathExpression",... | Splits the given NTCIR query file into individual queries, converts each query into an XQuery using
QVarXQueryGenerator, and returns the result as a list of NtcirPatterns for each individual query.
@return List of NtcirPatterns for each query
@throws XPathExpressionException Thrown if xpaths fail to compile or fail to evaluate
+ | [
"Splits",
"the",
"given",
"NTCIR",
"query",
"file",
"into",
"individual",
"queries",
"converts",
"each",
"query",
"into",
"an",
"XQuery",
"using",
"QVarXQueryGenerator",
"and",
"returns",
"the",
"result",
"as",
"a",
"list",
"of",
"NtcirPatterns",
"for",
"each",
... | train | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-core/src/main/java/com/formulasearchengine/mathmltools/querygenerator/NtcirTopicReader.java#L86-L104 |
ModeShape/modeshape | modeshape-common/src/main/java/org/modeshape/common/util/StringUtil.java | StringUtil.setLength | public static String setLength( String original,
int length,
char padChar ) {
return justifyLeft(original, length, padChar, false);
} | java | public static String setLength( String original,
int length,
char padChar ) {
return justifyLeft(original, length, padChar, false);
} | [
"public",
"static",
"String",
"setLength",
"(",
"String",
"original",
",",
"int",
"length",
",",
"char",
"padChar",
")",
"{",
"return",
"justifyLeft",
"(",
"original",
",",
"length",
",",
"padChar",
",",
"false",
")",
";",
"}"
] | Set the length of the string, padding with the supplied character if the supplied string is shorter than desired, or
truncating the string if it is longer than desired. Unlike {@link #justifyLeft(String, int, char)}, this method does not
remove leading and trailing whitespace.
@param original the string for which the length is to be set; may not be null
@param length the desired length; must be positive
@param padChar the character to use for padding, if the supplied string is not long enough
@return the string of the desired length
@see #justifyLeft(String, int, char) | [
"Set",
"the",
"length",
"of",
"the",
"string",
"padding",
"with",
"the",
"supplied",
"character",
"if",
"the",
"supplied",
"string",
"is",
"shorter",
"than",
"desired",
"or",
"truncating",
"the",
"string",
"if",
"it",
"is",
"longer",
"than",
"desired",
".",
... | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/StringUtil.java#L227-L231 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/Holiday.java | Holiday.isBetween | @Override
public boolean isBetween(Date start, Date end) {
return rule.isBetween(start, end);
} | java | @Override
public boolean isBetween(Date start, Date end) {
return rule.isBetween(start, end);
} | [
"@",
"Override",
"public",
"boolean",
"isBetween",
"(",
"Date",
"start",
",",
"Date",
"end",
")",
"{",
"return",
"rule",
".",
"isBetween",
"(",
"start",
",",
"end",
")",
";",
"}"
] | Check whether this holiday occurs at least once between the two
dates given.
@hide draft / provisional / internal are hidden on Android | [
"Check",
"whether",
"this",
"holiday",
"occurs",
"at",
"least",
"once",
"between",
"the",
"two",
"dates",
"given",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/Holiday.java#L117-L120 |
ocpsoft/prettytime | core/src/main/java/org/ocpsoft/prettytime/PrettyTime.java | PrettyTime.registerUnit | public PrettyTime registerUnit(final TimeUnit unit, TimeFormat format)
{
if (unit == null)
throw new IllegalArgumentException("Unit to register must not be null.");
if (format == null)
throw new IllegalArgumentException("Format to register must not be null.");
cachedUnits = null;
units.put(unit, format);
if (unit instanceof LocaleAware)
((LocaleAware<?>) unit).setLocale(locale);
if (format instanceof LocaleAware)
((LocaleAware<?>) format).setLocale(locale);
return this;
} | java | public PrettyTime registerUnit(final TimeUnit unit, TimeFormat format)
{
if (unit == null)
throw new IllegalArgumentException("Unit to register must not be null.");
if (format == null)
throw new IllegalArgumentException("Format to register must not be null.");
cachedUnits = null;
units.put(unit, format);
if (unit instanceof LocaleAware)
((LocaleAware<?>) unit).setLocale(locale);
if (format instanceof LocaleAware)
((LocaleAware<?>) format).setLocale(locale);
return this;
} | [
"public",
"PrettyTime",
"registerUnit",
"(",
"final",
"TimeUnit",
"unit",
",",
"TimeFormat",
"format",
")",
"{",
"if",
"(",
"unit",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unit to register must not be null.\"",
")",
";",
"if",
"(",
... | Register the given {@link TimeUnit} and corresponding {@link TimeFormat} instance to be used in calculations. If
an entry already exists for the given {@link TimeUnit}, its {@link TimeFormat} will be overwritten with the given
{@link TimeFormat}. ({@link TimeUnit} and {@link TimeFormat} must not be <code>null</code>.) | [
"Register",
"the",
"given",
"{"
] | train | https://github.com/ocpsoft/prettytime/blob/8a742bd1d8eaacc2a36865d144a43ea0211e25b7/core/src/main/java/org/ocpsoft/prettytime/PrettyTime.java#L652-L667 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/RepositoryException.java | RepositoryException.toFetchException | public final FetchException toFetchException(final String message) {
Throwable cause;
if (this instanceof FetchException) {
cause = this;
} else {
cause = getCause();
}
if (cause == null) {
cause = this;
} else if (cause instanceof FetchException && message == null) {
return (FetchException) cause;
}
String causeMessage = cause.getMessage();
if (causeMessage == null) {
causeMessage = message;
} else if (message != null) {
causeMessage = message + " : " + causeMessage;
}
return makeFetchException(causeMessage, cause);
} | java | public final FetchException toFetchException(final String message) {
Throwable cause;
if (this instanceof FetchException) {
cause = this;
} else {
cause = getCause();
}
if (cause == null) {
cause = this;
} else if (cause instanceof FetchException && message == null) {
return (FetchException) cause;
}
String causeMessage = cause.getMessage();
if (causeMessage == null) {
causeMessage = message;
} else if (message != null) {
causeMessage = message + " : " + causeMessage;
}
return makeFetchException(causeMessage, cause);
} | [
"public",
"final",
"FetchException",
"toFetchException",
"(",
"final",
"String",
"message",
")",
"{",
"Throwable",
"cause",
";",
"if",
"(",
"this",
"instanceof",
"FetchException",
")",
"{",
"cause",
"=",
"this",
";",
"}",
"else",
"{",
"cause",
"=",
"getCause... | Converts RepositoryException into an appropriate FetchException, prepending
the specified message. If message is null, original exception message is
preserved.
@param message message to prepend, which may be null | [
"Converts",
"RepositoryException",
"into",
"an",
"appropriate",
"FetchException",
"prepending",
"the",
"specified",
"message",
".",
"If",
"message",
"is",
"null",
"original",
"exception",
"message",
"is",
"preserved",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/RepositoryException.java#L177-L199 |
saxsys/SynchronizeFX | kryo-serializer/src/main/java/de/saxsys/synchronizefx/kryo/KryoInitializer.java | KryoInitializer.registerSerializableClass | <T> void registerSerializableClass(final Class<T> clazz, final Serializer<T> serializer) {
synchronized (customSerializers) {
customSerializers.add(new CustomSerializers<>(clazz, serializer));
}
} | java | <T> void registerSerializableClass(final Class<T> clazz, final Serializer<T> serializer) {
synchronized (customSerializers) {
customSerializers.add(new CustomSerializers<>(clazz, serializer));
}
} | [
"<",
"T",
">",
"void",
"registerSerializableClass",
"(",
"final",
"Class",
"<",
"T",
">",
"clazz",
",",
"final",
"Serializer",
"<",
"T",
">",
"serializer",
")",
"{",
"synchronized",
"(",
"customSerializers",
")",
"{",
"customSerializers",
".",
"add",
"(",
... | See {@link KryoSerializer#registerSerializableClass(Class, Serializer)}.
@param clazz see {@link KryoSerializer#registerSerializableClass(Class, Serializer)}.
@param serializer see {@link KryoSerializer#registerSerializableClass(Class, Serializer)}.
@param <T> see {@link KryoSerializer#registerSerializableClass(Class, Serializer)}.
@see KryoSerializer#registerSerializableClass(Class, Serializer) | [
"See",
"{",
"@link",
"KryoSerializer#registerSerializableClass",
"(",
"Class",
"Serializer",
")",
"}",
"."
] | train | https://github.com/saxsys/SynchronizeFX/blob/f3683020e4749110b38514eb5bc73a247998b579/kryo-serializer/src/main/java/de/saxsys/synchronizefx/kryo/KryoInitializer.java#L81-L85 |
exoplatform/jcr | exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/UserProfileHandlerImpl.java | UserProfileHandlerImpl.readProfile | private UserProfile readProfile(String userName, Node profileNode) throws RepositoryException
{
UserProfile profile = createUserProfileInstance(userName);
PropertyIterator attributes = profileNode.getProperties();
while (attributes.hasNext())
{
Property prop = attributes.nextProperty();
if (prop.getName().startsWith(ATTRIBUTE_PREFIX))
{
String name = prop.getName().substring(ATTRIBUTE_PREFIX.length());
String value = prop.getString();
profile.setAttribute(name, value);
}
}
return profile;
} | java | private UserProfile readProfile(String userName, Node profileNode) throws RepositoryException
{
UserProfile profile = createUserProfileInstance(userName);
PropertyIterator attributes = profileNode.getProperties();
while (attributes.hasNext())
{
Property prop = attributes.nextProperty();
if (prop.getName().startsWith(ATTRIBUTE_PREFIX))
{
String name = prop.getName().substring(ATTRIBUTE_PREFIX.length());
String value = prop.getString();
profile.setAttribute(name, value);
}
}
return profile;
} | [
"private",
"UserProfile",
"readProfile",
"(",
"String",
"userName",
",",
"Node",
"profileNode",
")",
"throws",
"RepositoryException",
"{",
"UserProfile",
"profile",
"=",
"createUserProfileInstance",
"(",
"userName",
")",
";",
"PropertyIterator",
"attributes",
"=",
"pr... | Read user profile from storage.
@param profileNode
the node which stores profile attributes as properties with
prefix {@link #ATTRIBUTE_PREFIX}
@return {@link UserProfile} instance
@throws RepositoryException
if unexpected exception is occurred during reading | [
"Read",
"user",
"profile",
"from",
"storage",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/UserProfileHandlerImpl.java#L334-L352 |
baasbox/Android-SDK | library/src/main/java/com/baasbox/android/BaasDocument.java | BaasDocument.fetchSync | public static BaasResult<BaasDocument> fetchSync(String collection,String id){
return fetchSync(collection,id,false);
} | java | public static BaasResult<BaasDocument> fetchSync(String collection,String id){
return fetchSync(collection,id,false);
} | [
"public",
"static",
"BaasResult",
"<",
"BaasDocument",
">",
"fetchSync",
"(",
"String",
"collection",
",",
"String",
"id",
")",
"{",
"return",
"fetchSync",
"(",
"collection",
",",
"id",
",",
"false",
")",
";",
"}"
] | Synchronously fetches a document from the server
@param collection the collection to retrieve the document from. Not <code>null</code>
@param id the id of the document to retrieve. Not <code>null</code>
@return the result of the request | [
"Synchronously",
"fetches",
"a",
"document",
"from",
"the",
"server"
] | train | https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasDocument.java#L417-L419 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Trie.java | Trie.getCodePointOffset | protected final int getCodePointOffset(int ch)
{
// if ((ch >> 16) == 0) slower
if (ch < 0) {
return -1;
} else if (ch < UTF16.LEAD_SURROGATE_MIN_VALUE) {
// fastpath for the part of the BMP below surrogates (D800) where getRawOffset() works
return getRawOffset(0, (char)ch);
} else if (ch < UTF16.SUPPLEMENTARY_MIN_VALUE) {
// BMP codepoint
return getBMPOffset((char)ch);
} else if (ch <= UCharacter.MAX_VALUE) {
// look at the construction of supplementary characters
// trail forms the ends of it.
return getSurrogateOffset(UTF16.getLeadSurrogate(ch),
(char)(ch & SURROGATE_MASK_));
} else {
// return -1 if there is an error, in this case we return
return -1;
}
} | java | protected final int getCodePointOffset(int ch)
{
// if ((ch >> 16) == 0) slower
if (ch < 0) {
return -1;
} else if (ch < UTF16.LEAD_SURROGATE_MIN_VALUE) {
// fastpath for the part of the BMP below surrogates (D800) where getRawOffset() works
return getRawOffset(0, (char)ch);
} else if (ch < UTF16.SUPPLEMENTARY_MIN_VALUE) {
// BMP codepoint
return getBMPOffset((char)ch);
} else if (ch <= UCharacter.MAX_VALUE) {
// look at the construction of supplementary characters
// trail forms the ends of it.
return getSurrogateOffset(UTF16.getLeadSurrogate(ch),
(char)(ch & SURROGATE_MASK_));
} else {
// return -1 if there is an error, in this case we return
return -1;
}
} | [
"protected",
"final",
"int",
"getCodePointOffset",
"(",
"int",
"ch",
")",
"{",
"// if ((ch >> 16) == 0) slower",
"if",
"(",
"ch",
"<",
"0",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"ch",
"<",
"UTF16",
".",
"LEAD_SURROGATE_MIN_VALUE",
")",... | Internal trie getter from a code point.
Could be faster(?) but longer with
if((c32)<=0xd7ff) { (result)=_TRIE_GET_RAW(trie, data, 0, c32); }
Gets the offset to data which the codepoint points to
@param ch codepoint
@return offset to data | [
"Internal",
"trie",
"getter",
"from",
"a",
"code",
"point",
".",
"Could",
"be",
"faster",
"(",
"?",
")",
"but",
"longer",
"with",
"if",
"((",
"c32",
")",
"<",
"=",
"0xd7ff",
")",
"{",
"(",
"result",
")",
"=",
"_TRIE_GET_RAW",
"(",
"trie",
"data",
"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Trie.java#L340-L360 |
actorapp/actor-platform | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java | Messenger.bindUpload | @NotNull
@ObjectiveCName("bindUploadWithRid:withCallback:")
public UploadFileVM bindUpload(long rid, UploadFileVMCallback callback) {
return new UploadFileVM(rid, callback, modules);
} | java | @NotNull
@ObjectiveCName("bindUploadWithRid:withCallback:")
public UploadFileVM bindUpload(long rid, UploadFileVMCallback callback) {
return new UploadFileVM(rid, callback, modules);
} | [
"@",
"NotNull",
"@",
"ObjectiveCName",
"(",
"\"bindUploadWithRid:withCallback:\"",
")",
"public",
"UploadFileVM",
"bindUpload",
"(",
"long",
"rid",
",",
"UploadFileVMCallback",
"callback",
")",
"{",
"return",
"new",
"UploadFileVM",
"(",
"rid",
",",
"callback",
",",
... | Bind Uploading File View Model
@param rid randomId of uploading file
@param callback View Model file state callback
@return Upload File View Model | [
"Bind",
"Uploading",
"File",
"View",
"Model"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java#L1917-L1921 |
iipc/webarchive-commons | src/main/java/org/archive/util/FileUtils.java | FileUtils.readFullyToFile | public static long readFullyToFile(InputStream is, File toFile)
throws IOException {
OutputStream os = org.apache.commons.io.FileUtils.openOutputStream(toFile);
try {
return IOUtils.copyLarge(is, os);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
}
} | java | public static long readFullyToFile(InputStream is, File toFile)
throws IOException {
OutputStream os = org.apache.commons.io.FileUtils.openOutputStream(toFile);
try {
return IOUtils.copyLarge(is, os);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
}
} | [
"public",
"static",
"long",
"readFullyToFile",
"(",
"InputStream",
"is",
",",
"File",
"toFile",
")",
"throws",
"IOException",
"{",
"OutputStream",
"os",
"=",
"org",
".",
"apache",
".",
"commons",
".",
"io",
".",
"FileUtils",
".",
"openOutputStream",
"(",
"to... | Read the entire stream to EOF into the passed file.
Closes <code>is</code> when done or if an exception.
@param is Stream to read.
@param toFile File to write to.
@throws IOException | [
"Read",
"the",
"entire",
"stream",
"to",
"EOF",
"into",
"the",
"passed",
"file",
".",
"Closes",
"<code",
">",
"is<",
"/",
"code",
">",
"when",
"done",
"or",
"if",
"an",
"exception",
"."
] | train | https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/FileUtils.java#L612-L621 |
infinispan/infinispan | core/src/main/java/org/infinispan/interceptors/impl/InvocationContextInterceptor.java | InvocationContextInterceptor.stoppingAndNotAllowed | private boolean stoppingAndNotAllowed(ComponentStatus status, InvocationContext ctx) throws Exception {
return status.isStopping() && (!ctx.isInTxScope() || !isOngoingTransaction(ctx));
} | java | private boolean stoppingAndNotAllowed(ComponentStatus status, InvocationContext ctx) throws Exception {
return status.isStopping() && (!ctx.isInTxScope() || !isOngoingTransaction(ctx));
} | [
"private",
"boolean",
"stoppingAndNotAllowed",
"(",
"ComponentStatus",
"status",
",",
"InvocationContext",
"ctx",
")",
"throws",
"Exception",
"{",
"return",
"status",
".",
"isStopping",
"(",
")",
"&&",
"(",
"!",
"ctx",
".",
"isInTxScope",
"(",
")",
"||",
"!",
... | If the cache is STOPPING, non-transaction invocations, or transactional invocations for transaction others than
the ongoing ones, are no allowed. This method returns true if under this circumstances meet. Otherwise, it returns
false. | [
"If",
"the",
"cache",
"is",
"STOPPING",
"non",
"-",
"transaction",
"invocations",
"or",
"transactional",
"invocations",
"for",
"transaction",
"others",
"than",
"the",
"ongoing",
"ones",
"are",
"no",
"allowed",
".",
"This",
"method",
"returns",
"true",
"if",
"u... | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/interceptors/impl/InvocationContextInterceptor.java#L164-L166 |
huangp/entityunit | src/main/java/com/github/huangp/entityunit/entity/EntityCleaner.java | EntityCleaner.getAssociationTables | private static Iterable<String> getAssociationTables(EntityClass entityClass) {
Iterable<Settable> association = filter(entityClass.getElements(),
and(or(has(ManyToMany.class), has(ElementCollection.class)), has(JoinTable.class)));
return transform(association, new Function<Settable, String>() {
@Override
public String apply(Settable input) {
JoinTable annotation = input.getAnnotation(JoinTable.class);
return annotation.name();
}
});
} | java | private static Iterable<String> getAssociationTables(EntityClass entityClass) {
Iterable<Settable> association = filter(entityClass.getElements(),
and(or(has(ManyToMany.class), has(ElementCollection.class)), has(JoinTable.class)));
return transform(association, new Function<Settable, String>() {
@Override
public String apply(Settable input) {
JoinTable annotation = input.getAnnotation(JoinTable.class);
return annotation.name();
}
});
} | [
"private",
"static",
"Iterable",
"<",
"String",
">",
"getAssociationTables",
"(",
"EntityClass",
"entityClass",
")",
"{",
"Iterable",
"<",
"Settable",
">",
"association",
"=",
"filter",
"(",
"entityClass",
".",
"getElements",
"(",
")",
",",
"and",
"(",
"or",
... | This will find all ManyToMany and ElementCollection annotated tables. | [
"This",
"will",
"find",
"all",
"ManyToMany",
"and",
"ElementCollection",
"annotated",
"tables",
"."
] | train | https://github.com/huangp/entityunit/blob/1a09b530149d707dbff7ff46f5428d9db709a4b4/src/main/java/com/github/huangp/entityunit/entity/EntityCleaner.java#L140-L150 |
diffplug/JMatIO | src/main/java/ca/mjdsystems/jmatio/io/MatFileIncrementalWriter.java | MatFileIncrementalWriter.writeFlags | private void writeFlags(DataOutputStream os, MLArray array) throws IOException
{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
DataOutputStream bufferDOS = new DataOutputStream(buffer);
bufferDOS.writeInt( array.getFlags() );
if ( array.isSparse() )
{
bufferDOS.writeInt( ((MLSparse)array).getMaxNZ() );
}
else
{
bufferDOS.writeInt( 0 );
}
OSArrayTag tag = new OSArrayTag(MatDataTypes.miUINT32, buffer.toByteArray() );
tag.writeTo( os );
} | java | private void writeFlags(DataOutputStream os, MLArray array) throws IOException
{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
DataOutputStream bufferDOS = new DataOutputStream(buffer);
bufferDOS.writeInt( array.getFlags() );
if ( array.isSparse() )
{
bufferDOS.writeInt( ((MLSparse)array).getMaxNZ() );
}
else
{
bufferDOS.writeInt( 0 );
}
OSArrayTag tag = new OSArrayTag(MatDataTypes.miUINT32, buffer.toByteArray() );
tag.writeTo( os );
} | [
"private",
"void",
"writeFlags",
"(",
"DataOutputStream",
"os",
",",
"MLArray",
"array",
")",
"throws",
"IOException",
"{",
"ByteArrayOutputStream",
"buffer",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"DataOutputStream",
"bufferDOS",
"=",
"new",
"DataOutpu... | Writes MATRIX flags into <code>OutputStream</code>.
@param os - <code>OutputStream</code>
@param array - a <code>MLArray</code>
@throws IOException | [
"Writes",
"MATRIX",
"flags",
"into",
"<code",
">",
"OutputStream<",
"/",
"code",
">",
"."
] | train | https://github.com/diffplug/JMatIO/blob/dab8a54fa21a8faeaa81537cdc45323c5c4e6ca6/src/main/java/ca/mjdsystems/jmatio/io/MatFileIncrementalWriter.java#L450-L468 |
threerings/nenya | core/src/main/java/com/threerings/miso/client/MisoScenePanel.java | MisoScenePanel.setShowFlags | public void setShowFlags (int flags, boolean on)
{
int oldshow = _showFlags;
if (on) {
_showFlags |= flags;
} else {
_showFlags &= ~flags;
}
if (oldshow != _showFlags) {
showFlagsDidChange(oldshow);
}
} | java | public void setShowFlags (int flags, boolean on)
{
int oldshow = _showFlags;
if (on) {
_showFlags |= flags;
} else {
_showFlags &= ~flags;
}
if (oldshow != _showFlags) {
showFlagsDidChange(oldshow);
}
} | [
"public",
"void",
"setShowFlags",
"(",
"int",
"flags",
",",
"boolean",
"on",
")",
"{",
"int",
"oldshow",
"=",
"_showFlags",
";",
"if",
"(",
"on",
")",
"{",
"_showFlags",
"|=",
"flags",
";",
"}",
"else",
"{",
"_showFlags",
"&=",
"~",
"flags",
";",
"}"... | Set whether or not to highlight object tooltips (and potentially other scene entities). | [
"Set",
"whether",
"or",
"not",
"to",
"highlight",
"object",
"tooltips",
"(",
"and",
"potentially",
"other",
"scene",
"entities",
")",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L201-L214 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NumberFormat.java | NumberFormat.getInstance | public static NumberFormat getInstance(Locale inLocale, int style) {
return getInstance(ULocale.forLocale(inLocale), style);
} | java | public static NumberFormat getInstance(Locale inLocale, int style) {
return getInstance(ULocale.forLocale(inLocale), style);
} | [
"public",
"static",
"NumberFormat",
"getInstance",
"(",
"Locale",
"inLocale",
",",
"int",
"style",
")",
"{",
"return",
"getInstance",
"(",
"ULocale",
".",
"forLocale",
"(",
"inLocale",
")",
",",
"style",
")",
";",
"}"
] | <strong>[icu]</strong> Returns a specific style number format for a specific locale.
@param inLocale the specific locale.
@param style number format style | [
"<strong",
">",
"[",
"icu",
"]",
"<",
"/",
"strong",
">",
"Returns",
"a",
"specific",
"style",
"number",
"format",
"for",
"a",
"specific",
"locale",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NumberFormat.java#L570-L572 |
OpenLiberty/open-liberty | dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/utils/DirUtils.java | DirUtils.createDirectoryPath | public static String createDirectoryPath(String source)
{
if (tc.isEntryEnabled()) Tr.entry(tc, "createDirectoryPath",source);
String directoryPath = null;
if (source != null)
{
directoryPath = "";
final StringTokenizer tokenizer = new StringTokenizer(source,"\\/");
while (tokenizer.hasMoreTokens())
{
final String pathChunk = tokenizer.nextToken();
directoryPath += pathChunk;
if (tokenizer.hasMoreTokens())
{
directoryPath += File.separator;
}
}
}
if (tc.isEntryEnabled()) Tr.exit(tc, "createDirectoryPath",directoryPath);
return directoryPath;
} | java | public static String createDirectoryPath(String source)
{
if (tc.isEntryEnabled()) Tr.entry(tc, "createDirectoryPath",source);
String directoryPath = null;
if (source != null)
{
directoryPath = "";
final StringTokenizer tokenizer = new StringTokenizer(source,"\\/");
while (tokenizer.hasMoreTokens())
{
final String pathChunk = tokenizer.nextToken();
directoryPath += pathChunk;
if (tokenizer.hasMoreTokens())
{
directoryPath += File.separator;
}
}
}
if (tc.isEntryEnabled()) Tr.exit(tc, "createDirectoryPath",directoryPath);
return directoryPath;
} | [
"public",
"static",
"String",
"createDirectoryPath",
"(",
"String",
"source",
")",
"{",
"if",
"(",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"entry",
"(",
"tc",
",",
"\"createDirectoryPath\"",
",",
"source",
")",
";",
"String",
"directoryPath",
... | Replaces forward and backward slashes in the source string with 'File.separator'
characters. | [
"Replaces",
"forward",
"and",
"backward",
"slashes",
"in",
"the",
"source",
"string",
"with",
"File",
".",
"separator",
"characters",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/utils/DirUtils.java#L30-L58 |
aws/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/FailureDetails.java | FailureDetails.setDetails | public void setDetails(java.util.Map<String, java.util.List<String>> details) {
this.details = details;
} | java | public void setDetails(java.util.Map<String, java.util.List<String>> details) {
this.details = details;
} | [
"public",
"void",
"setDetails",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"java",
".",
"util",
".",
"List",
"<",
"String",
">",
">",
"details",
")",
"{",
"this",
".",
"details",
"=",
"details",
";",
"}"
] | <p>
Detailed information about the Automation step failure.
</p>
@param details
Detailed information about the Automation step failure. | [
"<p",
">",
"Detailed",
"information",
"about",
"the",
"Automation",
"step",
"failure",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/FailureDetails.java#L165-L167 |
Netflix/conductor | client/src/main/java/com/netflix/conductor/client/http/TaskClient.java | TaskClient.getPollData | public List<PollData> getPollData(String taskType) {
Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank");
Object[] params = new Object[]{"taskType", taskType};
return getForEntity("tasks/queue/polldata", params, pollDataList);
} | java | public List<PollData> getPollData(String taskType) {
Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank");
Object[] params = new Object[]{"taskType", taskType};
return getForEntity("tasks/queue/polldata", params, pollDataList);
} | [
"public",
"List",
"<",
"PollData",
">",
"getPollData",
"(",
"String",
"taskType",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"taskType",
")",
",",
"\"Task type cannot be blank\"",
")",
";",
"Object",
"[",
"]",
... | Get last poll data for a given task type
@param taskType the task type for which poll data is to be fetched
@return returns the list of poll data for the task type | [
"Get",
"last",
"poll",
"data",
"for",
"a",
"given",
"task",
"type"
] | train | https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/client/src/main/java/com/netflix/conductor/client/http/TaskClient.java#L343-L348 |
amaembo/streamex | src/main/java/one/util/streamex/DoubleStreamEx.java | DoubleStreamEx.zip | public static DoubleStreamEx zip(double[] first, double[] second, DoubleBinaryOperator mapper) {
return of(new RangeBasedSpliterator.ZipDouble(0, checkLength(first.length, second.length), mapper, first,
second));
} | java | public static DoubleStreamEx zip(double[] first, double[] second, DoubleBinaryOperator mapper) {
return of(new RangeBasedSpliterator.ZipDouble(0, checkLength(first.length, second.length), mapper, first,
second));
} | [
"public",
"static",
"DoubleStreamEx",
"zip",
"(",
"double",
"[",
"]",
"first",
",",
"double",
"[",
"]",
"second",
",",
"DoubleBinaryOperator",
"mapper",
")",
"{",
"return",
"of",
"(",
"new",
"RangeBasedSpliterator",
".",
"ZipDouble",
"(",
"0",
",",
"checkLen... | Returns a sequential {@code DoubleStreamEx} containing the results of
applying the given function to the corresponding pairs of values in given
two arrays.
@param first the first array
@param second the second array
@param mapper a non-interfering, stateless function to apply to each pair
of the corresponding array elements.
@return a new {@code DoubleStreamEx}
@throws IllegalArgumentException if length of the arrays differs.
@since 0.2.1 | [
"Returns",
"a",
"sequential",
"{",
"@code",
"DoubleStreamEx",
"}",
"containing",
"the",
"results",
"of",
"applying",
"the",
"given",
"function",
"to",
"the",
"corresponding",
"pairs",
"of",
"values",
"in",
"given",
"two",
"arrays",
"."
] | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/DoubleStreamEx.java#L1904-L1907 |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/socks/Proxy.java | Proxy.exchange | protected ProxyMessage exchange(ProxyMessage request)
throws SocksException{
ProxyMessage reply;
try{
request.write(out);
reply = formMessage(in);
}catch(SocksException s_ex){
throw s_ex;
}catch(IOException ioe){
throw(new SocksException(SOCKS_PROXY_IO_ERROR,""+ioe));
}
return reply;
} | java | protected ProxyMessage exchange(ProxyMessage request)
throws SocksException{
ProxyMessage reply;
try{
request.write(out);
reply = formMessage(in);
}catch(SocksException s_ex){
throw s_ex;
}catch(IOException ioe){
throw(new SocksException(SOCKS_PROXY_IO_ERROR,""+ioe));
}
return reply;
} | [
"protected",
"ProxyMessage",
"exchange",
"(",
"ProxyMessage",
"request",
")",
"throws",
"SocksException",
"{",
"ProxyMessage",
"reply",
";",
"try",
"{",
"request",
".",
"write",
"(",
"out",
")",
";",
"reply",
"=",
"formMessage",
"(",
"in",
")",
";",
"}",
"... | Sends the request reads reply and returns it
throws exception if something wrong with IO
or the reply code is not zero | [
"Sends",
"the",
"request",
"reads",
"reply",
"and",
"returns",
"it",
"throws",
"exception",
"if",
"something",
"wrong",
"with",
"IO",
"or",
"the",
"reply",
"code",
"is",
"not",
"zero"
] | train | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/socks/Proxy.java#L471-L483 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/animation/keyframe/GVRQuatAnimation.java | GVRQuatAnimation.getKey | public void getKey(int keyIndex, Quaternionf q)
{
int index = keyIndex * mFloatsPerKey;
q.x = mKeys[index + 1];
q.y = mKeys[index + 2];
q.z = mKeys[index + 3];
q.w = mKeys[index + 4];
} | java | public void getKey(int keyIndex, Quaternionf q)
{
int index = keyIndex * mFloatsPerKey;
q.x = mKeys[index + 1];
q.y = mKeys[index + 2];
q.z = mKeys[index + 3];
q.w = mKeys[index + 4];
} | [
"public",
"void",
"getKey",
"(",
"int",
"keyIndex",
",",
"Quaternionf",
"q",
")",
"{",
"int",
"index",
"=",
"keyIndex",
"*",
"mFloatsPerKey",
";",
"q",
".",
"x",
"=",
"mKeys",
"[",
"index",
"+",
"1",
"]",
";",
"q",
".",
"y",
"=",
"mKeys",
"[",
"i... | Returns the scaling factor as vector.<p>
@param keyIndex the index of the scale key
@return the scaling factor as vector | [
"Returns",
"the",
"scaling",
"factor",
"as",
"vector",
".",
"<p",
">"
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/animation/keyframe/GVRQuatAnimation.java#L83-L90 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/input/colorpicker/CmsColor.java | CmsColor.setHSV | public void setHSV(int hue, int sat, int val) throws Exception {
if ((hue < 0) || (hue > 360)) {
throw new Exception();
}
if ((sat < 0) || (sat > 100)) {
throw new Exception();
}
if ((val < 0) || (val > 100)) {
throw new Exception();
}
m_hue = hue;
m_sat = (float)sat / 100;
m_bri = (float)val / 100;
HSVtoRGB(m_hue, m_sat, m_bri);
setHex();
} | java | public void setHSV(int hue, int sat, int val) throws Exception {
if ((hue < 0) || (hue > 360)) {
throw new Exception();
}
if ((sat < 0) || (sat > 100)) {
throw new Exception();
}
if ((val < 0) || (val > 100)) {
throw new Exception();
}
m_hue = hue;
m_sat = (float)sat / 100;
m_bri = (float)val / 100;
HSVtoRGB(m_hue, m_sat, m_bri);
setHex();
} | [
"public",
"void",
"setHSV",
"(",
"int",
"hue",
",",
"int",
"sat",
",",
"int",
"val",
")",
"throws",
"Exception",
"{",
"if",
"(",
"(",
"hue",
"<",
"0",
")",
"||",
"(",
"hue",
">",
"360",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
")",
";",... | Set the Hue, Saturation and Value (Brightness) variables.<p>
@param hue hue - valid range is 0-359
@param sat saturation - valid range is 0-100
@param val brightness - valid range is 0-100
@throws java.lang.Exception if something goes wrong | [
"Set",
"the",
"Hue",
"Saturation",
"and",
"Value",
"(",
"Brightness",
")",
"variables",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/input/colorpicker/CmsColor.java#L143-L162 |
Azure/azure-sdk-for-java | containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/TasksInner.java | TasksInner.getDetailsAsync | public Observable<TaskInner> getDetailsAsync(String resourceGroupName, String registryName, String taskName) {
return getDetailsWithServiceResponseAsync(resourceGroupName, registryName, taskName).map(new Func1<ServiceResponse<TaskInner>, TaskInner>() {
@Override
public TaskInner call(ServiceResponse<TaskInner> response) {
return response.body();
}
});
} | java | public Observable<TaskInner> getDetailsAsync(String resourceGroupName, String registryName, String taskName) {
return getDetailsWithServiceResponseAsync(resourceGroupName, registryName, taskName).map(new Func1<ServiceResponse<TaskInner>, TaskInner>() {
@Override
public TaskInner call(ServiceResponse<TaskInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"TaskInner",
">",
"getDetailsAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
",",
"String",
"taskName",
")",
"{",
"return",
"getDetailsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"registryName",
",",
... | Returns a task with extended information that includes all secrets.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param taskName The name of the container registry task.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the TaskInner object | [
"Returns",
"a",
"task",
"with",
"extended",
"information",
"that",
"includes",
"all",
"secrets",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/TasksInner.java#L888-L895 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/csv/CSVParser.java | CSVParser.setSeparatorChar | @Nonnull
public CSVParser setSeparatorChar (final char cSeparator)
{
if (cSeparator == CCSV.NULL_CHARACTER)
throw new UnsupportedOperationException ("The separator character must be defined!");
m_cSeparatorChar = cSeparator;
if (_anyCharactersAreTheSame ())
throw new UnsupportedOperationException ("The separator, quote, and escape characters must be different!");
return this;
} | java | @Nonnull
public CSVParser setSeparatorChar (final char cSeparator)
{
if (cSeparator == CCSV.NULL_CHARACTER)
throw new UnsupportedOperationException ("The separator character must be defined!");
m_cSeparatorChar = cSeparator;
if (_anyCharactersAreTheSame ())
throw new UnsupportedOperationException ("The separator, quote, and escape characters must be different!");
return this;
} | [
"@",
"Nonnull",
"public",
"CSVParser",
"setSeparatorChar",
"(",
"final",
"char",
"cSeparator",
")",
"{",
"if",
"(",
"cSeparator",
"==",
"CCSV",
".",
"NULL_CHARACTER",
")",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"The separator character must be defined!\... | Sets the delimiter to use for separating entries.
@param cSeparator
the delimiter to use for separating entries
@return this | [
"Sets",
"the",
"delimiter",
"to",
"use",
"for",
"separating",
"entries",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/csv/CSVParser.java#L108-L117 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/ControlMessageImpl.java | ControlMessageImpl.appendArray | protected static void appendArray(StringBuilder buff, String name, String[] values) {
buff.append(',');
buff.append(name);
buff.append("=[");
if (values != null) {
for (int i = 0; i < values.length; i++) {
if (i != 0) buff.append(',');
buff.append(values[i]);
}
}
buff.append(']');
} | java | protected static void appendArray(StringBuilder buff, String name, String[] values) {
buff.append(',');
buff.append(name);
buff.append("=[");
if (values != null) {
for (int i = 0; i < values.length; i++) {
if (i != 0) buff.append(',');
buff.append(values[i]);
}
}
buff.append(']');
} | [
"protected",
"static",
"void",
"appendArray",
"(",
"StringBuilder",
"buff",
",",
"String",
"name",
",",
"String",
"[",
"]",
"values",
")",
"{",
"buff",
".",
"append",
"(",
"'",
"'",
")",
";",
"buff",
".",
"append",
"(",
"name",
")",
";",
"buff",
".",... | Helper method to append a string array to a summary string method | [
"Helper",
"method",
"to",
"append",
"a",
"string",
"array",
"to",
"a",
"summary",
"string",
"method"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/ControlMessageImpl.java#L622-L633 |
RestComm/Restcomm-Connect | restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/cors/CorsFilter.java | CorsFilter.filter | @Override
public ContainerResponse filter(ContainerRequest cres, ContainerResponse response) {
initLazily(servletRequest);
String requestOrigin = cres.getHeaderValue("Origin");
if (requestOrigin != null) { // is this is a cors request (ajax request that targets a different domain than the one the page was loaded from)
if (allowedOrigin != null && allowedOrigin.startsWith(requestOrigin)) { // no cors allowances make are applied if allowedOrigins == null
// only return the origin the client informed
response.getHttpHeaders().add("Access-Control-Allow-Origin", requestOrigin);
response.getHttpHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
response.getHttpHeaders().add("Access-Control-Max-Age", "1209600");
}
}
return response;
} | java | @Override
public ContainerResponse filter(ContainerRequest cres, ContainerResponse response) {
initLazily(servletRequest);
String requestOrigin = cres.getHeaderValue("Origin");
if (requestOrigin != null) { // is this is a cors request (ajax request that targets a different domain than the one the page was loaded from)
if (allowedOrigin != null && allowedOrigin.startsWith(requestOrigin)) { // no cors allowances make are applied if allowedOrigins == null
// only return the origin the client informed
response.getHttpHeaders().add("Access-Control-Allow-Origin", requestOrigin);
response.getHttpHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
response.getHttpHeaders().add("Access-Control-Max-Age", "1209600");
}
}
return response;
} | [
"@",
"Override",
"public",
"ContainerResponse",
"filter",
"(",
"ContainerRequest",
"cres",
",",
"ContainerResponse",
"response",
")",
"{",
"initLazily",
"(",
"servletRequest",
")",
";",
"String",
"requestOrigin",
"=",
"cres",
".",
"getHeaderValue",
"(",
"\"Origin\""... | We return Access-* headers only in case allowedOrigin is present and equals to the 'Origin' header. | [
"We",
"return",
"Access",
"-",
"*",
"headers",
"only",
"in",
"case",
"allowedOrigin",
"is",
"present",
"and",
"equals",
"to",
"the",
"Origin",
"header",
"."
] | train | https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/cors/CorsFilter.java#L58-L73 |
RKumsher/utils | src/main/java/com/github/rkumsher/date/RandomDateUtils.java | RandomDateUtils.randomYearMonth | public static YearMonth randomYearMonth(YearMonth startInclusive, YearMonth endExclusive) {
checkArgument(startInclusive != null, "Start must be non-null");
checkArgument(endExclusive != null, "End must be non-null");
LocalDate start = startInclusive.atDay(1);
LocalDate end = endExclusive.atDay(1);
LocalDate localDate = randomLocalDate(start, end);
return YearMonth.of(localDate.getYear(), localDate.getMonth());
} | java | public static YearMonth randomYearMonth(YearMonth startInclusive, YearMonth endExclusive) {
checkArgument(startInclusive != null, "Start must be non-null");
checkArgument(endExclusive != null, "End must be non-null");
LocalDate start = startInclusive.atDay(1);
LocalDate end = endExclusive.atDay(1);
LocalDate localDate = randomLocalDate(start, end);
return YearMonth.of(localDate.getYear(), localDate.getMonth());
} | [
"public",
"static",
"YearMonth",
"randomYearMonth",
"(",
"YearMonth",
"startInclusive",
",",
"YearMonth",
"endExclusive",
")",
"{",
"checkArgument",
"(",
"startInclusive",
"!=",
"null",
",",
"\"Start must be non-null\"",
")",
";",
"checkArgument",
"(",
"endExclusive",
... | Returns a random {@link YearMonth} within the specified range.
@param startInclusive the earliest {@link YearMonth} that can be returned
@param endExclusive the upper bound (not included)
@return the random {@link YearMonth}
@throws IllegalArgumentException if startInclusive or endExclusive are null or if endExclusive
is earlier than startInclusive | [
"Returns",
"a",
"random",
"{",
"@link",
"YearMonth",
"}",
"within",
"the",
"specified",
"range",
"."
] | train | https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/date/RandomDateUtils.java#L802-L809 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/EasterHoliday.java | EasterRule.firstBetween | @Override
public Date firstBetween(Date start, Date end)
{
return doFirstBetween(start, end);
} | java | @Override
public Date firstBetween(Date start, Date end)
{
return doFirstBetween(start, end);
} | [
"@",
"Override",
"public",
"Date",
"firstBetween",
"(",
"Date",
"start",
",",
"Date",
"end",
")",
"{",
"return",
"doFirstBetween",
"(",
"start",
",",
"end",
")",
";",
"}"
] | Return the first occurrence of this rule on or after
the given start date and before the given end date. | [
"Return",
"the",
"first",
"occurrence",
"of",
"this",
"rule",
"on",
"or",
"after",
"the",
"given",
"start",
"date",
"and",
"before",
"the",
"given",
"end",
"date",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/EasterHoliday.java#L161-L165 |
Cornutum/tcases | tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleCombiner.java | TupleCombiner.assertApplicable | private void assertApplicable( FunctionInputDef inputDef, VarNamePattern varNamePattern) throws IllegalArgumentException
{
if( !varNamePattern.isApplicable( inputDef))
{
throw new IllegalArgumentException( "Can't find variable matching pattern=" + varNamePattern);
}
} | java | private void assertApplicable( FunctionInputDef inputDef, VarNamePattern varNamePattern) throws IllegalArgumentException
{
if( !varNamePattern.isApplicable( inputDef))
{
throw new IllegalArgumentException( "Can't find variable matching pattern=" + varNamePattern);
}
} | [
"private",
"void",
"assertApplicable",
"(",
"FunctionInputDef",
"inputDef",
",",
"VarNamePattern",
"varNamePattern",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"!",
"varNamePattern",
".",
"isApplicable",
"(",
"inputDef",
")",
")",
"{",
"throw",
"new"... | Throws an exception if the given variable pattern is not applicable to the given input definition. | [
"Throws",
"an",
"exception",
"if",
"the",
"given",
"variable",
"pattern",
"is",
"not",
"applicable",
"to",
"the",
"given",
"input",
"definition",
"."
] | train | https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleCombiner.java#L494-L500 |
apache/reef | lang/java/reef-runtime-hdinsight/src/main/java/org/apache/reef/runtime/hdinsight/client/yarnrest/HDInsightInstance.java | HDInsightInstance.submitApplication | public void submitApplication(final ApplicationSubmission applicationSubmission) throws IOException {
final String url = "ws/v1/cluster/apps";
final HttpPost post = preparePost(url);
final StringWriter writer = new StringWriter();
try {
this.objectMapper.writeValue(writer, applicationSubmission);
} catch (final IOException e) {
throw new RuntimeException(e);
}
final String message = writer.toString();
LOG.log(Level.FINE, "Sending:\n{0}", message.replace("\n", "\n\t"));
post.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));
try (final CloseableHttpResponse response = this.httpClient.execute(post, this.httpClientContext)) {
final String responseMessage = IOUtils.toString(response.getEntity().getContent());
LOG.log(Level.FINE, "Response: {0}", responseMessage.replace("\n", "\n\t"));
}
} | java | public void submitApplication(final ApplicationSubmission applicationSubmission) throws IOException {
final String url = "ws/v1/cluster/apps";
final HttpPost post = preparePost(url);
final StringWriter writer = new StringWriter();
try {
this.objectMapper.writeValue(writer, applicationSubmission);
} catch (final IOException e) {
throw new RuntimeException(e);
}
final String message = writer.toString();
LOG.log(Level.FINE, "Sending:\n{0}", message.replace("\n", "\n\t"));
post.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));
try (final CloseableHttpResponse response = this.httpClient.execute(post, this.httpClientContext)) {
final String responseMessage = IOUtils.toString(response.getEntity().getContent());
LOG.log(Level.FINE, "Response: {0}", responseMessage.replace("\n", "\n\t"));
}
} | [
"public",
"void",
"submitApplication",
"(",
"final",
"ApplicationSubmission",
"applicationSubmission",
")",
"throws",
"IOException",
"{",
"final",
"String",
"url",
"=",
"\"ws/v1/cluster/apps\"",
";",
"final",
"HttpPost",
"post",
"=",
"preparePost",
"(",
"url",
")",
... | Submits an application for execution.
@param applicationSubmission
@throws IOException | [
"Submits",
"an",
"application",
"for",
"execution",
"."
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-runtime-hdinsight/src/main/java/org/apache/reef/runtime/hdinsight/client/yarnrest/HDInsightInstance.java#L106-L124 |
xm-online/xm-commons | xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/repository/PermittedRepository.java | PermittedRepository.findByCondition | public <T> Page<T> findByCondition(String whereCondition,
Map<String, Object> conditionParams,
Pageable pageable,
Class<T> entityClass,
String privilegeKey) {
return findByCondition(whereCondition, conditionParams, null, pageable, entityClass, privilegeKey);
} | java | public <T> Page<T> findByCondition(String whereCondition,
Map<String, Object> conditionParams,
Pageable pageable,
Class<T> entityClass,
String privilegeKey) {
return findByCondition(whereCondition, conditionParams, null, pageable, entityClass, privilegeKey);
} | [
"public",
"<",
"T",
">",
"Page",
"<",
"T",
">",
"findByCondition",
"(",
"String",
"whereCondition",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"conditionParams",
",",
"Pageable",
"pageable",
",",
"Class",
"<",
"T",
">",
"entityClass",
",",
"String",
... | Find permitted entities by parameters.
@param whereCondition the parameters condition
@param conditionParams the parameters map
@param pageable the page info
@param entityClass the entity class to get
@param privilegeKey the privilege key for permission lookup
@param <T> the type of entity
@return page of permitted entities | [
"Find",
"permitted",
"entities",
"by",
"parameters",
"."
] | train | https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/repository/PermittedRepository.java#L113-L119 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/util/concurrent/ConcurrentConveyor.java | ConcurrentConveyor.drainTo | public final int drainTo(int queueIndex, Collection<? super E> drain, int limit) {
return drain(queues[queueIndex], drain, limit);
} | java | public final int drainTo(int queueIndex, Collection<? super E> drain, int limit) {
return drain(queues[queueIndex], drain, limit);
} | [
"public",
"final",
"int",
"drainTo",
"(",
"int",
"queueIndex",
",",
"Collection",
"<",
"?",
"super",
"E",
">",
"drain",
",",
"int",
"limit",
")",
"{",
"return",
"drain",
"(",
"queues",
"[",
"queueIndex",
"]",
",",
"drain",
",",
"limit",
")",
";",
"}"... | Drains no more than {@code limit} items from the queue at the supplied
index into the supplied collection.
@return the number of items drained | [
"Drains",
"no",
"more",
"than",
"{",
"@code",
"limit",
"}",
"items",
"from",
"the",
"queue",
"at",
"the",
"supplied",
"index",
"into",
"the",
"supplied",
"collection",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/util/concurrent/ConcurrentConveyor.java#L318-L320 |
banq/jdonframework | JdonAccessory/jdon-jdbc/src/main/java/com/jdon/model/query/PageIteratorSolver.java | PageIteratorSolver.getPageIterator | public PageIterator getPageIterator(String sqlqueryAllCount, String sqlquery, String queryParam, int start, int count) {
if (UtilValidate.isEmpty(sqlqueryAllCount)) {
Debug.logError(" the parameter sqlqueryAllCount is null", module);
return new PageIterator();
}
if (UtilValidate.isEmpty(sqlquery)) {
Debug.logError(" the parameter sqlquery is null", module);
return new PageIterator();
}
return getDatas(queryParam, sqlqueryAllCount, sqlquery, start, count);
} | java | public PageIterator getPageIterator(String sqlqueryAllCount, String sqlquery, String queryParam, int start, int count) {
if (UtilValidate.isEmpty(sqlqueryAllCount)) {
Debug.logError(" the parameter sqlqueryAllCount is null", module);
return new PageIterator();
}
if (UtilValidate.isEmpty(sqlquery)) {
Debug.logError(" the parameter sqlquery is null", module);
return new PageIterator();
}
return getDatas(queryParam, sqlqueryAllCount, sqlquery, start, count);
} | [
"public",
"PageIterator",
"getPageIterator",
"(",
"String",
"sqlqueryAllCount",
",",
"String",
"sqlquery",
",",
"String",
"queryParam",
",",
"int",
"start",
",",
"int",
"count",
")",
"{",
"if",
"(",
"UtilValidate",
".",
"isEmpty",
"(",
"sqlqueryAllCount",
")",
... | same as getDatas the parameters sort is different from the getDatas
method
@param sqlqueryAllCount
the sql sentence for "select count(1) .."
@param sqlquery
the sql sentence for "select id from xxxx";
@param queryParam
the parameter of String type for the sqlquery.
@param start
the starting number of a page in allCount;
@param count
the display number of a page
@return | [
"same",
"as",
"getDatas",
"the",
"parameters",
"sort",
"is",
"different",
"from",
"the",
"getDatas",
"method"
] | train | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-jdbc/src/main/java/com/jdon/model/query/PageIteratorSolver.java#L201-L211 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/ResourceHealthMetadatasInner.java | ResourceHealthMetadatasInner.getBySiteSlot | public ResourceHealthMetadataInner getBySiteSlot(String resourceGroupName, String name, String slot) {
return getBySiteSlotWithServiceResponseAsync(resourceGroupName, name, slot).toBlocking().single().body();
} | java | public ResourceHealthMetadataInner getBySiteSlot(String resourceGroupName, String name, String slot) {
return getBySiteSlotWithServiceResponseAsync(resourceGroupName, name, slot).toBlocking().single().body();
} | [
"public",
"ResourceHealthMetadataInner",
"getBySiteSlot",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"String",
"slot",
")",
"{",
"return",
"getBySiteSlotWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"slot",
")",
".",
"toBl... | Gets the category of ResourceHealthMetadata to use for the given site.
Gets the category of ResourceHealthMetadata to use for the given site.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of web app
@param slot Name of web app slot. If not specified then will default to production slot.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws DefaultErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ResourceHealthMetadataInner object if successful. | [
"Gets",
"the",
"category",
"of",
"ResourceHealthMetadata",
"to",
"use",
"for",
"the",
"given",
"site",
".",
"Gets",
"the",
"category",
"of",
"ResourceHealthMetadata",
"to",
"use",
"for",
"the",
"given",
"site",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/ResourceHealthMetadatasInner.java#L701-L703 |
apereo/cas | support/cas-server-support-x509-core/src/main/java/org/apereo/cas/adaptors/x509/authentication/revocation/checker/CRLDistributionPointRevocationChecker.java | CRLDistributionPointRevocationChecker.addURL | private static void addURL(final List<URI> list, final String uriString) {
try {
try {
val url = new URL(URLDecoder.decode(uriString, StandardCharsets.UTF_8.name()));
list.add(new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null));
} catch (final MalformedURLException e) {
list.add(new URI(uriString));
}
} catch (final Exception e) {
LOGGER.warn("[{}] is not a valid distribution point URI.", uriString);
}
} | java | private static void addURL(final List<URI> list, final String uriString) {
try {
try {
val url = new URL(URLDecoder.decode(uriString, StandardCharsets.UTF_8.name()));
list.add(new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null));
} catch (final MalformedURLException e) {
list.add(new URI(uriString));
}
} catch (final Exception e) {
LOGGER.warn("[{}] is not a valid distribution point URI.", uriString);
}
} | [
"private",
"static",
"void",
"addURL",
"(",
"final",
"List",
"<",
"URI",
">",
"list",
",",
"final",
"String",
"uriString",
")",
"{",
"try",
"{",
"try",
"{",
"val",
"url",
"=",
"new",
"URL",
"(",
"URLDecoder",
".",
"decode",
"(",
"uriString",
",",
"St... | Adds the url to the list.
Build URI by components to facilitate proper encoding of querystring.
e.g. http://example.com:8085/ca?action=crl&issuer=CN=CAS Test User CA
<p>
<p>If {@code uriString} is encoded, it will be decoded with {@code UTF-8}
first before it's added to the list.</p>
@param list the list
@param uriString the uri string | [
"Adds",
"the",
"url",
"to",
"the",
"list",
".",
"Build",
"URI",
"by",
"components",
"to",
"facilitate",
"proper",
"encoding",
"of",
"querystring",
".",
"e",
".",
"g",
".",
"http",
":",
"//",
"example",
".",
"com",
":",
"8085",
"/",
"ca?action",
"=",
... | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-x509-core/src/main/java/org/apereo/cas/adaptors/x509/authentication/revocation/checker/CRLDistributionPointRevocationChecker.java#L151-L162 |
citrusframework/citrus | modules/citrus-selenium/src/main/java/com/consol/citrus/selenium/util/BrowserUtils.java | BrowserUtils.makeIECachingSafeUrl | public static String makeIECachingSafeUrl(String url, long unique) {
if (url.contains("timestamp=")) {
return url.replaceFirst("(.*)(timestamp=)(.*)([&#].*)", "$1$2" + unique + "$4")
.replaceFirst("(.*)(timestamp=)(.*)$", "$1$2" + unique);
} else {
return url.contains("?")
? url + "×tamp=" + unique
: url + "?timestamp=" + unique;
}
} | java | public static String makeIECachingSafeUrl(String url, long unique) {
if (url.contains("timestamp=")) {
return url.replaceFirst("(.*)(timestamp=)(.*)([&#].*)", "$1$2" + unique + "$4")
.replaceFirst("(.*)(timestamp=)(.*)$", "$1$2" + unique);
} else {
return url.contains("?")
? url + "×tamp=" + unique
: url + "?timestamp=" + unique;
}
} | [
"public",
"static",
"String",
"makeIECachingSafeUrl",
"(",
"String",
"url",
",",
"long",
"unique",
")",
"{",
"if",
"(",
"url",
".",
"contains",
"(",
"\"timestamp=\"",
")",
")",
"{",
"return",
"url",
".",
"replaceFirst",
"(",
"\"(.*)(timestamp=)(.*)([&#].*)\"",
... | Makes new unique URL to avoid IE caching.
@param url
@param unique
@return | [
"Makes",
"new",
"unique",
"URL",
"to",
"avoid",
"IE",
"caching",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-selenium/src/main/java/com/consol/citrus/selenium/util/BrowserUtils.java#L38-L47 |
algolia/algoliasearch-client-java | src/main/java/com/algolia/search/saas/Index.java | Index.searchRules | public JSONObject searchRules(RuleQuery query, RequestOptions requestOptions) throws AlgoliaException, JSONException {
JSONObject body = new JSONObject();
if (query.getQuery() != null) {
body = body.put("query", query.getQuery());
}
if (query.getAnchoring() != null) {
body = body.put("anchoring", query.getAnchoring());
}
if (query.getContext() != null) {
body = body.put("context", query.getContext());
}
if (query.getPage() != null) {
body = body.put("page", query.getPage());
}
if (query.getHitsPerPage() != null) {
body = body.put("hitsPerPage", query.getHitsPerPage());
}
return client.postRequest("/1/indexes/" + encodedIndexName + "/rules/search", body.toString(), false, true, requestOptions);
} | java | public JSONObject searchRules(RuleQuery query, RequestOptions requestOptions) throws AlgoliaException, JSONException {
JSONObject body = new JSONObject();
if (query.getQuery() != null) {
body = body.put("query", query.getQuery());
}
if (query.getAnchoring() != null) {
body = body.put("anchoring", query.getAnchoring());
}
if (query.getContext() != null) {
body = body.put("context", query.getContext());
}
if (query.getPage() != null) {
body = body.put("page", query.getPage());
}
if (query.getHitsPerPage() != null) {
body = body.put("hitsPerPage", query.getHitsPerPage());
}
return client.postRequest("/1/indexes/" + encodedIndexName + "/rules/search", body.toString(), false, true, requestOptions);
} | [
"public",
"JSONObject",
"searchRules",
"(",
"RuleQuery",
"query",
",",
"RequestOptions",
"requestOptions",
")",
"throws",
"AlgoliaException",
",",
"JSONException",
"{",
"JSONObject",
"body",
"=",
"new",
"JSONObject",
"(",
")",
";",
"if",
"(",
"query",
".",
"getQ... | Search for query rules
@param query the query
@param requestOptions Options to pass to this request | [
"Search",
"for",
"query",
"rules"
] | train | https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L1857-L1876 |
alamkanak/Android-Week-View | sample/src/main/java/com/alamkanak/weekview/sample/BaseActivity.java | BaseActivity.setupDateTimeInterpreter | private void setupDateTimeInterpreter(final boolean shortDate) {
mWeekView.setDateTimeInterpreter(new DateTimeInterpreter() {
@Override
public String interpretDate(Calendar date) {
SimpleDateFormat weekdayNameFormat = new SimpleDateFormat("EEE", Locale.getDefault());
String weekday = weekdayNameFormat.format(date.getTime());
SimpleDateFormat format = new SimpleDateFormat(" M/d", Locale.getDefault());
// All android api level do not have a standard way of getting the first letter of
// the week day name. Hence we get the first char programmatically.
// Details: http://stackoverflow.com/questions/16959502/get-one-letter-abbreviation-of-week-day-of-a-date-in-java#answer-16959657
if (shortDate)
weekday = String.valueOf(weekday.charAt(0));
return weekday.toUpperCase() + format.format(date.getTime());
}
@Override
public String interpretTime(int hour) {
return hour > 11 ? (hour - 12) + " PM" : (hour == 0 ? "12 AM" : hour + " AM");
}
});
} | java | private void setupDateTimeInterpreter(final boolean shortDate) {
mWeekView.setDateTimeInterpreter(new DateTimeInterpreter() {
@Override
public String interpretDate(Calendar date) {
SimpleDateFormat weekdayNameFormat = new SimpleDateFormat("EEE", Locale.getDefault());
String weekday = weekdayNameFormat.format(date.getTime());
SimpleDateFormat format = new SimpleDateFormat(" M/d", Locale.getDefault());
// All android api level do not have a standard way of getting the first letter of
// the week day name. Hence we get the first char programmatically.
// Details: http://stackoverflow.com/questions/16959502/get-one-letter-abbreviation-of-week-day-of-a-date-in-java#answer-16959657
if (shortDate)
weekday = String.valueOf(weekday.charAt(0));
return weekday.toUpperCase() + format.format(date.getTime());
}
@Override
public String interpretTime(int hour) {
return hour > 11 ? (hour - 12) + " PM" : (hour == 0 ? "12 AM" : hour + " AM");
}
});
} | [
"private",
"void",
"setupDateTimeInterpreter",
"(",
"final",
"boolean",
"shortDate",
")",
"{",
"mWeekView",
".",
"setDateTimeInterpreter",
"(",
"new",
"DateTimeInterpreter",
"(",
")",
"{",
"@",
"Override",
"public",
"String",
"interpretDate",
"(",
"Calendar",
"date"... | Set up a date time interpreter which will show short date values when in week view and long
date values otherwise.
@param shortDate True if the date values should be short. | [
"Set",
"up",
"a",
"date",
"time",
"interpreter",
"which",
"will",
"show",
"short",
"date",
"values",
"when",
"in",
"week",
"view",
"and",
"long",
"date",
"values",
"otherwise",
"."
] | train | https://github.com/alamkanak/Android-Week-View/blob/dc3f97d65d44785d1a761b52b58527c86c4eee1b/sample/src/main/java/com/alamkanak/weekview/sample/BaseActivity.java#L121-L142 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java | ImgUtil.binary | public static void binary(ImageInputStream srcStream, ImageOutputStream destStream, String imageType) {
binary(read(srcStream), destStream, imageType);
} | java | public static void binary(ImageInputStream srcStream, ImageOutputStream destStream, String imageType) {
binary(read(srcStream), destStream, imageType);
} | [
"public",
"static",
"void",
"binary",
"(",
"ImageInputStream",
"srcStream",
",",
"ImageOutputStream",
"destStream",
",",
"String",
"imageType",
")",
"{",
"binary",
"(",
"read",
"(",
"srcStream",
")",
",",
"destStream",
",",
"imageType",
")",
";",
"}"
] | 彩色转为黑白黑白二值化图片<br>
此方法并不关闭流
@param srcStream 源图像流
@param destStream 目标图像流
@param imageType 图片格式(扩展名)
@since 4.0.5 | [
"彩色转为黑白黑白二值化图片<br",
">",
"此方法并不关闭流"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L688-L690 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringParser.java | StringParser.parseLongObj | @Nullable
public static Long parseLongObj (@Nullable final Object aObject)
{
return parseLongObj (aObject, DEFAULT_RADIX, null);
} | java | @Nullable
public static Long parseLongObj (@Nullable final Object aObject)
{
return parseLongObj (aObject, DEFAULT_RADIX, null);
} | [
"@",
"Nullable",
"public",
"static",
"Long",
"parseLongObj",
"(",
"@",
"Nullable",
"final",
"Object",
"aObject",
")",
"{",
"return",
"parseLongObj",
"(",
"aObject",
",",
"DEFAULT_RADIX",
",",
"null",
")",
";",
"}"
] | Parse the given {@link Object} as {@link Long} with radix
{@value #DEFAULT_RADIX}.
@param aObject
The object to parse. May be <code>null</code>.
@return <code>null</code> if the object does not represent a valid value. | [
"Parse",
"the",
"given",
"{",
"@link",
"Object",
"}",
"as",
"{",
"@link",
"Long",
"}",
"with",
"radix",
"{",
"@value",
"#DEFAULT_RADIX",
"}",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L1057-L1061 |
magro/memcached-session-manager | core/src/main/java/de/javakaffee/web/msm/NodeAvailabilityCache.java | NodeAvailabilityCache.setNodeAvailable | @CheckForNull
@SuppressWarnings( "NP_BOOLEAN_RETURN_NULL" )
public Boolean setNodeAvailable( final K key, final boolean available ) {
final ManagedItem<Boolean> item = _map.get( key );
final Boolean availableObj = Boolean.valueOf( available );
if ( item == null || item._value != availableObj ) {
final ManagedItem<Boolean> previous =
_map.put( key, new ManagedItem<Boolean>( availableObj, System.currentTimeMillis() ) );
return previous != null
? previous._value
: null;
} else {
return item._value;
}
} | java | @CheckForNull
@SuppressWarnings( "NP_BOOLEAN_RETURN_NULL" )
public Boolean setNodeAvailable( final K key, final boolean available ) {
final ManagedItem<Boolean> item = _map.get( key );
final Boolean availableObj = Boolean.valueOf( available );
if ( item == null || item._value != availableObj ) {
final ManagedItem<Boolean> previous =
_map.put( key, new ManagedItem<Boolean>( availableObj, System.currentTimeMillis() ) );
return previous != null
? previous._value
: null;
} else {
return item._value;
}
} | [
"@",
"CheckForNull",
"@",
"SuppressWarnings",
"(",
"\"NP_BOOLEAN_RETURN_NULL\"",
")",
"public",
"Boolean",
"setNodeAvailable",
"(",
"final",
"K",
"key",
",",
"final",
"boolean",
"available",
")",
"{",
"final",
"ManagedItem",
"<",
"Boolean",
">",
"item",
"=",
"_m... | If the specified key is not already associated with a value or if it's
associated with a different value, associate it with the given value.
This is equivalent to
<pre>
<code> if (map.get(key) == null || !map.get(key).equals(value))
return map.put(key, value);
else
return map.get(key);
</code>
</pre>
except that the action is performed atomically.
@param key
the key to associate the value with.
@param available
the value to associate with the provided key.
@return the previous value associated with the specified key, or null if
there was no mapping for the key | [
"If",
"the",
"specified",
"key",
"is",
"not",
"already",
"associated",
"with",
"a",
"value",
"or",
"if",
"it",
"s",
"associated",
"with",
"a",
"different",
"value",
"associate",
"it",
"with",
"the",
"given",
"value",
".",
"This",
"is",
"equivalent",
"to"
] | train | https://github.com/magro/memcached-session-manager/blob/716e147c9840ab10298c4d2b9edd0662058331e6/core/src/main/java/de/javakaffee/web/msm/NodeAvailabilityCache.java#L91-L105 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/slim/FileFixture.java | FileFixture.createContainingValue | public String createContainingValue(String filename, String key) {
Object data = value(key);
if (data == null) {
throw new SlimFixtureException(false, "No value for key: " + key);
}
return createContaining(filename, data);
} | java | public String createContainingValue(String filename, String key) {
Object data = value(key);
if (data == null) {
throw new SlimFixtureException(false, "No value for key: " + key);
}
return createContaining(filename, data);
} | [
"public",
"String",
"createContainingValue",
"(",
"String",
"filename",
",",
"String",
"key",
")",
"{",
"Object",
"data",
"=",
"value",
"(",
"key",
")",
";",
"if",
"(",
"data",
"==",
"null",
")",
"{",
"throw",
"new",
"SlimFixtureException",
"(",
"false",
... | Creates new file, containing value 'key'.
@param filename name of file to create.
@param key key whose value should be used to generate the file.
@return file created. | [
"Creates",
"new",
"file",
"containing",
"value",
"key",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/slim/FileFixture.java#L54-L60 |
nikolavp/approval | approval-core/src/main/java/com/github/approval/Pre.java | Pre.notNull | public static void notNull(@Nullable Object value, String name) {
if (value == null) {
throw new IllegalArgumentException(name + " must not be null!");
}
} | java | public static void notNull(@Nullable Object value, String name) {
if (value == null) {
throw new IllegalArgumentException(name + " must not be null!");
}
} | [
"public",
"static",
"void",
"notNull",
"(",
"@",
"Nullable",
"Object",
"value",
",",
"String",
"name",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"name",
"+",
"\" must not be null!\"",
")",
";",
"... | Verify that a value is not null.
@param value the value to verify
@param name the name of the value that will be used in the exception message. | [
"Verify",
"that",
"a",
"value",
"is",
"not",
"null",
"."
] | train | https://github.com/nikolavp/approval/blob/5e32ecc3bc7f631e94a7049894fdd99a3aa5b1b8/approval-core/src/main/java/com/github/approval/Pre.java#L39-L43 |
line/armeria | core/src/main/java/com/linecorp/armeria/server/PathMappingResult.java | PathMappingResult.of | public static PathMappingResult of(String path, @Nullable String query,
Map<String, String> rawPathParams, int score) {
requireNonNull(path, "path");
requireNonNull(rawPathParams, "rawPathParams");
return new PathMappingResult(path, query, rawPathParams, score);
} | java | public static PathMappingResult of(String path, @Nullable String query,
Map<String, String> rawPathParams, int score) {
requireNonNull(path, "path");
requireNonNull(rawPathParams, "rawPathParams");
return new PathMappingResult(path, query, rawPathParams, score);
} | [
"public",
"static",
"PathMappingResult",
"of",
"(",
"String",
"path",
",",
"@",
"Nullable",
"String",
"query",
",",
"Map",
"<",
"String",
",",
"String",
">",
"rawPathParams",
",",
"int",
"score",
")",
"{",
"requireNonNull",
"(",
"path",
",",
"\"path\"",
")... | Creates a new instance with the specified {@code path}, {@code query}, the extracted path parameters
and the score. | [
"Creates",
"a",
"new",
"instance",
"with",
"the",
"specified",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/PathMappingResult.java#L74-L79 |
Deep-Symmetry/beat-link | src/main/java/org/deepsymmetry/beatlink/data/WaveformFinder.java | WaveformFinder.deliverWaveformDetailUpdate | private void deliverWaveformDetailUpdate(final int player, final WaveformDetail detail) {
if (!getWaveformListeners().isEmpty()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final WaveformDetailUpdate update = new WaveformDetailUpdate(player, detail);
for (final WaveformListener listener : getWaveformListeners()) {
try {
listener.detailChanged(update);
} catch (Throwable t) {
logger.warn("Problem delivering waveform detail update to listener", t);
}
}
}
});
}
} | java | private void deliverWaveformDetailUpdate(final int player, final WaveformDetail detail) {
if (!getWaveformListeners().isEmpty()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final WaveformDetailUpdate update = new WaveformDetailUpdate(player, detail);
for (final WaveformListener listener : getWaveformListeners()) {
try {
listener.detailChanged(update);
} catch (Throwable t) {
logger.warn("Problem delivering waveform detail update to listener", t);
}
}
}
});
}
} | [
"private",
"void",
"deliverWaveformDetailUpdate",
"(",
"final",
"int",
"player",
",",
"final",
"WaveformDetail",
"detail",
")",
"{",
"if",
"(",
"!",
"getWaveformListeners",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"SwingUtilities",
".",
"invokeLater",
"("... | Send a waveform detail update announcement to all registered listeners.
@param player the player whose waveform detail has changed
@param detail the new waveform detail, if any | [
"Send",
"a",
"waveform",
"detail",
"update",
"announcement",
"to",
"all",
"registered",
"listeners",
"."
] | train | https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/WaveformFinder.java#L697-L714 |
lettuce-io/lettuce-core | src/main/java/io/lettuce/core/support/ConnectionPoolSupport.java | ConnectionPoolSupport.createSoftReferenceObjectPool | public static <T extends StatefulConnection<?, ?>> SoftReferenceObjectPool<T> createSoftReferenceObjectPool(
Supplier<T> connectionSupplier) {
return createSoftReferenceObjectPool(connectionSupplier, true);
} | java | public static <T extends StatefulConnection<?, ?>> SoftReferenceObjectPool<T> createSoftReferenceObjectPool(
Supplier<T> connectionSupplier) {
return createSoftReferenceObjectPool(connectionSupplier, true);
} | [
"public",
"static",
"<",
"T",
"extends",
"StatefulConnection",
"<",
"?",
",",
"?",
">",
">",
"SoftReferenceObjectPool",
"<",
"T",
">",
"createSoftReferenceObjectPool",
"(",
"Supplier",
"<",
"T",
">",
"connectionSupplier",
")",
"{",
"return",
"createSoftReferenceOb... | Creates a new {@link SoftReferenceObjectPool} using the {@link Supplier}. Allocated instances are wrapped and must not be
returned with {@link ObjectPool#returnObject(Object)}.
@param connectionSupplier must not be {@literal null}.
@param <T> connection type.
@return the connection pool. | [
"Creates",
"a",
"new",
"{",
"@link",
"SoftReferenceObjectPool",
"}",
"using",
"the",
"{",
"@link",
"Supplier",
"}",
".",
"Allocated",
"instances",
"are",
"wrapped",
"and",
"must",
"not",
"be",
"returned",
"with",
"{",
"@link",
"ObjectPool#returnObject",
"(",
"... | train | https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/support/ConnectionPoolSupport.java#L149-L152 |
alkacon/opencms-core | src/org/opencms/ui/apps/user/CmsUserTable.java | CmsUserTable.fillItem | protected void fillItem(Item item, CmsUser user) {
item.getItemProperty(TableProperty.Name).setValue(user.getSimpleName());
item.getItemProperty(TableProperty.FullName).setValue(user.getFullName());
item.getItemProperty(TableProperty.SystemName).setValue(user.getName());
boolean disabled = !user.isEnabled();
item.getItemProperty(TableProperty.DISABLED).setValue(new Boolean(disabled));
boolean newUser = user.getLastlogin() == 0L;
item.getItemProperty(TableProperty.NEWUSER).setValue(new Boolean(newUser));
try {
item.getItemProperty(TableProperty.OU).setValue(
OpenCms.getOrgUnitManager().readOrganizationalUnit(m_cms, user.getOuFqn()).getDisplayName(
A_CmsUI.get().getLocale()));
} catch (CmsException e) {
LOG.error("Can't read OU", e);
}
item.getItemProperty(TableProperty.LastLogin).setValue(new Long(user.getLastlogin()));
item.getItemProperty(TableProperty.Created).setValue(new Long(user.getDateCreated()));
item.getItemProperty(TableProperty.INDIRECT).setValue(new Boolean(m_indirects.contains(user)));
item.getItemProperty(TableProperty.FROMOTHEROU).setValue(new Boolean(!user.getOuFqn().equals(m_ou)));
item.getItemProperty(TableProperty.STATUS).setValue(getStatusInt(disabled, newUser));
} | java | protected void fillItem(Item item, CmsUser user) {
item.getItemProperty(TableProperty.Name).setValue(user.getSimpleName());
item.getItemProperty(TableProperty.FullName).setValue(user.getFullName());
item.getItemProperty(TableProperty.SystemName).setValue(user.getName());
boolean disabled = !user.isEnabled();
item.getItemProperty(TableProperty.DISABLED).setValue(new Boolean(disabled));
boolean newUser = user.getLastlogin() == 0L;
item.getItemProperty(TableProperty.NEWUSER).setValue(new Boolean(newUser));
try {
item.getItemProperty(TableProperty.OU).setValue(
OpenCms.getOrgUnitManager().readOrganizationalUnit(m_cms, user.getOuFqn()).getDisplayName(
A_CmsUI.get().getLocale()));
} catch (CmsException e) {
LOG.error("Can't read OU", e);
}
item.getItemProperty(TableProperty.LastLogin).setValue(new Long(user.getLastlogin()));
item.getItemProperty(TableProperty.Created).setValue(new Long(user.getDateCreated()));
item.getItemProperty(TableProperty.INDIRECT).setValue(new Boolean(m_indirects.contains(user)));
item.getItemProperty(TableProperty.FROMOTHEROU).setValue(new Boolean(!user.getOuFqn().equals(m_ou)));
item.getItemProperty(TableProperty.STATUS).setValue(getStatusInt(disabled, newUser));
} | [
"protected",
"void",
"fillItem",
"(",
"Item",
"item",
",",
"CmsUser",
"user",
")",
"{",
"item",
".",
"getItemProperty",
"(",
"TableProperty",
".",
"Name",
")",
".",
"setValue",
"(",
"user",
".",
"getSimpleName",
"(",
")",
")",
";",
"item",
".",
"getItemP... | Fills the container item for a user.<p>
@param item the item
@param user the user | [
"Fills",
"the",
"container",
"item",
"for",
"a",
"user",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/user/CmsUserTable.java#L1050-L1071 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GJGeometryReader.java | GJGeometryReader.parsePolygon | private Polygon parsePolygon(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ coordinates
jp.nextToken(); //Start the RING
int linesIndex = 0;
LinearRing linearRing = null;
ArrayList<LinearRing> holes = new ArrayList<LinearRing>();
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
if (linesIndex == 0) {
linearRing = GF.createLinearRing(parseCoordinates(jp));
} else {
holes.add(GF.createLinearRing(parseCoordinates(jp)));
}
jp.nextToken();//END RING
linesIndex++;
}
if (linesIndex > 1) {
jp.nextToken();//END_OBJECT } geometry
return GF.createPolygon(linearRing, holes.toArray(new LinearRing[0]));
} else {
jp.nextToken();//END_OBJECT } geometry
return GF.createPolygon(linearRing, null);
}
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
} | java | private Polygon parsePolygon(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ coordinates
jp.nextToken(); //Start the RING
int linesIndex = 0;
LinearRing linearRing = null;
ArrayList<LinearRing> holes = new ArrayList<LinearRing>();
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
if (linesIndex == 0) {
linearRing = GF.createLinearRing(parseCoordinates(jp));
} else {
holes.add(GF.createLinearRing(parseCoordinates(jp)));
}
jp.nextToken();//END RING
linesIndex++;
}
if (linesIndex > 1) {
jp.nextToken();//END_OBJECT } geometry
return GF.createPolygon(linearRing, holes.toArray(new LinearRing[0]));
} else {
jp.nextToken();//END_OBJECT } geometry
return GF.createPolygon(linearRing, null);
}
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
} | [
"private",
"Polygon",
"parsePolygon",
"(",
"JsonParser",
"jp",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"jp",
".",
"nextToken",
"(",
")",
";",
"// FIELD_NAME coordinates ",
"String",
"coordinatesField",
"=",
"jp",
".",
"getText",
"(",
")",
... | Coordinates of a Polygon are an array of LinearRing coordinate arrays.
The first element in the array represents the exterior ring. Any
subsequent elements represent interior rings (or holes).
Syntax:
No holes:
{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }
With holes:
{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], [ [100.2, 0.2], [100.8, 0.2],
[100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] ] }
@param jp
@return Polygon | [
"Coordinates",
"of",
"a",
"Polygon",
"are",
"an",
"array",
"of",
"LinearRing",
"coordinate",
"arrays",
".",
"The",
"first",
"element",
"in",
"the",
"array",
"represents",
"the",
"exterior",
"ring",
".",
"Any",
"subsequent",
"elements",
"represent",
"interior",
... | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GJGeometryReader.java#L203-L231 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/client/ApiClient.java | ApiClient.requestJWTUserToken | public OAuth.OAuthToken requestJWTUserToken(String clientId, String userId, java.util.List<String>scopes, byte[] rsaPrivateKey, long expiresIn) throws IllegalArgumentException, IOException, ApiException {
String formattedScopes = (scopes == null || scopes.size() < 1) ? "" : scopes.get(0);
StringBuilder sb = new StringBuilder(formattedScopes);
for (int i = 1; i < scopes.size(); i++) {
sb.append(" " + scopes.get(i));
}
try {
String assertion = JWTUtils.generateJWTAssertionFromByteArray(rsaPrivateKey, getOAuthBasePath(), clientId, userId, expiresIn, sb.toString());
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("assertion", assertion);
form.add("grant_type", OAuth.GRANT_TYPE_JWT);
Client client = buildHttpClient(debugging);
WebResource webResource = client.resource("https://" + getOAuthBasePath() + "/oauth/token");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OAuth.OAuthToken oAuthToken = mapper.readValue(response.getEntityInputStream(), OAuth.OAuthToken.class);
if (oAuthToken.getAccessToken() == null || "".equals(oAuthToken.getAccessToken()) || oAuthToken.getExpiresIn() <= 0) {
throw new ApiException("Error while requesting an access token: " + response.toString());
}
return oAuthToken;
} catch (JsonParseException e) {
throw new ApiException("Error while parsing the response for the access token: " + e);
} catch (JsonMappingException e) {
throw e;
} catch (IOException e) {
throw e;
}
} | java | public OAuth.OAuthToken requestJWTUserToken(String clientId, String userId, java.util.List<String>scopes, byte[] rsaPrivateKey, long expiresIn) throws IllegalArgumentException, IOException, ApiException {
String formattedScopes = (scopes == null || scopes.size() < 1) ? "" : scopes.get(0);
StringBuilder sb = new StringBuilder(formattedScopes);
for (int i = 1; i < scopes.size(); i++) {
sb.append(" " + scopes.get(i));
}
try {
String assertion = JWTUtils.generateJWTAssertionFromByteArray(rsaPrivateKey, getOAuthBasePath(), clientId, userId, expiresIn, sb.toString());
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("assertion", assertion);
form.add("grant_type", OAuth.GRANT_TYPE_JWT);
Client client = buildHttpClient(debugging);
WebResource webResource = client.resource("https://" + getOAuthBasePath() + "/oauth/token");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OAuth.OAuthToken oAuthToken = mapper.readValue(response.getEntityInputStream(), OAuth.OAuthToken.class);
if (oAuthToken.getAccessToken() == null || "".equals(oAuthToken.getAccessToken()) || oAuthToken.getExpiresIn() <= 0) {
throw new ApiException("Error while requesting an access token: " + response.toString());
}
return oAuthToken;
} catch (JsonParseException e) {
throw new ApiException("Error while parsing the response for the access token: " + e);
} catch (JsonMappingException e) {
throw e;
} catch (IOException e) {
throw e;
}
} | [
"public",
"OAuth",
".",
"OAuthToken",
"requestJWTUserToken",
"(",
"String",
"clientId",
",",
"String",
"userId",
",",
"java",
".",
"util",
".",
"List",
"<",
"String",
">",
"scopes",
",",
"byte",
"[",
"]",
"rsaPrivateKey",
",",
"long",
"expiresIn",
")",
"th... | Configures the current instance of ApiClient with a fresh OAuth JWT access token from DocuSign
@param clientId DocuSign OAuth Client Id (AKA Integrator Key)
@param userId DocuSign user Id to be impersonated (This is a UUID)
@param scopes the list of requested scopes. Values include {@link OAuth#Scope_SIGNATURE}, {@link OAuth#Scope_EXTENDED}, {@link OAuth#Scope_IMPERSONATION}. You can also pass any advanced scope.
@param rsaPrivateKey the byte contents of the RSA private key
@param expiresIn number of seconds remaining before the JWT assertion is considered as invalid
@return OAuth.OAuthToken object.
@throws IllegalArgumentException if one of the arguments is invalid
@throws IOException if there is an issue with either the public or private file
@throws ApiException if there is an error while exchanging the JWT with an access token | [
"Configures",
"the",
"current",
"instance",
"of",
"ApiClient",
"with",
"a",
"fresh",
"OAuth",
"JWT",
"access",
"token",
"from",
"DocuSign"
] | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/client/ApiClient.java#L717-L750 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/ObjectInputStream.java | ObjectInputStream.readNonPrimitiveContent | private Object readNonPrimitiveContent(boolean unshared)
throws ClassNotFoundException, IOException {
checkReadPrimitiveTypes();
int remaining = primitiveData.available();
if (remaining > 0) {
OptionalDataException e = new OptionalDataException(remaining);
e.length = remaining;
throw e;
}
do {
byte tc = nextTC();
switch (tc) {
case TC_CLASS:
return readNewClass(unshared);
case TC_CLASSDESC:
return readNewClassDesc(unshared);
case TC_ARRAY:
return readNewArray(unshared);
case TC_OBJECT:
return readNewObject(unshared);
case TC_STRING:
return readNewString(unshared);
case TC_LONGSTRING:
return readNewLongString(unshared);
case TC_ENUM:
return readEnum(unshared);
case TC_REFERENCE:
if (unshared) {
readNewHandle();
throw new InvalidObjectException("Unshared read of back reference");
}
return readCyclicReference();
case TC_NULL:
return null;
case TC_EXCEPTION:
Exception exc = readException();
throw new WriteAbortedException("Read an exception", exc);
case TC_RESET:
resetState();
break;
case TC_ENDBLOCKDATA: // Can occur reading class annotation
pushbackTC();
OptionalDataException e = new OptionalDataException(true);
e.eof = true;
throw e;
default:
throw corruptStream(tc);
}
// Only TC_RESET falls through
} while (true);
} | java | private Object readNonPrimitiveContent(boolean unshared)
throws ClassNotFoundException, IOException {
checkReadPrimitiveTypes();
int remaining = primitiveData.available();
if (remaining > 0) {
OptionalDataException e = new OptionalDataException(remaining);
e.length = remaining;
throw e;
}
do {
byte tc = nextTC();
switch (tc) {
case TC_CLASS:
return readNewClass(unshared);
case TC_CLASSDESC:
return readNewClassDesc(unshared);
case TC_ARRAY:
return readNewArray(unshared);
case TC_OBJECT:
return readNewObject(unshared);
case TC_STRING:
return readNewString(unshared);
case TC_LONGSTRING:
return readNewLongString(unshared);
case TC_ENUM:
return readEnum(unshared);
case TC_REFERENCE:
if (unshared) {
readNewHandle();
throw new InvalidObjectException("Unshared read of back reference");
}
return readCyclicReference();
case TC_NULL:
return null;
case TC_EXCEPTION:
Exception exc = readException();
throw new WriteAbortedException("Read an exception", exc);
case TC_RESET:
resetState();
break;
case TC_ENDBLOCKDATA: // Can occur reading class annotation
pushbackTC();
OptionalDataException e = new OptionalDataException(true);
e.eof = true;
throw e;
default:
throw corruptStream(tc);
}
// Only TC_RESET falls through
} while (true);
} | [
"private",
"Object",
"readNonPrimitiveContent",
"(",
"boolean",
"unshared",
")",
"throws",
"ClassNotFoundException",
",",
"IOException",
"{",
"checkReadPrimitiveTypes",
"(",
")",
";",
"int",
"remaining",
"=",
"primitiveData",
".",
"available",
"(",
")",
";",
"if",
... | Reads the content of the receiver based on the previously read token
{@code tc}. Primitive data content is considered an error.
@param unshared
read the object unshared
@return the object read from the stream
@throws IOException
If an IO exception happened when reading the class
descriptor.
@throws ClassNotFoundException
If the class corresponding to the object being read could not
be found. | [
"Reads",
"the",
"content",
"of",
"the",
"receiver",
"based",
"on",
"the",
"previously",
"read",
"token",
"{",
"@code",
"tc",
"}",
".",
"Primitive",
"data",
"content",
"is",
"considered",
"an",
"error",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/ObjectInputStream.java#L770-L821 |
jbundle/jbundle | thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/DatabaseProxy.java | DatabaseProxy.setDBProperties | public void setDBProperties(Map<String, Object> properties) throws DBException, RemoteException
{
BaseTransport transport = this.createProxyTransport(SET_DB_PROPERTIES);
transport.addParam(PROPERTIES, properties);
Object strReturn = transport.sendMessageAndGetReply();
Object objReturn = transport.convertReturnObject(strReturn);
this.checkDBException(objReturn);
} | java | public void setDBProperties(Map<String, Object> properties) throws DBException, RemoteException
{
BaseTransport transport = this.createProxyTransport(SET_DB_PROPERTIES);
transport.addParam(PROPERTIES, properties);
Object strReturn = transport.sendMessageAndGetReply();
Object objReturn = transport.convertReturnObject(strReturn);
this.checkDBException(objReturn);
} | [
"public",
"void",
"setDBProperties",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"throws",
"DBException",
",",
"RemoteException",
"{",
"BaseTransport",
"transport",
"=",
"this",
".",
"createProxyTransport",
"(",
"SET_DB_PROPERTIES",
")",
";",... | Get the database properties.
@return The database properties object (Always non-null). | [
"Get",
"the",
"database",
"properties",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/DatabaseProxy.java#L105-L112 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryParameterValue.java | QueryParameterValue.of | public static <T> QueryParameterValue of(T value, Class<T> type) {
return of(value, classToType(type));
} | java | public static <T> QueryParameterValue of(T value, Class<T> type) {
return of(value, classToType(type));
} | [
"public",
"static",
"<",
"T",
">",
"QueryParameterValue",
"of",
"(",
"T",
"value",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"return",
"of",
"(",
"value",
",",
"classToType",
"(",
"type",
")",
")",
";",
"}"
] | Creates a {@code QueryParameterValue} object with the given value and type. | [
"Creates",
"a",
"{"
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryParameterValue.java#L164-L166 |
derari/cthul | objects/src/main/java/org/cthul/objects/Boxing.java | Boxing.boxAllAs | public static <T> T boxAllAs(Object src, Class<T> type) {
return (T) boxAll(type, src, 0, -1);
} | java | public static <T> T boxAllAs(Object src, Class<T> type) {
return (T) boxAll(type, src, 0, -1);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"boxAllAs",
"(",
"Object",
"src",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"return",
"(",
"T",
")",
"boxAll",
"(",
"type",
",",
"src",
",",
"0",
",",
"-",
"1",
")",
";",
"}"
] | Transforms any array into an array of boxed values.
@param <T>
@param type target type
@param src source array
@return array | [
"Transforms",
"any",
"array",
"into",
"an",
"array",
"of",
"boxed",
"values",
"."
] | train | https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/objects/src/main/java/org/cthul/objects/Boxing.java#L491-L493 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java | MariaDbDatabaseMetaData.getPrimaryKeys | public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException {
//MySQL 8 now use 'PRI' in place of 'pri'
String sql =
"SELECT A.TABLE_SCHEMA TABLE_CAT, NULL TABLE_SCHEM, A.TABLE_NAME, A.COLUMN_NAME, B.SEQ_IN_INDEX KEY_SEQ, B.INDEX_NAME PK_NAME "
+ " FROM INFORMATION_SCHEMA.COLUMNS A, INFORMATION_SCHEMA.STATISTICS B"
+ " WHERE A.COLUMN_KEY in ('PRI','pri') AND B.INDEX_NAME='PRIMARY' "
+ " AND "
+ catalogCond("A.TABLE_SCHEMA", catalog)
+ " AND "
+ catalogCond("B.TABLE_SCHEMA", catalog)
+ " AND "
+ patternCond("A.TABLE_NAME", table)
+ " AND "
+ patternCond("B.TABLE_NAME", table)
+ " AND A.TABLE_SCHEMA = B.TABLE_SCHEMA AND A.TABLE_NAME = B.TABLE_NAME AND A.COLUMN_NAME = B.COLUMN_NAME "
+ " ORDER BY A.COLUMN_NAME";
return executeQuery(sql);
} | java | public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException {
//MySQL 8 now use 'PRI' in place of 'pri'
String sql =
"SELECT A.TABLE_SCHEMA TABLE_CAT, NULL TABLE_SCHEM, A.TABLE_NAME, A.COLUMN_NAME, B.SEQ_IN_INDEX KEY_SEQ, B.INDEX_NAME PK_NAME "
+ " FROM INFORMATION_SCHEMA.COLUMNS A, INFORMATION_SCHEMA.STATISTICS B"
+ " WHERE A.COLUMN_KEY in ('PRI','pri') AND B.INDEX_NAME='PRIMARY' "
+ " AND "
+ catalogCond("A.TABLE_SCHEMA", catalog)
+ " AND "
+ catalogCond("B.TABLE_SCHEMA", catalog)
+ " AND "
+ patternCond("A.TABLE_NAME", table)
+ " AND "
+ patternCond("B.TABLE_NAME", table)
+ " AND A.TABLE_SCHEMA = B.TABLE_SCHEMA AND A.TABLE_NAME = B.TABLE_NAME AND A.COLUMN_NAME = B.COLUMN_NAME "
+ " ORDER BY A.COLUMN_NAME";
return executeQuery(sql);
} | [
"public",
"ResultSet",
"getPrimaryKeys",
"(",
"String",
"catalog",
",",
"String",
"schema",
",",
"String",
"table",
")",
"throws",
"SQLException",
"{",
"//MySQL 8 now use 'PRI' in place of 'pri'",
"String",
"sql",
"=",
"\"SELECT A.TABLE_SCHEMA TABLE_CAT, NULL TABLE_SCHEM, A.T... | Retrieves a description of the given table's primary key columns. They are ordered by
COLUMN_NAME.
<P>Each primary key column description has the following columns:</p>
<OL>
<li><B>TABLE_CAT</B> String {@code =>} table catalog </li>
<li><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)</li>
<li><B>TABLE_NAME</B> String {@code =>} table name </li>
<li><B>COLUMN_NAME</B> String {@code =>} column name </li>
<li><B>KEY_SEQ</B> short {@code =>} sequence number within primary key( a value of 1
represents the first column of the primary key, a value of 2 would represent the second column
within the primary key).</li>
<li><B>PK_NAME</B> String {@code =>} primary key name </li>
</OL>
@param catalog a catalog name; must match the catalog name as it is stored in the database; ""
retrieves those without a catalog;
<code>null</code> means that the catalog name should not be used to narrow the
search
@param schema a schema name; must match the schema name as it is stored in the database; ""
retrieves those without a schema; <code>null</code> means that the schema name
should not be used to narrow the search
@param table a table name; must match the table name as it is stored in the database
@return <code>ResultSet</code> - each row is a primary key column description
@throws SQLException if a database access error occurs | [
"Retrieves",
"a",
"description",
"of",
"the",
"given",
"table",
"s",
"primary",
"key",
"columns",
".",
"They",
"are",
"ordered",
"by",
"COLUMN_NAME",
"."
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java#L555-L574 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/asn1/x509/X509DefaultEntryConverter.java | X509DefaultEntryConverter.getConvertedValue | public DERObject getConvertedValue(
DERObjectIdentifier oid,
String value)
{
if (value.length() != 0 && value.charAt(0) == '#')
{
try
{
return convertHexEncoded(value, 1);
}
catch (IOException e)
{
throw new RuntimeException("can't recode value for oid " + oid.getId(), e);
}
}
else if (oid.equals(X509Name.EmailAddress))
{
return new DERIA5String(value);
}
else if (canBePrintable(value))
{
return new DERPrintableString(value);
}
else if (canBeUTF8(value))
{
return new DERUTF8String(value);
}
return new DERBMPString(value);
} | java | public DERObject getConvertedValue(
DERObjectIdentifier oid,
String value)
{
if (value.length() != 0 && value.charAt(0) == '#')
{
try
{
return convertHexEncoded(value, 1);
}
catch (IOException e)
{
throw new RuntimeException("can't recode value for oid " + oid.getId(), e);
}
}
else if (oid.equals(X509Name.EmailAddress))
{
return new DERIA5String(value);
}
else if (canBePrintable(value))
{
return new DERPrintableString(value);
}
else if (canBeUTF8(value))
{
return new DERUTF8String(value);
}
return new DERBMPString(value);
} | [
"public",
"DERObject",
"getConvertedValue",
"(",
"DERObjectIdentifier",
"oid",
",",
"String",
"value",
")",
"{",
"if",
"(",
"value",
".",
"length",
"(",
")",
"!=",
"0",
"&&",
"value",
".",
"charAt",
"(",
"0",
")",
"==",
"'",
"'",
")",
"{",
"try",
"{"... | Apply default coversion for the given value depending on the oid
and the character range of the value.
@param oid the object identifier for the DN entry
@param value the value associated with it
@return the ASN.1 equivalent for the string value. | [
"Apply",
"default",
"coversion",
"for",
"the",
"given",
"value",
"depending",
"on",
"the",
"oid",
"and",
"the",
"character",
"range",
"of",
"the",
"value",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/asn1/x509/X509DefaultEntryConverter.java#L41-L70 |
lukas-krecan/JsonUnit | json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java | Configuration.withMatcher | public Configuration withMatcher(String matcherName, Matcher<?> matcher) {
return new Configuration(tolerance, options, ignorePlaceholder, matchers.with(matcherName, matcher), pathsToBeIgnored, differenceListener);
} | java | public Configuration withMatcher(String matcherName, Matcher<?> matcher) {
return new Configuration(tolerance, options, ignorePlaceholder, matchers.with(matcherName, matcher), pathsToBeIgnored, differenceListener);
} | [
"public",
"Configuration",
"withMatcher",
"(",
"String",
"matcherName",
",",
"Matcher",
"<",
"?",
">",
"matcher",
")",
"{",
"return",
"new",
"Configuration",
"(",
"tolerance",
",",
"options",
",",
"ignorePlaceholder",
",",
"matchers",
".",
"with",
"(",
"matche... | Adds a matcher to be used in ${json-unit.matches:matcherName} macro.
@param matcherName
@param matcher
@return | [
"Adds",
"a",
"matcher",
"to",
"be",
"used",
"in",
"$",
"{",
"json",
"-",
"unit",
".",
"matches",
":",
"matcherName",
"}",
"macro",
"."
] | train | https://github.com/lukas-krecan/JsonUnit/blob/2b12ed792e8dd787bddd6f3b8eb2325737435791/json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java#L142-L144 |
DDTH/ddth-commons | ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateFormatUtils.java | DateFormatUtils.fromString | public static Date fromString(String source, String format) {
try {
ObjectPool<DateFormat> pool = cachedDateFormat.get(format);
try {
DateFormat df = pool.borrowObject();
try {
return df.parse(source);
} finally {
pool.returnObject(df);
}
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e
: new RuntimeException(e);
}
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
} | java | public static Date fromString(String source, String format) {
try {
ObjectPool<DateFormat> pool = cachedDateFormat.get(format);
try {
DateFormat df = pool.borrowObject();
try {
return df.parse(source);
} finally {
pool.returnObject(df);
}
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e
: new RuntimeException(e);
}
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"Date",
"fromString",
"(",
"String",
"source",
",",
"String",
"format",
")",
"{",
"try",
"{",
"ObjectPool",
"<",
"DateFormat",
">",
"pool",
"=",
"cachedDateFormat",
".",
"get",
"(",
"format",
")",
";",
"try",
"{",
"DateFormat",
"df",
... | Parse a string to {@link Date}, based on the specified {@code format}.
@param source
@param format
@return | [
"Parse",
"a",
"string",
"to",
"{",
"@link",
"Date",
"}",
"based",
"on",
"the",
"specified",
"{",
"@code",
"format",
"}",
"."
] | train | https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateFormatUtils.java#L158-L175 |
jdereg/java-util | src/main/java/com/cedarsoftware/util/MapUtilities.java | MapUtilities.get | public static <T> T get(Map map, String key, T def) {
Object val = map.get(key);
return val == null ? def : (T)val;
} | java | public static <T> T get(Map map, String key, T def) {
Object val = map.get(key);
return val == null ? def : (T)val;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"get",
"(",
"Map",
"map",
",",
"String",
"key",
",",
"T",
"def",
")",
"{",
"Object",
"val",
"=",
"map",
".",
"get",
"(",
"key",
")",
";",
"return",
"val",
"==",
"null",
"?",
"def",
":",
"(",
"T",
")",
... | Retrieves a value from a map by key
@param map Map to retrieve item from
@param key the key whose associated value is to be returned
@param def value to return if item was not found.
@return Returns a string value that was found at the location key.
If the item is null then the def value is sent back.
If the item is not the expected type, an exception is thrown.
@exception ClassCastException if the item found is not
a the expected type. | [
"Retrieves",
"a",
"value",
"from",
"a",
"map",
"by",
"key"
] | train | https://github.com/jdereg/java-util/blob/a2dce61aed16d6454ee575174dda1ba6bff0015c/src/main/java/com/cedarsoftware/util/MapUtilities.java#L47-L50 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/query/Criteria.java | Criteria.addIn | public void addIn(Object attribute, Query subQuery)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias()));
addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getUserAlias(attribute)));
} | java | public void addIn(Object attribute, Query subQuery)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias()));
addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getUserAlias(attribute)));
} | [
"public",
"void",
"addIn",
"(",
"Object",
"attribute",
",",
"Query",
"subQuery",
")",
"{",
"// PAW\r",
"// addSelectionCriteria(ValueCriteria.buildInCriteria(attribute, subQuery, getAlias()));\r",
"addSelectionCriteria",
"(",
"ValueCriteria",
".",
"buildInCriteria",
"(",
"attri... | IN Criteria with SubQuery
@param attribute The field name to be used
@param subQuery The subQuery | [
"IN",
"Criteria",
"with",
"SubQuery"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L841-L846 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/api/CloudStorageApi.java | CloudStorageApi.listFolders | public ExternalFolder listFolders(String accountId, String userId, String serviceId) throws ApiException {
return listFolders(accountId, userId, serviceId, null);
} | java | public ExternalFolder listFolders(String accountId, String userId, String serviceId) throws ApiException {
return listFolders(accountId, userId, serviceId, null);
} | [
"public",
"ExternalFolder",
"listFolders",
"(",
"String",
"accountId",
",",
"String",
"userId",
",",
"String",
"serviceId",
")",
"throws",
"ApiException",
"{",
"return",
"listFolders",
"(",
"accountId",
",",
"userId",
",",
"serviceId",
",",
"null",
")",
";",
"... | Retrieves a list of all the items in a specified folder from the specified cloud storage provider.
Retrieves a list of all the items in a specified folder from the specified cloud storage provider.
@param accountId The external account number (int) or account ID Guid. (required)
@param userId The user ID of the user being accessed. Generally this is the user ID of the authenticated user, but if the authenticated user is an Admin on the account, this may be another user the Admin user is accessing. (required)
@param serviceId The ID of the service to access. Valid values are the service name (\"Box\") or the numerical serviceId (\"4136\"). (required)
@return ExternalFolder | [
"Retrieves",
"a",
"list",
"of",
"all",
"the",
"items",
"in",
"a",
"specified",
"folder",
"from",
"the",
"specified",
"cloud",
"storage",
"provider",
".",
"Retrieves",
"a",
"list",
"of",
"all",
"the",
"items",
"in",
"a",
"specified",
"folder",
"from",
"the"... | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/CloudStorageApi.java#L522-L524 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/util/ByteConverter.java | ByteConverter.int2 | public static void int2(byte[] target, int idx, int value) {
target[idx + 0] = (byte) (value >>> 8);
target[idx + 1] = (byte) value;
} | java | public static void int2(byte[] target, int idx, int value) {
target[idx + 0] = (byte) (value >>> 8);
target[idx + 1] = (byte) value;
} | [
"public",
"static",
"void",
"int2",
"(",
"byte",
"[",
"]",
"target",
",",
"int",
"idx",
",",
"int",
"value",
")",
"{",
"target",
"[",
"idx",
"+",
"0",
"]",
"=",
"(",
"byte",
")",
"(",
"value",
">>>",
"8",
")",
";",
"target",
"[",
"idx",
"+",
... | Encodes a int value to the byte array.
@param target The byte array to encode to.
@param idx The starting index in the byte array.
@param value The value to encode. | [
"Encodes",
"a",
"int",
"value",
"to",
"the",
"byte",
"array",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/util/ByteConverter.java#L138-L141 |
alibaba/jstorm | jstorm-core/src/main/java/com/alibaba/jstorm/transactional/TransactionTopologyBuilder.java | TransactionTopologyBuilder.setBoltWithAck | public BoltDeclarer setBoltWithAck(String id, IRichBolt bolt, Number parallelismHint) {
return setBolt(id, new AckTransactionBolt(bolt), parallelismHint);
} | java | public BoltDeclarer setBoltWithAck(String id, IRichBolt bolt, Number parallelismHint) {
return setBolt(id, new AckTransactionBolt(bolt), parallelismHint);
} | [
"public",
"BoltDeclarer",
"setBoltWithAck",
"(",
"String",
"id",
",",
"IRichBolt",
"bolt",
",",
"Number",
"parallelismHint",
")",
"{",
"return",
"setBolt",
"(",
"id",
",",
"new",
"AckTransactionBolt",
"(",
"bolt",
")",
",",
"parallelismHint",
")",
";",
"}"
] | Build bolt to provide the compatibility with Storm's ack mechanism
@param id bolt Id
@param bolt
@return | [
"Build",
"bolt",
"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#L181-L183 |
eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java | HawkbitCommonUtil.getPollStatusToolTip | public static String getPollStatusToolTip(final PollStatus pollStatus, final VaadinMessageSource i18N) {
if (pollStatus != null && pollStatus.getLastPollDate() != null && pollStatus.isOverdue()) {
final TimeZone tz = SPDateTimeUtil.getBrowserTimeZone();
return i18N.getMessage(UIMessageIdProvider.TOOLTIP_OVERDUE, SPDateTimeUtil.getDurationFormattedString(
pollStatus.getOverdueDate().atZone(SPDateTimeUtil.getTimeZoneId(tz)).toInstant().toEpochMilli(),
pollStatus.getCurrentDate().atZone(SPDateTimeUtil.getTimeZoneId(tz)).toInstant().toEpochMilli(),
i18N));
}
return null;
} | java | public static String getPollStatusToolTip(final PollStatus pollStatus, final VaadinMessageSource i18N) {
if (pollStatus != null && pollStatus.getLastPollDate() != null && pollStatus.isOverdue()) {
final TimeZone tz = SPDateTimeUtil.getBrowserTimeZone();
return i18N.getMessage(UIMessageIdProvider.TOOLTIP_OVERDUE, SPDateTimeUtil.getDurationFormattedString(
pollStatus.getOverdueDate().atZone(SPDateTimeUtil.getTimeZoneId(tz)).toInstant().toEpochMilli(),
pollStatus.getCurrentDate().atZone(SPDateTimeUtil.getTimeZoneId(tz)).toInstant().toEpochMilli(),
i18N));
}
return null;
} | [
"public",
"static",
"String",
"getPollStatusToolTip",
"(",
"final",
"PollStatus",
"pollStatus",
",",
"final",
"VaadinMessageSource",
"i18N",
")",
"{",
"if",
"(",
"pollStatus",
"!=",
"null",
"&&",
"pollStatus",
".",
"getLastPollDate",
"(",
")",
"!=",
"null",
"&&"... | Get tool tip for Poll status.
@param pollStatus
@param i18N
@return PollStatusToolTip | [
"Get",
"tool",
"tip",
"for",
"Poll",
"status",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java#L165-L174 |
taimos/RESTUtils | src/main/java/de/taimos/restutils/RESTAssert.java | RESTAssert.assertPattern | public static void assertPattern(String string, String pattern, final StatusType status) {
RESTAssert.assertNotNull(string);
RESTAssert.assertNotNull(pattern);
RESTAssert.assertTrue(string.matches(pattern), status);
} | java | public static void assertPattern(String string, String pattern, final StatusType status) {
RESTAssert.assertNotNull(string);
RESTAssert.assertNotNull(pattern);
RESTAssert.assertTrue(string.matches(pattern), status);
} | [
"public",
"static",
"void",
"assertPattern",
"(",
"String",
"string",
",",
"String",
"pattern",
",",
"final",
"StatusType",
"status",
")",
"{",
"RESTAssert",
".",
"assertNotNull",
"(",
"string",
")",
";",
"RESTAssert",
".",
"assertNotNull",
"(",
"pattern",
")"... | assert that string matches the given pattern
@param string the string to check
@param status the status code to throw
@throws WebApplicationException with given status code | [
"assert",
"that",
"string",
"matches",
"the",
"given",
"pattern"
] | train | https://github.com/taimos/RESTUtils/blob/bdb1bf9a2eb13ede0eec6f071c10cb2698313501/src/main/java/de/taimos/restutils/RESTAssert.java#L300-L304 |
comapi/comapi-sdk-android | COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java | InternalService.addParticipants | public void addParticipants(@NonNull final String conversationId, @NonNull final List<Participant> participants, @Nullable Callback<ComapiResult<Void>> callback) {
adapter.adapt(addParticipants(conversationId, participants), callback);
} | java | public void addParticipants(@NonNull final String conversationId, @NonNull final List<Participant> participants, @Nullable Callback<ComapiResult<Void>> callback) {
adapter.adapt(addParticipants(conversationId, participants), callback);
} | [
"public",
"void",
"addParticipants",
"(",
"@",
"NonNull",
"final",
"String",
"conversationId",
",",
"@",
"NonNull",
"final",
"List",
"<",
"Participant",
">",
"participants",
",",
"@",
"Nullable",
"Callback",
"<",
"ComapiResult",
"<",
"Void",
">",
">",
"callbac... | Returns observable to add a list of participants to a conversation.
@param conversationId ID of a conversation to update.
@param participants New conversation participants details.
@param callback Callback to deliver new session instance. | [
"Returns",
"observable",
"to",
"add",
"a",
"list",
"of",
"participants",
"to",
"a",
"conversation",
"."
] | train | https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java#L686-L688 |
jsonld-java/jsonld-java | core/src/main/java/com/github/jsonldjava/core/JsonLdProcessor.java | JsonLdProcessor.fromRDF | public static Object fromRDF(Object dataset, JsonLdOptions options) throws JsonLdError {
// handle non specified serializer case
RDFParser parser = null;
if (options.format == null && dataset instanceof String) {
// attempt to parse the input as nquads
options.format = JsonLdConsts.APPLICATION_NQUADS;
}
if (rdfParsers.containsKey(options.format)) {
parser = rdfParsers.get(options.format);
} else {
throw new JsonLdError(JsonLdError.Error.UNKNOWN_FORMAT, options.format);
}
// convert from RDF
return fromRDF(dataset, options, parser);
} | java | public static Object fromRDF(Object dataset, JsonLdOptions options) throws JsonLdError {
// handle non specified serializer case
RDFParser parser = null;
if (options.format == null && dataset instanceof String) {
// attempt to parse the input as nquads
options.format = JsonLdConsts.APPLICATION_NQUADS;
}
if (rdfParsers.containsKey(options.format)) {
parser = rdfParsers.get(options.format);
} else {
throw new JsonLdError(JsonLdError.Error.UNKNOWN_FORMAT, options.format);
}
// convert from RDF
return fromRDF(dataset, options, parser);
} | [
"public",
"static",
"Object",
"fromRDF",
"(",
"Object",
"dataset",
",",
"JsonLdOptions",
"options",
")",
"throws",
"JsonLdError",
"{",
"// handle non specified serializer case",
"RDFParser",
"parser",
"=",
"null",
";",
"if",
"(",
"options",
".",
"format",
"==",
"n... | Converts an RDF dataset to JSON-LD.
@param dataset
a serialized string of RDF in a format specified by the format
option or an RDF dataset to convert.
@param options
the options to use: [format] the format if input is not an
array: 'application/nquads' for N-Quads (default).
[useRdfType] true to use rdf:type, false to use @type
(default: false). [useNativeTypes] true to convert XSD types
into native types (boolean, integer, double), false not to
(default: true).
@return A JSON-LD object.
@throws JsonLdError
If there is an error converting the dataset to JSON-LD. | [
"Converts",
"an",
"RDF",
"dataset",
"to",
"JSON",
"-",
"LD",
"."
] | train | https://github.com/jsonld-java/jsonld-java/blob/efeef6ee96029a0011649633457035fa6be42da1/core/src/main/java/com/github/jsonldjava/core/JsonLdProcessor.java#L384-L402 |
openengsb/openengsb | api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java | TransformationDescription.instantiateField | public void instantiateField(String targetField, String targetType, String targetTypeInit, String... sourceFields) {
TransformationStep step = new TransformationStep();
step.setSourceFields(sourceFields);
step.setTargetField(targetField);
step.setOperationParameter(TransformationConstants.INSTANTIATE_TARGETTYPE_PARAM, targetType);
if (targetTypeInit != null) {
step.setOperationParameter(TransformationConstants.INSTANTIATE_INITMETHOD_PARAM, targetTypeInit);
}
step.setOperationName("instantiate");
steps.add(step);
} | java | public void instantiateField(String targetField, String targetType, String targetTypeInit, String... sourceFields) {
TransformationStep step = new TransformationStep();
step.setSourceFields(sourceFields);
step.setTargetField(targetField);
step.setOperationParameter(TransformationConstants.INSTANTIATE_TARGETTYPE_PARAM, targetType);
if (targetTypeInit != null) {
step.setOperationParameter(TransformationConstants.INSTANTIATE_INITMETHOD_PARAM, targetTypeInit);
}
step.setOperationName("instantiate");
steps.add(step);
} | [
"public",
"void",
"instantiateField",
"(",
"String",
"targetField",
",",
"String",
"targetType",
",",
"String",
"targetTypeInit",
",",
"String",
"...",
"sourceFields",
")",
"{",
"TransformationStep",
"step",
"=",
"new",
"TransformationStep",
"(",
")",
";",
"step",... | Adds an instantiate step to the transformation description. An object defined through the given target type will
be created. For the instantiation the targetTypeInit method will be used. If this parameter is null, the
constructor of the targetType will be used with the object type of the source object as parameter. | [
"Adds",
"an",
"instantiate",
"step",
"to",
"the",
"transformation",
"description",
".",
"An",
"object",
"defined",
"through",
"the",
"given",
"target",
"type",
"will",
"be",
"created",
".",
"For",
"the",
"instantiation",
"the",
"targetTypeInit",
"method",
"will"... | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java#L275-L285 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.