_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q165100 | GeneralRange.reverse | validation | GeneralRange<T> reverse() {
GeneralRange<T> result = reverse;
if (result == null) {
result =
new GeneralRange<T>(
Ordering.from(comparator).reverse(),
hasUpperBound,
getUpperEndpoint(),
getUpperBoundType(),
hasLowerBound,
getLowerEndpoint(),
getLowerBoundType());
result.reverse = this;
return this.reverse = result;
}
return result;
} | java | {
"resource": ""
} |
q165101 | ImmutableSet.unsafeDelegate | validation | static <E> ImmutableSet<E> unsafeDelegate(Set<E> delegate) {
switch (delegate.size()) {
case 0:
return of();
case 1:
return new SingletonImmutableSet<E>(delegate.iterator().next());
default:
return new RegularImmutableSet<E>(delegate);
}
} | java | {
"resource": ""
} |
q165102 | ImmutableTypeToInstanceMap.of | validation | public static <B> ImmutableTypeToInstanceMap<B> of() {
return new ImmutableTypeToInstanceMap<B>(ImmutableMap.<TypeToken<? extends B>, B>of());
} | java | {
"resource": ""
} |
q165103 | CycleDetectingLockFactory.aboutToAcquire | validation | private void aboutToAcquire(CycleDetectingLock lock) {
if (!lock.isAcquiredByCurrentThread()) {
ArrayList<LockGraphNode> acquiredLockList = acquiredLocks.get();
LockGraphNode node = lock.getLockGraphNode();
node.checkAcquiredLocks(policy, acquiredLockList);
acquiredLockList.add(node);
}
} | java | {
"resource": ""
} |
q165104 | ImmutableRangeSet.subRangeSet | validation | @Override
public ImmutableRangeSet<C> subRangeSet(Range<C> range) {
if (!isEmpty()) {
Range<C> span = span();
if (range.encloses(span)) {
return this;
} else if (range.isConnected(span)) {
return new ImmutableRangeSet<C>(intersectRanges(range));
}
}
return of();
} | java | {
"resource": ""
} |
q165105 | RegularImmutableMap.makeImmutable | validation | static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry, K key, V value) {
boolean reusable =
entry instanceof ImmutableMapEntry && ((ImmutableMapEntry<K, V>) entry).isReusable();
return reusable ? (ImmutableMapEntry<K, V>) entry : new ImmutableMapEntry<K, V>(key, value);
} | java | {
"resource": ""
} |
q165106 | RegularImmutableMap.makeImmutable | validation | static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry) {
return makeImmutable(entry, entry.getKey(), entry.getValue());
} | java | {
"resource": ""
} |
q165107 | Escapers.wrap | validation | private static UnicodeEscaper wrap(final CharEscaper escaper) {
return new UnicodeEscaper() {
@Override
protected char[] escape(int cp) {
// If a code point maps to a single character, just escape that.
if (cp < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
return escaper.escape((char) cp);
}
// Convert the code point to a surrogate pair and escape them both.
// Note: This code path is horribly slow and typically allocates 4 new
// char[] each time it is invoked. However this avoids any
// synchronization issues and makes the escaper thread safe.
char[] surrogateChars = new char[2];
Character.toChars(cp, surrogateChars, 0);
char[] hiChars = escaper.escape(surrogateChars[0]);
char[] loChars = escaper.escape(surrogateChars[1]);
// If either hiChars or lowChars are non-null, the CharEscaper is trying
// to escape the characters of a surrogate pair separately. This is
// uncommon and applies only to escapers that assume UCS-2 rather than
// UTF-16. See: http://en.wikipedia.org/wiki/UTF-16/UCS-2
if (hiChars == null && loChars == null) {
// We expect this to be the common code path for most escapers.
return null;
}
// Combine the characters and/or escaped sequences into a single array.
int hiCount = hiChars != null ? hiChars.length : 1;
int loCount = loChars != null ? loChars.length : 1;
char[] output = new char[hiCount + loCount];
if (hiChars != null) {
// TODO: Is this faster than System.arraycopy() for small arrays?
for (int n = 0; n < hiChars.length; ++n) {
output[n] = hiChars[n];
}
} else {
output[0] = surrogateChars[0];
}
if (loChars != null) {
for (int n = 0; n < loChars.length; ++n) {
output[hiCount + n] = loChars[n];
}
} else {
output[hiCount] = surrogateChars[1];
}
return output;
}
};
} | java | {
"resource": ""
} |
q165108 | PairedStatsAccumulator.add | validation | public void add(double x, double y) {
// We extend the recursive expression for the one-variable case at Art of Computer Programming
// vol. 2, Knuth, 4.2.2, (16) to the two-variable case. We have two value series x_i and y_i.
// We define the arithmetic means X_n = 1/n \sum_{i=1}^n x_i, and Y_n = 1/n \sum_{i=1}^n y_i.
// We also define the sum of the products of the differences from the means
// C_n = \sum_{i=1}^n x_i y_i - n X_n Y_n
// for all n >= 1. Then for all n > 1:
// C_{n-1} = \sum_{i=1}^{n-1} x_i y_i - (n-1) X_{n-1} Y_{n-1}
// C_n - C_{n-1} = x_n y_n - n X_n Y_n + (n-1) X_{n-1} Y_{n-1}
// = x_n y_n - X_n [ y_n + (n-1) Y_{n-1} ] + [ n X_n - x_n ] Y_{n-1}
// = x_n y_n - X_n y_n - x_n Y_{n-1} + X_n Y_{n-1}
// = (x_n - X_n) (y_n - Y_{n-1})
xStats.add(x);
if (isFinite(x) && isFinite(y)) {
if (xStats.count() > 1) {
sumOfProductsOfDeltas += (x - xStats.mean()) * (y - yStats.mean());
}
} else {
sumOfProductsOfDeltas = NaN;
}
yStats.add(y);
} | java | {
"resource": ""
} |
q165109 | ImmutableBiMap.of | validation | public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) {
checkEntryNotNull(k1, v1);
return new RegularImmutableBiMap<>(new Object[] {k1, v1}, 1);
} | java | {
"resource": ""
} |
q165110 | ImmutableBiMap.copyOf | validation | @Beta
public static <K, V> ImmutableBiMap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
int estimatedSize =
(entries instanceof Collection)
? ((Collection<?>) entries).size()
: ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY;
return new Builder<K, V>(estimatedSize).putAll(entries).build();
} | java | {
"resource": ""
} |
q165111 | Functions.identity | validation | @SuppressWarnings("unchecked")
public static <E> Function<E, E> identity() {
return (Function<E, E>) IdentityFunction.INSTANCE;
} | java | {
"resource": ""
} |
q165112 | Functions.forPredicate | validation | public static <T> Function<T, Boolean> forPredicate(Predicate<T> predicate) {
return new PredicateFunction<T>(predicate);
} | java | {
"resource": ""
} |
q165113 | LocalCache.unset | validation | @SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <K, V> ValueReference<K, V> unset() {
return (ValueReference<K, V>) UNSET;
} | java | {
"resource": ""
} |
q165114 | LocalCache.isExpired | validation | boolean isExpired(ReferenceEntry<K, V> entry, long now) {
checkNotNull(entry);
if (expiresAfterAccess() && (now - entry.getAccessTime() >= expireAfterAccessNanos)) {
return true;
}
if (expiresAfterWrite() && (now - entry.getWriteTime() >= expireAfterWriteNanos)) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q165115 | RateLimiter.reserveAndGetWaitLength | validation | final long reserveAndGetWaitLength(int permits, long nowMicros) {
long momentAvailable = reserveEarliestAvailable(permits, nowMicros);
return max(momentAvailable - nowMicros, 0);
} | java | {
"resource": ""
} |
q165116 | UnicodeEscaper.codePointAt | validation | protected static int codePointAt(CharSequence seq, int index, int end) {
checkNotNull(seq);
if (index < end) {
char c1 = seq.charAt(index++);
if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) {
// Fast path (first test is probably all we need to do)
return c1;
} else if (c1 <= Character.MAX_HIGH_SURROGATE) {
// If the high surrogate was the last character, return its inverse
if (index == end) {
return -c1;
}
// Otherwise look for the low surrogate following it
char c2 = seq.charAt(index);
if (Character.isLowSurrogate(c2)) {
return Character.toCodePoint(c1, c2);
}
throw new IllegalArgumentException(
"Expected low surrogate but got char '"
+ c2
+ "' with value "
+ (int) c2
+ " at index "
+ index
+ " in '"
+ seq
+ "'");
} else {
throw new IllegalArgumentException(
"Unexpected low surrogate character '"
+ c1
+ "' with value "
+ (int) c1
+ " at index "
+ (index - 1)
+ " in '"
+ seq
+ "'");
}
}
throw new IndexOutOfBoundsException("Index exceeds specified range");
} | java | {
"resource": ""
} |
q165117 | HashBiMap.ensureCapacity | validation | private void ensureCapacity(int minCapacity) {
if (nextInBucketKToV.length < minCapacity) {
int oldCapacity = nextInBucketKToV.length;
int newCapacity = ImmutableCollection.Builder.expandedCapacity(oldCapacity, minCapacity);
keys = Arrays.copyOf(keys, newCapacity);
values = Arrays.copyOf(values, newCapacity);
nextInBucketKToV = expandAndFillWithAbsent(nextInBucketKToV, newCapacity);
nextInBucketVToK = expandAndFillWithAbsent(nextInBucketVToK, newCapacity);
prevInInsertionOrder = expandAndFillWithAbsent(prevInInsertionOrder, newCapacity);
nextInInsertionOrder = expandAndFillWithAbsent(nextInInsertionOrder, newCapacity);
}
if (hashTableKToV.length < minCapacity) {
int newTableSize = Hashing.closedTableSize(minCapacity, 1.0);
hashTableKToV = createFilledWithAbsent(newTableSize);
hashTableVToK = createFilledWithAbsent(newTableSize);
for (int entryToRehash = 0; entryToRehash < size; entryToRehash++) {
int keyHash = Hashing.smearedHash(keys[entryToRehash]);
int keyBucket = bucket(keyHash);
nextInBucketKToV[entryToRehash] = hashTableKToV[keyBucket];
hashTableKToV[keyBucket] = entryToRehash;
int valueHash = Hashing.smearedHash(values[entryToRehash]);
int valueBucket = bucket(valueHash);
nextInBucketVToK[entryToRehash] = hashTableVToK[valueBucket];
hashTableVToK[valueBucket] = entryToRehash;
}
}
} | java | {
"resource": ""
} |
q165118 | HashBiMap.insertIntoTableKToV | validation | private void insertIntoTableKToV(int entry, int keyHash) {
checkArgument(entry != ABSENT);
int keyBucket = bucket(keyHash);
nextInBucketKToV[entry] = hashTableKToV[keyBucket];
hashTableKToV[keyBucket] = entry;
} | java | {
"resource": ""
} |
q165119 | HashBiMap.insertIntoTableVToK | validation | private void insertIntoTableVToK(int entry, int valueHash) {
checkArgument(entry != ABSENT);
int valueBucket = bucket(valueHash);
nextInBucketVToK[entry] = hashTableVToK[valueBucket];
hashTableVToK[valueBucket] = entry;
} | java | {
"resource": ""
} |
q165120 | HashBiMap.deleteFromTableKToV | validation | private void deleteFromTableKToV(int entry, int keyHash) {
checkArgument(entry != ABSENT);
int keyBucket = bucket(keyHash);
if (hashTableKToV[keyBucket] == entry) {
hashTableKToV[keyBucket] = nextInBucketKToV[entry];
nextInBucketKToV[entry] = ABSENT;
return;
}
int prevInBucket = hashTableKToV[keyBucket];
for (int entryInBucket = nextInBucketKToV[prevInBucket];
entryInBucket != ABSENT;
entryInBucket = nextInBucketKToV[entryInBucket]) {
if (entryInBucket == entry) {
nextInBucketKToV[prevInBucket] = nextInBucketKToV[entry];
nextInBucketKToV[entry] = ABSENT;
return;
}
prevInBucket = entryInBucket;
}
throw new AssertionError("Expected to find entry with key " + keys[entry]);
} | java | {
"resource": ""
} |
q165121 | HashBiMap.deleteFromTableVToK | validation | private void deleteFromTableVToK(int entry, int valueHash) {
checkArgument(entry != ABSENT);
int valueBucket = bucket(valueHash);
if (hashTableVToK[valueBucket] == entry) {
hashTableVToK[valueBucket] = nextInBucketVToK[entry];
nextInBucketVToK[entry] = ABSENT;
return;
}
int prevInBucket = hashTableVToK[valueBucket];
for (int entryInBucket = nextInBucketVToK[prevInBucket];
entryInBucket != ABSENT;
entryInBucket = nextInBucketVToK[entryInBucket]) {
if (entryInBucket == entry) {
nextInBucketVToK[prevInBucket] = nextInBucketVToK[entry];
nextInBucketVToK[entry] = ABSENT;
return;
}
prevInBucket = entryInBucket;
}
throw new AssertionError("Expected to find entry with value " + values[entry]);
} | java | {
"resource": ""
} |
q165122 | HashBiMap.removeEntry | validation | private void removeEntry(int entry, int keyHash, int valueHash) {
checkArgument(entry != ABSENT);
deleteFromTableKToV(entry, keyHash);
deleteFromTableVToK(entry, valueHash);
int oldPredecessor = prevInInsertionOrder[entry];
int oldSuccessor = nextInInsertionOrder[entry];
setSucceeds(oldPredecessor, oldSuccessor);
moveEntryToIndex(size - 1, entry);
keys[size - 1] = null;
values[size - 1] = null;
size--;
modCount++;
} | java | {
"resource": ""
} |
q165123 | HashBiMap.removeEntryKeyHashKnown | validation | void removeEntryKeyHashKnown(int entry, int keyHash) {
removeEntry(entry, keyHash, Hashing.smearedHash(values[entry]));
} | java | {
"resource": ""
} |
q165124 | HashBiMap.removeEntryValueHashKnown | validation | void removeEntryValueHashKnown(int entry, int valueHash) {
removeEntry(entry, Hashing.smearedHash(keys[entry]), valueHash);
} | java | {
"resource": ""
} |
q165125 | NetworkBuilder.expectedNodeCount | validation | public NetworkBuilder<N, E> expectedNodeCount(int expectedNodeCount) {
this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
return this;
} | java | {
"resource": ""
} |
q165126 | NetworkBuilder.expectedEdgeCount | validation | public NetworkBuilder<N, E> expectedEdgeCount(int expectedEdgeCount) {
this.expectedEdgeCount = Optional.of(checkNonNegative(expectedEdgeCount));
return this;
} | java | {
"resource": ""
} |
q165127 | CallableStatementInformation.getSqlWithValues | validation | @Override
public String getSqlWithValues() {
if( namedParameterValues.size() == 0 ) {
return super.getSqlWithValues();
}
/*
If named parameters were used, it is no longer possible to simply replace the placeholders in the
original statement with the values of the bind variables. The only way it could be done is if the names
could be resolved by to the ordinal positions which is not possible on all databases.
New log format: <original statement> name:value, name:value
Example: {? = call test_proc(?,?)} param1:value1, param2:value2, param3:value3
In the event that ordinal and named parameters are both used, the original position will be used as the name.
Example: {? = call test_proc(?,?)} 1:value1, 3:value3, param2:value2
*/
final StringBuilder result = new StringBuilder();
final String statementQuery = getStatementQuery();
// first append the original statement
result.append(statementQuery);
result.append(" ");
StringBuilder parameters = new StringBuilder();
// add parameters set with ordinal positions
for( Map.Entry<Integer, Value> entry : getParameterValues().entrySet() ) {
appendParameter(parameters, entry.getKey().toString(), entry.getValue());
}
// add named parameters
for( Map.Entry<String, Value> entry : namedParameterValues.entrySet() ) {
appendParameter(parameters, entry.getKey(), entry.getValue());
}
result.append(parameters);
return result.toString();
} | java | {
"resource": ""
} |
q165128 | CallableStatementInformation.setParameterValue | validation | public void setParameterValue(final String name, final Object value) {
namedParameterValues.put(name, new Value(value));
} | java | {
"resource": ""
} |
q165129 | SqlUtils.objectToBlob | validation | public static byte[] objectToBlob(Object o) {
try {
return SerializerContext.getInstance().serialize(o);
} catch (SerializerException e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q165130 | SqlUtils.blobToObject | validation | public static <T> T blobToObject(byte[] blob, Class<T> type) {
try {
return SerializerContext.getInstance().deSerialize(blob, type);
} catch (SerializerException e) {
throw new IllegalStateException(e);
}
} | java | {
"resource": ""
} |
q165131 | TxcServiceImpl.lockDataLine | validation | private void lockDataLine(String groupId, String unitId, Set<String> lockIdSet, boolean isXLock) throws TxcLogicException {
try {
if (!reliableMessenger.acquireLocks(groupId, lockIdSet, isXLock ? DTXLocks.X_LOCK : DTXLocks.S_LOCK)) {
throw new TxcLogicException("resource is locked! place try again later.");
}
globalContext.addTxcLockId(groupId, unitId, lockIdSet);
} catch (RpcException e) {
throw new TxcLogicException("can't contact to any TM for lock info. default error.");
}
} | java | {
"resource": ""
} |
q165132 | TxcServiceImpl.saveUndoLog | validation | private void saveUndoLog(String groupId, String unitId, int sqlType, TableRecordList recordList) throws TxcLogicException {
UndoLogDO undoLogDO = new UndoLogDO();
undoLogDO.setRollbackInfo(SqlUtils.objectToBlob(recordList));
undoLogDO.setUnitId(unitId);
undoLogDO.setGroupId(groupId);
undoLogDO.setSqlType(sqlType);
try {
txcLogHelper.saveUndoLog(undoLogDO);
} catch (SQLException e) {
throw new TxcLogicException(e);
}
} | java | {
"resource": ""
} |
q165133 | RedisConfiguration.functionDomainRedisTemplate | validation | @Bean
@ConditionalOnClass(name = "org.springframework.data.redis.connection.RedisConnectionFactory")
public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
JdkSerializationRedisSerializer serializationRedisSerializer = new JdkSerializationRedisSerializer();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setHashValueSerializer(serializationRedisSerializer);
redisTemplate.setValueSerializer(serializationRedisSerializer);
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
} | java | {
"resource": ""
} |
q165134 | TracingContext.appMapString | validation | public String appMapString() {
if (hasGroup()) {
String appMap = Optional.ofNullable(this.fields.get(TracingConstants.APP_MAP)).orElse("");
log.debug("App map: {}", appMap);
return appMap;
}
raiseNonGroupException();
return "{}";
} | java | {
"resource": ""
} |
q165135 | P6Util.locateOnClassPath | validation | public static URL locateOnClassPath(String filename) {
URL result;
// first try to load from context class loader
result = Thread.currentThread().getContextClassLoader().getResource(filename);
// next try the current class loader which loaded p6spy
if (result == null) {
result = P6Util.class.getClassLoader().getResource(filename);
}
// finally try the system class loader
if (result == null) {
result = ClassLoader.getSystemResource(filename);
}
return result;
} | java | {
"resource": ""
} |
q165136 | ConnectionInformation.fromConnection | validation | public static ConnectionInformation fromConnection(Connection connection) {
final ConnectionInformation connectionInformation = new ConnectionInformation();
connectionInformation.connection = connection;
return connectionInformation;
} | java | {
"resource": ""
} |
q165137 | ExceptionToResourceMapping.mapThrowable | validation | public Integer mapThrowable(final Throwable throwable) {
Throwable throwableToCheck = throwable;
int depthToGo = 20;
while (true) {
Integer resId = mapThrowableFlat(throwableToCheck);
if (resId != null) {
return resId;
} else {
throwableToCheck = throwableToCheck.getCause();
depthToGo--;
if (depthToGo <= 0 || throwableToCheck == throwable || throwableToCheck == null) {
Log.d("EventBus", "No specific message resource ID found for " + throwable);
// return config.defaultErrorMsgId;
return null;
}
}
}
} | java | {
"resource": ""
} |
q165138 | EventBusAnnotationProcessor.checkForSubscribersToSkip | validation | private void checkForSubscribersToSkip(Messager messager, String myPackage) {
for (TypeElement skipCandidate : methodsByClass.keySet()) {
TypeElement subscriberClass = skipCandidate;
while (subscriberClass != null) {
if (!isVisible(myPackage, subscriberClass)) {
boolean added = classesToSkip.add(skipCandidate);
if (added) {
String msg;
if (subscriberClass.equals(skipCandidate)) {
msg = "Falling back to reflection because class is not public";
} else {
msg = "Falling back to reflection because " + skipCandidate +
" has a non-public super class";
}
messager.printMessage(Diagnostic.Kind.NOTE, msg, subscriberClass);
}
break;
}
List<ExecutableElement> methods = methodsByClass.get(subscriberClass);
if (methods != null) {
for (ExecutableElement method : methods) {
String skipReason = null;
VariableElement param = method.getParameters().get(0);
TypeMirror typeMirror = getParamTypeMirror(param, messager);
if (!(typeMirror instanceof DeclaredType) ||
!(((DeclaredType) typeMirror).asElement() instanceof TypeElement)) {
skipReason = "event type cannot be processed";
}
if (skipReason == null) {
TypeElement eventTypeElement = (TypeElement) ((DeclaredType) typeMirror).asElement();
if (!isVisible(myPackage, eventTypeElement)) {
skipReason = "event type is not public";
}
}
if (skipReason != null) {
boolean added = classesToSkip.add(skipCandidate);
if (added) {
String msg = "Falling back to reflection because " + skipReason;
if (!subscriberClass.equals(skipCandidate)) {
msg += " (found in super class for " + skipCandidate + ")";
}
messager.printMessage(Diagnostic.Kind.NOTE, msg, param);
}
break;
}
}
}
subscriberClass = getSuperclass(subscriberClass);
}
}
} | java | {
"resource": ""
} |
q165139 | EventBus.getDefault | validation | public static EventBus getDefault() {
EventBus instance = defaultInstance;
if (instance == null) {
synchronized (EventBus.class) {
instance = EventBus.defaultInstance;
if (instance == null) {
instance = EventBus.defaultInstance = new EventBus();
}
}
}
return instance;
} | java | {
"resource": ""
} |
q165140 | EventBus.subscribe | validation | private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
subscriptions.add(i, newSubscription);
break;
}
}
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
if (subscriberMethod.sticky) {
if (eventInheritance) {
// Existing sticky events of all subclasses of eventType have to be considered.
// Note: Iterating over all events may be inefficient with lots of sticky events,
// thus data structure should be changed to allow a more efficient lookup
// (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
for (Map.Entry<Class<?>, Object> entry : entries) {
Class<?> candidateEventType = entry.getKey();
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} | java | {
"resource": ""
} |
q165141 | EventBus.unsubscribeByEventType | validation | private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
} | java | {
"resource": ""
} |
q165142 | EventBus.unregister | validation | public synchronized void unregister(Object subscriber) {
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
typesBySubscriber.remove(subscriber);
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
} | java | {
"resource": ""
} |
q165143 | EventBus.post | validation | public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
if (!postingState.isPosting) {
postingState.isMainThread = isMainThread();
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
} | java | {
"resource": ""
} |
q165144 | EventBus.getStickyEvent | validation | public <T> T getStickyEvent(Class<T> eventType) {
synchronized (stickyEvents) {
return eventType.cast(stickyEvents.get(eventType));
}
} | java | {
"resource": ""
} |
q165145 | EventBus.removeStickyEvent | validation | public <T> T removeStickyEvent(Class<T> eventType) {
synchronized (stickyEvents) {
return eventType.cast(stickyEvents.remove(eventType));
}
} | java | {
"resource": ""
} |
q165146 | EventBus.removeStickyEvent | validation | public boolean removeStickyEvent(Object event) {
synchronized (stickyEvents) {
Class<?> eventType = event.getClass();
Object existingEvent = stickyEvents.get(eventType);
if (event.equals(existingEvent)) {
stickyEvents.remove(eventType);
return true;
} else {
return false;
}
}
} | java | {
"resource": ""
} |
q165147 | EventBus.lookupAllEventTypes | validation | private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
synchronized (eventTypesCache) {
List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
if (eventTypes == null) {
eventTypes = new ArrayList<>();
Class<?> clazz = eventClass;
while (clazz != null) {
eventTypes.add(clazz);
addInterfaces(eventTypes, clazz.getInterfaces());
clazz = clazz.getSuperclass();
}
eventTypesCache.put(eventClass, eventTypes);
}
return eventTypes;
}
} | java | {
"resource": ""
} |
q165148 | EventBus.addInterfaces | validation | static void addInterfaces(List<Class<?>> eventTypes, Class<?>[] interfaces) {
for (Class<?> interfaceClass : interfaces) {
if (!eventTypes.contains(interfaceClass)) {
eventTypes.add(interfaceClass);
addInterfaces(eventTypes, interfaceClass.getInterfaces());
}
}
} | java | {
"resource": ""
} |
q165149 | EventBusBuilder.addIndex | validation | public EventBusBuilder addIndex(SubscriberInfoIndex index) {
if (subscriberInfoIndexes == null) {
subscriberInfoIndexes = new ArrayList<>();
}
subscriberInfoIndexes.add(index);
return this;
} | java | {
"resource": ""
} |
q165150 | ErrorDialogManager.attachTo | validation | public static void attachTo(Activity activity, boolean finishAfterDialog, Bundle argumentsForErrorDialog) {
Object executionScope = activity.getClass();
attachTo(activity, executionScope, finishAfterDialog, argumentsForErrorDialog);
} | java | {
"resource": ""
} |
q165151 | ErrorDialogFragmentFactory.prepareErrorFragment | validation | protected T prepareErrorFragment(ThrowableFailureEvent event, boolean finishAfterDialog,
Bundle argumentsForErrorDialog) {
if (event.isSuppressErrorUi()) {
// Show nothing by default
return null;
}
Bundle bundle;
if (argumentsForErrorDialog != null) {
bundle = (Bundle) argumentsForErrorDialog.clone();
} else {
bundle = new Bundle();
}
if (!bundle.containsKey(ErrorDialogManager.KEY_TITLE)) {
String title = getTitleFor(event, bundle);
bundle.putString(ErrorDialogManager.KEY_TITLE, title);
}
if (!bundle.containsKey(ErrorDialogManager.KEY_MESSAGE)) {
String message = getMessageFor(event, bundle);
bundle.putString(ErrorDialogManager.KEY_MESSAGE, message);
}
if (!bundle.containsKey(ErrorDialogManager.KEY_FINISH_AFTER_DIALOG)) {
bundle.putBoolean(ErrorDialogManager.KEY_FINISH_AFTER_DIALOG, finishAfterDialog);
}
if (!bundle.containsKey(ErrorDialogManager.KEY_EVENT_TYPE_ON_CLOSE)
&& config.defaultEventTypeOnDialogClosed != null) {
bundle.putSerializable(ErrorDialogManager.KEY_EVENT_TYPE_ON_CLOSE, config.defaultEventTypeOnDialogClosed);
}
if (!bundle.containsKey(ErrorDialogManager.KEY_ICON_ID) && config.defaultDialogIconId != 0) {
bundle.putInt(ErrorDialogManager.KEY_ICON_ID, config.defaultDialogIconId);
}
return createErrorFragment(event, bundle);
} | java | {
"resource": ""
} |
q165152 | ErrorDialogFragmentFactory.getTitleFor | validation | protected String getTitleFor(ThrowableFailureEvent event, Bundle arguments) {
return config.resources.getString(config.defaultTitleId);
} | java | {
"resource": ""
} |
q165153 | ErrorDialogFragmentFactory.getMessageFor | validation | protected String getMessageFor(ThrowableFailureEvent event, Bundle arguments) {
int msgResId = config.getMessageIdForThrowable(event.throwable);
return config.resources.getString(msgResId);
} | java | {
"resource": ""
} |
q165154 | DrainUtils.postCompleteDrain | validation | static <T, F> boolean postCompleteDrain(long n,
Subscriber<? super T> actual,
Queue<T> queue,
AtomicLongFieldUpdater<F> field,
F instance,
BooleanSupplier isCancelled) {
// TODO enable fast-path
// if (n == -1 || n == Long.MAX_VALUE) {
// for (;;) {
// if (isDisposed.getAsBoolean()) {
// break;
// }
//
// T v = queue.poll();
//
// if (v == null) {
// actual.onComplete();
// break;
// }
//
// actual.onNext(v);
// }
//
// return true;
// }
long e = n & COMPLETED_MASK;
for (; ; ) {
while (e != n) {
if (isCancelled.getAsBoolean()) {
return true;
}
T t = queue.poll();
if (t == null) {
actual.onComplete();
return true;
}
actual.onNext(t);
e++;
}
if (isCancelled.getAsBoolean()) {
return true;
}
if (queue.isEmpty()) {
actual.onComplete();
return true;
}
n = field.get(instance);
if (n == e) {
n = field.addAndGet(instance, -(e & REQUESTED_MASK));
if ((n & REQUESTED_MASK) == 0L) {
return false;
}
e = n & COMPLETED_MASK;
}
}
} | java | {
"resource": ""
} |
q165155 | BlockingSingleSubscriber.blockingGet | validation | @Nullable
final T blockingGet(long timeout, TimeUnit unit) {
if (Schedulers.isInNonBlockingThread()) {
throw new IllegalStateException("block()/blockFirst()/blockLast() are blocking, which is not supported in thread " + Thread.currentThread().getName());
}
if (getCount() != 0) {
try {
if (!await(timeout, unit)) {
dispose();
throw new IllegalStateException("Timeout on blocking read for " + timeout + " " + unit);
}
}
catch (InterruptedException ex) {
dispose();
RuntimeException re = Exceptions.propagate(ex);
//this is ok, as re is always a new non-singleton instance
re.addSuppressed(new Exception("#block has been interrupted"));
throw re;
}
}
Throwable e = error;
if (e != null) {
RuntimeException re = Exceptions.propagate(e);
//this is ok, as re is always a new non-singleton instance
re.addSuppressed(new Exception("#block terminated with an error"));
throw re;
}
return value;
} | java | {
"resource": ""
} |
q165156 | Flux.elementAt | validation | public final Mono<T> elementAt(int index, T defaultValue) {
return Mono.onAssembly(new MonoElementAt<>(this, index, defaultValue));
} | java | {
"resource": ""
} |
q165157 | Flux.onErrorResume | validation | public final Flux<T> onErrorResume(Function<? super Throwable, ? extends Publisher<? extends T>> fallback) {
return onAssembly(new FluxOnErrorResume<>(this, fallback));
} | java | {
"resource": ""
} |
q165158 | Flux.repeat | validation | public final Flux<T> repeat(long numRepeat, BooleanSupplier predicate) {
if (numRepeat < 0L) {
throw new IllegalArgumentException("numRepeat >= 0 required");
}
if (numRepeat == 0) {
return this;
}
return defer( () -> repeat(countingBooleanSupplier(predicate, numRepeat)));
} | java | {
"resource": ""
} |
q165159 | Flux.convertToMono | validation | static <T> Mono<T> convertToMono(Callable<T> supplier) {
if (supplier instanceof Fuseable.ScalarCallable) {
Fuseable.ScalarCallable<T> scalarCallable = (Fuseable.ScalarCallable<T>) supplier;
T v;
try {
v = scalarCallable.call();
}
catch (Exception e) {
return Mono.error(e);
}
if (v == null) {
return Mono.empty();
}
return Mono.just(v);
}
return Mono.onAssembly(new MonoCallable<>(supplier));
} | java | {
"resource": ""
} |
q165160 | EventLoopProcessor.getAndSub | validation | static long getAndSub(RingBuffer.Sequence sequence, long toSub) {
long r, u;
do {
r = sequence.getAsLong();
if (r == 0 || r == Long.MAX_VALUE) {
return r;
}
u = Operators.subOrZero(r, toSub);
}
while (!sequence.compareAndSet(r, u));
return r;
} | java | {
"resource": ""
} |
q165161 | Operators.as | validation | @SuppressWarnings("unchecked")
@Nullable
public static <T> QueueSubscription<T> as(Subscription s) {
if (s instanceof QueueSubscription) {
return (QueueSubscription<T>) s;
}
return null;
} | java | {
"resource": ""
} |
q165162 | Operators.error | validation | public static void error(Subscriber<?> s, Throwable e) {
s.onSubscribe(EmptySubscription.INSTANCE);
s.onError(e);
} | java | {
"resource": ""
} |
q165163 | Operators.produced | validation | public static <T> long produced(AtomicLongFieldUpdater<T> updater, T instance, long toSub) {
long r, u;
do {
r = updater.get(instance);
if (r == 0 || r == Long.MAX_VALUE) {
return r;
}
u = subOrZero(r, toSub);
} while (!updater.compareAndSet(instance, r, u));
return u;
} | java | {
"resource": ""
} |
q165164 | Operators.scalarSubscription | validation | public static <T> Subscription scalarSubscription(CoreSubscriber<? super T> subscriber,
T value){
return new ScalarSubscription<>(subscriber, value);
} | java | {
"resource": ""
} |
q165165 | MonoIgnoreThen.shift | validation | <U> MonoIgnoreThen<U> shift(Mono<U> newLast) {
Objects.requireNonNull(newLast, "newLast");
Publisher<?>[] a = ignore;
int n = a.length;
Publisher<?>[] b = new Publisher[n + 1];
System.arraycopy(a, 0, b, 0, n);
b[n] = last;
return new MonoIgnoreThen<>(b, newLast);
} | java | {
"resource": ""
} |
q165166 | WaitStrategy.phasedOffSleep | validation | public static WaitStrategy phasedOffSleep(long spinTimeout, long yieldTimeout, TimeUnit units) {
return phasedOff(spinTimeout, yieldTimeout, units, parking(0));
} | java | {
"resource": ""
} |
q165167 | Mono.and | validation | public final Mono<Void> and(Publisher<?> other) {
if (this instanceof MonoWhen) {
@SuppressWarnings("unchecked") MonoWhen o = (MonoWhen) this;
Mono<Void> result = o.whenAdditionalSource(other);
if (result != null) {
return result;
}
}
return when(this, other);
} | java | {
"resource": ""
} |
q165168 | Mono.defaultIfEmpty | validation | public final Mono<T> defaultIfEmpty(T defaultV) {
if (this instanceof Fuseable.ScalarCallable) {
try {
T v = block();
if (v == null) {
return Mono.just(defaultV);
}
}
catch (Throwable e) {
//leave MonoError returns as this
}
return this;
}
return onAssembly(new MonoDefaultIfEmpty<>(this, defaultV));
} | java | {
"resource": ""
} |
q165169 | Mono.or | validation | public final Mono<T> or(Mono<? extends T> other) {
if (this instanceof MonoFirst) {
MonoFirst<T> a = (MonoFirst<T>) this;
Mono<T> result = a.orAdditionalSource(other);
if (result != null) {
return result;
}
}
return first(this, other);
} | java | {
"resource": ""
} |
q165170 | Mono.onErrorResume | validation | public final Mono<T> onErrorResume(Function<? super Throwable, ? extends Mono<? extends
T>> fallback) {
return onAssembly(new MonoOnErrorResume<>(this, fallback));
} | java | {
"resource": ""
} |
q165171 | Hooks.getOnEachOperatorHooks | validation | static final Map<String, Function<? super Publisher<Object>, ? extends Publisher<Object>>> getOnEachOperatorHooks() {
return Collections.unmodifiableMap(onEachOperatorHooks);
} | java | {
"resource": ""
} |
q165172 | MonoDelayUntil.copyWithNewTriggerGenerator | validation | @SuppressWarnings("unchecked")
MonoDelayUntil<T> copyWithNewTriggerGenerator(boolean delayError,
Function<? super T, ? extends Publisher<?>> triggerGenerator) {
Objects.requireNonNull(triggerGenerator, "triggerGenerator");
Function<? super T, ? extends Publisher<?>>[] oldTriggers = this.otherGenerators;
Function<? super T, ? extends Publisher<?>>[] newTriggers = new Function[oldTriggers.length + 1];
System.arraycopy(oldTriggers, 0, newTriggers, 0, oldTriggers.length);
newTriggers[oldTriggers.length] = triggerGenerator;
return new MonoDelayUntil<>(this.source, newTriggers);
} | java | {
"resource": ""
} |
q165173 | QueueDrainSubscriber.drainMaxLoop | validation | static <Q, S> void drainMaxLoop(Queue<Q> q, Subscriber<? super S> a, boolean delayError,
Disposable dispose, QueueDrainSubscriber<?, Q, S> qd) {
int missed = 1;
for (;;) {
for (;;) {
boolean d = qd.done();
Q v = q.poll();
boolean empty = v == null;
if (checkTerminated(d, empty, a, delayError, q, qd)) {
if (dispose != null) {
dispose.dispose();
}
return;
}
if (empty) {
break;
}
long r = qd.requested();
if (r != 0L) {
if (qd.accept(a, v)) {
if (r != Long.MAX_VALUE) {
qd.produced(1);
}
}
} else {
q.clear();
if (dispose != null) {
dispose.dispose();
}
a.onError(Exceptions.failWithOverflow("Could not emit value due to lack of requests."));
return;
}
}
missed = qd.leave(-missed);
if (missed == 0) {
break;
}
}
} | java | {
"resource": ""
} |
q165174 | FluxFlatMap.trySubscribeScalarMap | validation | @SuppressWarnings("unchecked")
static <T, R> boolean trySubscribeScalarMap(Publisher<? extends T> source,
CoreSubscriber<? super R> s,
Function<? super T, ? extends Publisher<? extends R>> mapper,
boolean fuseableExpected) {
if (source instanceof Callable) {
T t;
try {
t = ((Callable<? extends T>) source).call();
}
catch (Throwable e) {
Operators.error(s, Operators.onOperatorError(e, s.currentContext()));
return true;
}
if (t == null) {
Operators.complete(s);
return true;
}
Publisher<? extends R> p;
try {
p = Objects.requireNonNull(mapper.apply(t),
"The mapper returned a null Publisher");
}
catch (Throwable e) {
Operators.error(s, Operators.onOperatorError(null, e, t, s.currentContext()));
return true;
}
if (p instanceof Callable) {
R v;
try {
v = ((Callable<R>) p).call();
}
catch (Throwable e) {
Operators.error(s, Operators.onOperatorError(null, e, t, s.currentContext()));
return true;
}
if (v != null) {
s.onSubscribe(Operators.scalarSubscription(s, v));
}
else {
Operators.complete(s);
}
}
else {
if (!fuseableExpected || p instanceof Fuseable) {
p.subscribe(s);
}
else {
p.subscribe(new FluxHide.SuppressFuseableSubscriber<>(s));
}
}
return true;
}
return false;
} | java | {
"resource": ""
} |
q165175 | ParallelFlux.as | validation | public final <U> U as(Function<? super ParallelFlux<T>, U> converter) {
return converter.apply(this);
} | java | {
"resource": ""
} |
q165176 | ParallelFlux.collect | validation | public final <C> ParallelFlux<C> collect(Supplier<? extends C> collectionSupplier,
BiConsumer<? super C, ? super T> collector) {
return onAssembly(new ParallelCollect<>(this, collectionSupplier, collector));
} | java | {
"resource": ""
} |
q165177 | ParallelFlux.concatMap | validation | public final <R> ParallelFlux<R> concatMap(Function<? super T, ? extends Publisher<? extends R>> mapper) {
return concatMap(mapper, 2, ErrorMode.IMMEDIATE);
} | java | {
"resource": ""
} |
q165178 | ParallelFlux.doOnCancel | validation | public final ParallelFlux<T> doOnCancel(Runnable onCancel) {
Objects.requireNonNull(onCancel, "onCancel");
return doOnSignal(this, null, null, null, null, null, null, null, onCancel);
} | java | {
"resource": ""
} |
q165179 | ParallelFlux.doOnComplete | validation | public final ParallelFlux<T> doOnComplete(Runnable onComplete) {
Objects.requireNonNull(onComplete, "onComplete");
return doOnSignal(this, null, null, null, onComplete, null, null, null, null);
} | java | {
"resource": ""
} |
q165180 | ParallelFlux.doOnError | validation | public final ParallelFlux<T> doOnError(Consumer<? super Throwable> onError) {
Objects.requireNonNull(onError, "onError");
return doOnSignal(this, null, null, onError, null, null, null, null, null);
} | java | {
"resource": ""
} |
q165181 | ParallelFlux.doOnRequest | validation | public final ParallelFlux<T> doOnRequest(LongConsumer onRequest) {
Objects.requireNonNull(onRequest, "onRequest");
return doOnSignal(this, null, null, null, null, null, null, onRequest, null);
} | java | {
"resource": ""
} |
q165182 | ParallelFlux.flatMap | validation | public final <R> ParallelFlux<R> flatMap(Function<? super T, ? extends Publisher<? extends R>> mapper,
boolean delayError,
int maxConcurrency,
int prefetch) {
return onAssembly(new ParallelFlatMap<>(this,
mapper,
delayError,
maxConcurrency,
Queues.get(maxConcurrency),
prefetch, Queues.get(prefetch)));
} | java | {
"resource": ""
} |
q165183 | ParallelFlux.sequential | validation | public final Flux<T> sequential(int prefetch) {
return Flux.onAssembly(new ParallelMergeSequential<>(this,
prefetch,
Queues.get(prefetch)));
} | java | {
"resource": ""
} |
q165184 | ParallelFlux.validate | validation | protected final boolean validate(Subscriber<?>[] subscribers) {
int p = parallelism();
if (subscribers.length != p) {
IllegalArgumentException iae = new IllegalArgumentException("parallelism = " +
"" + p + ", subscribers = " + subscribers.length);
for (Subscriber<?> s : subscribers) {
Operators.error(s, iae);
}
return false;
}
return true;
} | java | {
"resource": ""
} |
q165185 | ParallelFlux.concatMap | validation | final <R> ParallelFlux<R> concatMap(Function<? super T, ? extends Publisher<? extends R>> mapper,
int prefetch,
ErrorMode errorMode) {
return onAssembly(new ParallelConcatMap<>(this,
mapper,
Queues.get(prefetch),
prefetch,
errorMode));
} | java | {
"resource": ""
} |
q165186 | ParallelFlux.concatMapDelayError | validation | final <R> ParallelFlux<R> concatMapDelayError(Function<? super T, ? extends
Publisher<? extends R>> mapper,
boolean delayUntilEnd,
int prefetch) {
return concatMap(mapper, prefetch, delayUntilEnd ? ErrorMode.END: ErrorMode.BOUNDARY);
} | java | {
"resource": ""
} |
q165187 | Exceptions.terminate | validation | @Nullable
public static <T> Throwable terminate(AtomicReferenceFieldUpdater<T, Throwable> field,
T instance) {
Throwable current = field.get(instance);
if (current != TERMINATED) {
current = field.getAndSet(instance, TERMINATED);
}
return current;
} | java | {
"resource": ""
} |
q165188 | SignalLogger.log | validation | void log(SignalType signalType, Object signalValue) {
String line = fuseable ? LOG_TEMPLATE_FUSEABLE : LOG_TEMPLATE;
if (operatorLine != null) {
line = line + " " + operatorLine;
}
if (level == Level.FINEST) {
log.trace(line, signalType, signalValue);
}
else if (level == Level.FINE) {
log.debug(line, signalType, signalValue);
}
else if (level == Level.INFO) {
log.info(line, signalType, signalValue);
}
else if (level == Level.WARNING) {
log.warn(line, signalType, signalValue);
}
else if (level == Level.SEVERE) {
log.error(line, signalType, signalValue);
}
} | java | {
"resource": ""
} |
q165189 | FileDownloader.start | validation | public boolean start(final FileDownloadListener listener, final boolean isSerial) {
if (listener == null) {
FileDownloadLog.w(this, "Tasks with the listener can't start, because the listener "
+ "provided is null: [null, %B]", isSerial);
return false;
}
return isSerial
? getQueuesHandler().startQueueSerial(listener)
: getQueuesHandler().startQueueParallel(listener);
} | java | {
"resource": ""
} |
q165190 | FileDownloader.pauseAll | validation | public void pauseAll() {
FileDownloadTaskLauncher.getImpl().expireAll();
final BaseDownloadTask.IRunningTask[] downloadList = FileDownloadList.getImpl().copy();
for (BaseDownloadTask.IRunningTask task : downloadList) {
task.getOrigin().pause();
}
// double check, for case: File Download progress alive but ui progress has died and relived
// so FileDownloadList not always contain all running task exactly.
if (FileDownloadServiceProxy.getImpl().isConnected()) {
FileDownloadServiceProxy.getImpl().pauseAllTasks();
} else {
PauseAllMarker.createMarker();
}
} | java | {
"resource": ""
} |
q165191 | FileDownloader.getSoFar | validation | public long getSoFar(final int downloadId) {
BaseDownloadTask.IRunningTask task = FileDownloadList.getImpl().get(downloadId);
if (task == null) {
return FileDownloadServiceProxy.getImpl().getSofar(downloadId);
}
return task.getOrigin().getLargeFileSoFarBytes();
} | java | {
"resource": ""
} |
q165192 | FileDownloader.unBindServiceIfIdle | validation | public boolean unBindServiceIfIdle() {
// check idle
if (!isServiceConnected()) {
return false;
}
if (FileDownloadList.getImpl().isEmpty()
&& FileDownloadServiceProxy.getImpl().isIdle()) {
unBindService();
return true;
}
return false;
} | java | {
"resource": ""
} |
q165193 | FileDownloader.setMaxNetworkThreadCount | validation | public boolean setMaxNetworkThreadCount(final int count) {
if (!FileDownloadList.getImpl().isEmpty()) {
FileDownloadLog.w(this, "Can't change the max network thread count, because there "
+ "are actively executing tasks in FileDownloader, please try again after all"
+ " actively executing tasks are completed or invoking FileDownloader#pauseAll"
+ " directly.");
return false;
}
return FileDownloadServiceProxy.getImpl().setMaxNetworkThreadCount(count);
} | java | {
"resource": ""
} |
q165194 | FileDownloadManager.pauseAll | validation | public void pauseAll() {
List<Integer> list = mThreadPool.getAllExactRunningDownloadIds();
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.d(this, "pause all tasks %d", list.size());
}
for (Integer id : list) {
pause(id);
}
} | java | {
"resource": ""
} |
q165195 | FileDownloadQueueSet.start | validation | public void start() {
for (BaseDownloadTask task : tasks) {
task.setListener(target);
if (autoRetryTimes != null) {
task.setAutoRetryTimes(autoRetryTimes);
}
if (syncCallback != null) {
task.setSyncCallback(syncCallback);
}
if (isForceReDownload != null) {
task.setForceReDownload(isForceReDownload);
}
if (callbackProgressTimes != null) {
task.setCallbackProgressTimes(callbackProgressTimes);
}
if (callbackProgressMinIntervalMillis != null) {
task.setCallbackProgressMinInterval(callbackProgressMinIntervalMillis);
}
if (tag != null) {
task.setTag(tag);
}
if (taskFinishListenerList != null) {
for (BaseDownloadTask.FinishListener finishListener : taskFinishListenerList) {
task.addFinishListener(finishListener);
}
}
if (this.directory != null) {
task.setPath(this.directory, true);
}
if (this.isWifiRequired != null) {
task.setWifiRequired(this.isWifiRequired);
}
task.asInQueueTask().enqueue();
}
FileDownloader.getImpl().start(target, isSerial);
} | java | {
"resource": ""
} |
q165196 | FileDownloadList.divertAndIgnoreDuplicate | validation | void divertAndIgnoreDuplicate(
@SuppressWarnings("SameParameterValue") final List<BaseDownloadTask.IRunningTask>
destination) {
synchronized (mList) {
for (BaseDownloadTask.IRunningTask iRunningTask : mList) {
if (!destination.contains(iRunningTask)) {
destination.add(iRunningTask);
}
}
mList.clear();
}
} | java | {
"resource": ""
} |
q165197 | FileDownloadList.addUnchecked | validation | void addUnchecked(final BaseDownloadTask.IRunningTask task) {
if (task.isMarkedAdded2List()) {
return;
}
synchronized (mList) {
if (mList.contains(task)) {
FileDownloadLog.w(this, "already has %s", task);
} else {
task.markAdded2List();
mList.add(task);
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.v(this, "add list in all %s %d %d", task,
task.getOrigin().getStatus(), mList.size());
}
}
}
} | java | {
"resource": ""
} |
q165198 | FileDownloadSerialQueue.pause | validation | public void pause() {
synchronized (finishCallback) {
if (paused) {
FileDownloadLog.w(this, "require pause this queue(remain %d), but "
+ "it has already been paused", mTasks.size());
return;
}
paused = true;
mTasks.drainTo(pausedList);
if (workingTask != null) {
workingTask.removeFinishListener(finishCallback);
workingTask.pause();
}
}
} | java | {
"resource": ""
} |
q165199 | FileDownloadSerialQueue.resume | validation | public void resume() {
synchronized (finishCallback) {
if (!paused) {
FileDownloadLog.w(this, "require resume this queue(remain %d), but it is"
+ " still running", mTasks.size());
return;
}
paused = false;
mTasks.addAll(pausedList);
pausedList.clear();
if (workingTask == null) {
sendNext();
} else {
workingTask.addFinishListener(finishCallback);
workingTask.start();
}
}
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.