_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q165000
TypeCapture.capture
validation
final Type capture() { Type superclass = getClass().getGenericSuperclass(); checkArgument(superclass instanceof ParameterizedType, "%s isn't parameterized", superclass); return ((ParameterizedType) superclass).getActualTypeArguments()[0]; }
java
{ "resource": "" }
q165001
Sets.removeAllImpl
validation
static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) { boolean changed = false; while (iterator.hasNext()) { changed |= set.remove(iterator.next()); } return changed; }
java
{ "resource": "" }
q165002
CharEscaper.escape
validation
@Override public String escape(String string) { checkNotNull(string); // GWT specific check (do not optimize) // Inlineable fast-path loop which hands off to escapeSlow() only if needed int length = string.length(); for (int index = 0; index < length; index++) { if (escape(string.charAt(index)) != null) { return escapeSlow(string, index); } } return string; }
java
{ "resource": "" }
q165003
CharEscaper.growBuffer
validation
private static char[] growBuffer(char[] dest, int index, int size) { if (size < 0) { // overflow - should be OutOfMemoryError but GWT/j2cl don't support it throw new AssertionError("Cannot increase internal buffer any further"); } char[] copy = new char[size]; if (index > 0) { System.arraycopy(dest, 0, copy, 0, index); } return copy; }
java
{ "resource": "" }
q165004
CacheBuilder.concurrencyLevel
validation
public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) { checkState( this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s", this.concurrencyLevel); checkArgument(concurrencyLevel > 0); this.concurrencyLevel = concurrencyLevel; return this; }
java
{ "resource": "" }
q165005
CacheBuilder.build
validation
public <K1 extends K, V1 extends V> Cache<K1, V1> build() { checkWeightWithWeigher(); checkNonLoadingCache(); return new LocalCache.LocalManualCache<>(this); }
java
{ "resource": "" }
q165006
CompactHashMap.allocArrays
validation
void allocArrays() { Preconditions.checkState(needsAllocArrays(), "Arrays already allocated"); int expectedSize = modCount; int buckets = Hashing.closedTableSize(expectedSize, LOAD_FACTOR); this.table = newTable(buckets); this.entries = newEntries(expectedSize); this.keys = new Object[expectedSize]; this.values = new Object[expectedSize]; }
java
{ "resource": "" }
q165007
StatsAccumulator.add
validation
public void add(double value) { if (count == 0) { count = 1; mean = value; min = value; max = value; if (!isFinite(value)) { sumOfSquaresOfDeltas = NaN; } } else { count++; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) and (16) double delta = value - mean; mean += delta / count; sumOfSquaresOfDeltas += delta * (value - mean); } else { mean = calculateNewMeanNonFinite(mean, value); sumOfSquaresOfDeltas = NaN; } min = Math.min(min, value); max = Math.max(max, value); } }
java
{ "resource": "" }
q165008
StatsAccumulator.calculateNewMeanNonFinite
validation
static double calculateNewMeanNonFinite(double previousMean, double value) { /* * Desired behaviour is to match the results of applying the naive mean formula. In particular, * the update formula can subtract infinities in cases where the naive formula would add them. * * Consequently: * 1. If the previous mean is finite and the new value is non-finite then the new mean is that * value (whether it is NaN or infinity). * 2. If the new value is finite and the previous mean is non-finite then the mean is unchanged * (whether it is NaN or infinity). * 3. If both the previous mean and the new value are non-finite and... * 3a. ...either or both is NaN (so mean != value) then the new mean is NaN. * 3b. ...they are both the same infinities (so mean == value) then the mean is unchanged. * 3c. ...they are different infinities (so mean != value) then the new mean is NaN. */ if (isFinite(previousMean)) { // This is case 1. return value; } else if (isFinite(value) || previousMean == value) { // This is case 2. or 3b. return previousMean; } else { // This is case 3a. or 3c. return NaN; } }
java
{ "resource": "" }
q165009
ImmutableSet.rebuildHashTable
validation
static Object[] rebuildHashTable(int newTableSize, Object[] elements, int n) { Object[] hashTable = new Object[newTableSize]; int mask = hashTable.length - 1; for (int i = 0; i < n; i++) { Object e = elements[i]; int j0 = Hashing.smear(e.hashCode()); for (int j = j0; ; j++) { int index = j & mask; if (hashTable[index] == null) { hashTable[index] = e; break; } } } return hashTable; }
java
{ "resource": "" }
q165010
ImmutableSet.chooseTableSize
validation
@VisibleForTesting static int chooseTableSize(int setSize) { setSize = Math.max(setSize, 2); // Correct the size for open addressing to match desired load factor. if (setSize < CUTOFF) { // Round up to the next highest power of 2. int tableSize = Integer.highestOneBit(setSize - 1) << 1; while (tableSize * DESIRED_LOAD_FACTOR < setSize) { tableSize <<= 1; } return tableSize; } // The table can't be completely full or we'll get infinite reprobes checkArgument(setSize < MAX_TABLE_SIZE, "collection too large"); return MAX_TABLE_SIZE; }
java
{ "resource": "" }
q165011
ImmutableTable.of
validation
@SuppressWarnings("unchecked") public static <R, C, V> ImmutableTable<R, C, V> of() { return (ImmutableTable<R, C, V>) SparseImmutableTable.EMPTY; }
java
{ "resource": "" }
q165012
ImmutableTable.of
validation
public static <R, C, V> ImmutableTable<R, C, V> of(R rowKey, C columnKey, V value) { return new SingletonImmutableTable<>(rowKey, columnKey, value); }
java
{ "resource": "" }
q165013
ImmutableTable.copyOf
validation
public static <R, C, V> ImmutableTable<R, C, V> copyOf( Table<? extends R, ? extends C, ? extends V> table) { if (table instanceof ImmutableTable) { @SuppressWarnings("unchecked") ImmutableTable<R, C, V> parameterizedTable = (ImmutableTable<R, C, V>) table; return parameterizedTable; } else { return copyOf(table.cellSet()); } }
java
{ "resource": "" }
q165014
Converter.identity
validation
@SuppressWarnings("unchecked") // implementation is "fully variant" public static <T> Converter<T, T> identity() { return (IdentityConverter<T>) IdentityConverter.INSTANCE; }
java
{ "resource": "" }
q165015
RegularImmutableTable.forOrderedComponents
validation
static <R, C, V> RegularImmutableTable<R, C, V> forOrderedComponents( ImmutableList<Cell<R, C, V>> cellList, ImmutableSet<R> rowSpace, ImmutableSet<C> columnSpace) { // use a dense table if more than half of the cells have values // TODO(gak): tune this condition based on empirical evidence return (cellList.size() > (((long) rowSpace.size() * columnSpace.size()) / 2)) ? new DenseImmutableTable<R, C, V>(cellList, rowSpace, columnSpace) : new SparseImmutableTable<R, C, V>(cellList, rowSpace, columnSpace); }
java
{ "resource": "" }
q165016
ImmutableSortedMultiset.of
validation
public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E element) { RegularImmutableSortedSet<E> elementSet = (RegularImmutableSortedSet<E>) ImmutableSortedSet.of(element); long[] cumulativeCounts = {0, 1}; return new RegularImmutableSortedMultiset<E>(elementSet, cumulativeCounts, 0, 1); }
java
{ "resource": "" }
q165017
ImmutableSortedMultiset.reverseOrder
validation
public static <E extends Comparable<?>> Builder<E> reverseOrder() { return new Builder<E>(Ordering.natural().reverse()); }
java
{ "resource": "" }
q165018
Multisets.retainOccurrencesImpl
validation
private static <E> boolean retainOccurrencesImpl( Multiset<E> multisetToModify, Multiset<?> occurrencesToRetain) { checkNotNull(multisetToModify); checkNotNull(occurrencesToRetain); // Avoiding ConcurrentModificationExceptions is tricky. Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator(); boolean changed = false; while (entryIterator.hasNext()) { Entry<E> entry = entryIterator.next(); int retainCount = occurrencesToRetain.count(entry.getElement()); if (retainCount == 0) { entryIterator.remove(); changed = true; } else if (retainCount < entry.getCount()) { multisetToModify.setCount(entry.getElement(), retainCount); changed = true; } } return changed; }
java
{ "resource": "" }
q165019
TreeTraverser.preOrderTraversal
validation
@Deprecated public final FluentIterable<T> preOrderTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return preOrderIterator(root); } @Override public void forEach(Consumer<? super T> action) { checkNotNull(action); new Consumer<T>() { @Override public void accept(T t) { action.accept(t); children(t).forEach(this); } }.accept(root); } }; }
java
{ "resource": "" }
q165020
Collections2.newStringBuilderForCollection
validation
static StringBuilder newStringBuilderForCollection(int size) { checkNonnegative(size, "size"); return new StringBuilder((int) Math.min(size * 8L, Ints.MAX_POWER_OF_TWO)); }
java
{ "resource": "" }
q165021
TypeResolver.invariantly
validation
static TypeResolver invariantly(Type contextType) { Type invariantContext = WildcardCapturer.INSTANCE.capture(contextType); return new TypeResolver().where(TypeMappingIntrospector.getTypeMappings(invariantContext)); }
java
{ "resource": "" }
q165022
AbstractMapBasedMultimap.setMap
validation
final void setMap(Map<K, Collection<V>> map) { this.map = map; totalSize = 0; for (Collection<V> values : map.values()) { checkArgument(!values.isEmpty()); totalSize += values.size(); } }
java
{ "resource": "" }
q165023
AbstractMapBasedMultimap.removeValuesForKey
validation
private void removeValuesForKey(Object key) { Collection<V> collection = Maps.safeRemove(map, key); if (collection != null) { int count = collection.size(); collection.clear(); totalSize -= count; } }
java
{ "resource": "" }
q165024
FluentIterable.concatNoDefensiveCopy
validation
private static <T> FluentIterable<T> concatNoDefensiveCopy( final Iterable<? extends T>... inputs) { for (Iterable<? extends T> input : inputs) { checkNotNull(input); } return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.concat( /* lazily generate the iterators on each input only as needed */ new AbstractIndexedListIterator<Iterator<? extends T>>(inputs.length) { @Override public Iterator<? extends T> get(int i) { return inputs[i].iterator(); } }); } }; }
java
{ "resource": "" }
q165025
FluentIterable.of
validation
@Beta public static <E> FluentIterable<E> of() { return FluentIterable.from(ImmutableList.<E>of()); }
java
{ "resource": "" }
q165026
FluentIterable.toArray
validation
@GwtIncompatible // Array.newArray(Class, int) public final E[] toArray(Class<E> type) { return Iterables.toArray(getDelegate(), type); }
java
{ "resource": "" }
q165027
ImmutableMultimap.of
validation
public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2) { return ImmutableListMultimap.of(k1, v1, k2, v2); }
java
{ "resource": "" }
q165028
ImmutableMultimap.entries
validation
@Override public ImmutableCollection<Entry<K, V>> entries() { return (ImmutableCollection<Entry<K, V>>) super.entries(); }
java
{ "resource": "" }
q165029
ByteSource.countBySkipping
validation
private long countBySkipping(InputStream in) throws IOException { long count = 0; long skipped; while ((skipped = skipUpTo(in, Integer.MAX_VALUE)) > 0) { count += skipped; } return count; }
java
{ "resource": "" }
q165030
ByteSource.read
validation
public byte[] read() throws IOException { Closer closer = Closer.create(); try { InputStream in = closer.register(openStream()); Optional<Long> size = sizeIfKnown(); return size.isPresent() ? ByteStreams.toByteArray(in, size.get()) : ByteStreams.toByteArray(in); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
java
{ "resource": "" }
q165031
ByteSource.hash
validation
public HashCode hash(HashFunction hashFunction) throws IOException { Hasher hasher = hashFunction.newHasher(); copyTo(Funnels.asOutputStream(hasher)); return hasher.hash(); }
java
{ "resource": "" }
q165032
ByteSource.contentEquals
validation
public boolean contentEquals(ByteSource other) throws IOException { checkNotNull(other); byte[] buf1 = createBuffer(); byte[] buf2 = createBuffer(); Closer closer = Closer.create(); try { InputStream in1 = closer.register(openStream()); InputStream in2 = closer.register(other.openStream()); while (true) { int read1 = ByteStreams.read(in1, buf1, 0, buf1.length); int read2 = ByteStreams.read(in2, buf2, 0, buf2.length); if (read1 != read2 || !Arrays.equals(buf1, buf2)) { return false; } else if (read1 != buf1.length) { return true; } } } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
java
{ "resource": "" }
q165033
ImmutableRangeMap.of
validation
@SuppressWarnings("unchecked") public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> of() { return (ImmutableRangeMap<K, V>) EMPTY; }
java
{ "resource": "" }
q165034
ImmutableRangeMap.of
validation
public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> of(Range<K> range, V value) { return new ImmutableRangeMap<>(ImmutableList.of(range), ImmutableList.of(value)); }
java
{ "resource": "" }
q165035
Hashing.concatenating
validation
public static HashFunction concatenating( HashFunction first, HashFunction second, HashFunction... rest) { // We can't use Lists.asList() here because there's no hash->collect dependency List<HashFunction> list = new ArrayList<>(); list.add(first); list.add(second); list.addAll(Arrays.asList(rest)); return new ConcatenatedHashFunction(list.toArray(new HashFunction[0])); }
java
{ "resource": "" }
q165036
ImmutableSortedSet.of
validation
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E element) { return new RegularImmutableSortedSet<E>(ImmutableList.of(element), Ordering.natural()); }
java
{ "resource": "" }
q165037
ValueGraphBuilder.expectedNodeCount
validation
public ValueGraphBuilder<N, V> expectedNodeCount(int expectedNodeCount) { this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount)); return this; }
java
{ "resource": "" }
q165038
Comparators.lexicographical
validation
public static <T, S extends T> Comparator<Iterable<S>> lexicographical(Comparator<T> comparator) { return new LexicographicalOrdering<S>(checkNotNull(comparator)); }
java
{ "resource": "" }
q165039
Finalizer.startFinalizer
validation
public static void startFinalizer( Class<?> finalizableReferenceClass, ReferenceQueue<Object> queue, PhantomReference<Object> frqReference) { /* * We use FinalizableReference.class for two things: * * 1) To invoke FinalizableReference.finalizeReferent() * * 2) To detect when FinalizableReference's class loader has to be garbage collected, at which * point, Finalizer can stop running */ if (!finalizableReferenceClass.getName().equals(FINALIZABLE_REFERENCE)) { throw new IllegalArgumentException("Expected " + FINALIZABLE_REFERENCE + "."); } Finalizer finalizer = new Finalizer(finalizableReferenceClass, queue, frqReference); String threadName = Finalizer.class.getName(); Thread thread = null; if (bigThreadConstructor != null) { try { boolean inheritThreadLocals = false; long defaultStackSize = 0; thread = bigThreadConstructor.newInstance( (ThreadGroup) null, finalizer, threadName, defaultStackSize, inheritThreadLocals); } catch (Throwable t) { logger.log( Level.INFO, "Failed to create a thread without inherited thread-local values", t); } } if (thread == null) { thread = new Thread((ThreadGroup) null, finalizer, threadName); } thread.setDaemon(true); try { if (inheritableThreadLocals != null) { inheritableThreadLocals.set(thread, null); } } catch (Throwable t) { logger.log( Level.INFO, "Failed to clear thread local values inherited by reference finalizer thread.", t); } thread.start(); }
java
{ "resource": "" }
q165040
ImmutableSortedMap.of
validation
@SuppressWarnings("unchecked") // unsafe, comparator() returns a comparator on the specified type // TODO(kevinb): evaluate whether or not of().comparator() should return null public static <K, V> ImmutableSortedMap<K, V> of() { return (ImmutableSortedMap<K, V>) NATURAL_EMPTY_MAP; }
java
{ "resource": "" }
q165041
ImmutableSortedMap.of
validation
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(K k1, V v1) { return of(Ordering.natural(), k1, v1); }
java
{ "resource": "" }
q165042
ImmutableSortedMap.of
validation
@SuppressWarnings("unchecked") public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of( K k1, V v1, K k2, V v2) { return ofEntries(entryOf(k1, v1), entryOf(k2, v2)); }
java
{ "resource": "" }
q165043
ImmutableSortedMap.copyOfSorted
validation
@SuppressWarnings("unchecked") public static <K, V> ImmutableSortedMap<K, V> copyOfSorted(SortedMap<K, ? extends V> map) { Comparator<? super K> comparator = map.comparator(); if (comparator == null) { // If map has a null comparator, the keys should have a natural ordering, // even though K doesn't explicitly implement Comparable. comparator = (Comparator<? super K>) NATURAL_ORDER; } if (map instanceof ImmutableSortedMap) { // TODO(kevinb): Prove that this cast is safe, even though // Collections.unmodifiableSortedMap requires the same key type. @SuppressWarnings("unchecked") ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map; if (!kvMap.isPartialView()) { return kvMap; } } return fromEntries(comparator, true, map.entrySet()); }
java
{ "resource": "" }
q165044
FarmHashFingerprint64.weakHashLength32WithSeeds
validation
private static void weakHashLength32WithSeeds( byte[] bytes, int offset, long seedA, long seedB, long[] output) { long part1 = load64(bytes, offset); long part2 = load64(bytes, offset + 8); long part3 = load64(bytes, offset + 16); long part4 = load64(bytes, offset + 24); seedA += part1; seedB = rotateRight(seedB + seedA + part4, 21); long c = seedA; seedA += part2; seedA += part3; seedB += rotateRight(seedA, 44); output[0] = seedA + part4; output[1] = seedB + c; }
java
{ "resource": "" }
q165045
AbstractService.checkCurrentState
validation
@GuardedBy("monitor") private void checkCurrentState(State expected) { State actual = state(); if (actual != expected) { if (actual == FAILED) { // Handle this specially so that we can include the failureCause, if there is one. throw new IllegalStateException( "Expected the service " + this + " to be " + expected + ", but the service has FAILED", failureCause()); } throw new IllegalStateException( "Expected the service " + this + " to be " + expected + ", but was " + actual); } }
java
{ "resource": "" }
q165046
MoreFiles.listFiles
validation
public static ImmutableList<Path> listFiles(Path dir) throws IOException { try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { return ImmutableList.copyOf(stream); } catch (DirectoryIteratorException e) { throw e.getCause(); } }
java
{ "resource": "" }
q165047
MoreFiles.isDirectory
validation
private static boolean isDirectory( SecureDirectoryStream<Path> dir, Path name, LinkOption... options) throws IOException { return dir.getFileAttributeView(name, BasicFileAttributeView.class, options) .readAttributes() .isDirectory(); }
java
{ "resource": "" }
q165048
MoreFiles.equal
validation
public static boolean equal(Path path1, Path path2) throws IOException { checkNotNull(path1); checkNotNull(path2); if (Files.isSameFile(path1, path2)) { return true; } /* * Some operating systems may return zero as the length for files denoting system-dependent * entities such as devices or pipes, in which case we must fall back on comparing the bytes * directly. */ ByteSource source1 = asByteSource(path1); ByteSource source2 = asByteSource(path2); long len1 = source1.sizeIfKnown().or(0L); long len2 = source2.sizeIfKnown().or(0L); if (len1 != 0 && len2 != 0 && len1 != len2) { return false; } return source1.contentEquals(source2); }
java
{ "resource": "" }
q165049
MoreFiles.touch
validation
@SuppressWarnings("GoodTime") // reading system time without TimeSource public static void touch(Path path) throws IOException { checkNotNull(path); try { Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis())); } catch (NoSuchFileException e) { try { Files.createFile(path); } catch (FileAlreadyExistsException ignore) { // The file didn't exist when we called setLastModifiedTime, but it did when we called // createFile, so something else created the file in between. The end result is // what we wanted: a new file that probably has its last modified time set to approximately // now. Or it could have an arbitrary last modified time set by the creator, but that's no // different than if another process set its last modified time to something else after we // created it here. } } }
java
{ "resource": "" }
q165050
MoreFiles.getParentPath
validation
private static @Nullable Path getParentPath(Path path) { Path parent = path.getParent(); // Paths that have a parent: if (parent != null) { // "/foo" ("/") // "foo/bar" ("foo") // "C:\foo" ("C:\") // "\foo" ("\" - current drive for process on Windows) // "C:foo" ("C:" - working dir of drive C on Windows) return parent; } // Paths that don't have a parent: if (path.getNameCount() == 0) { // "/", "C:\", "\" (no parent) // "" (undefined, though typically parent of working dir) // "C:" (parent of working dir of drive C on Windows) // // For working dir paths ("" and "C:"), return null because: // A) it's not specified that "" is the path to the working directory. // B) if we're getting this path for recursive delete, it's typically not possible to // delete the working dir with a relative path anyway, so it's ok to fail. // C) if we're getting it for opening a new SecureDirectoryStream, there's no need to get // the parent path anyway since we can safely open a DirectoryStream to the path without // worrying about a symlink. return null; } else { // "foo" (working dir) return path.getFileSystem().getPath("."); } }
java
{ "resource": "" }
q165051
MoreFiles.checkAllowsInsecure
validation
private static void checkAllowsInsecure(Path path, RecursiveDeleteOption[] options) throws InsecureRecursiveDeleteException { if (!Arrays.asList(options).contains(RecursiveDeleteOption.ALLOW_INSECURE)) { throw new InsecureRecursiveDeleteException(path.toString()); } }
java
{ "resource": "" }
q165052
MoreFiles.throwDeleteFailed
validation
private static void throwDeleteFailed(Path path, Collection<IOException> exceptions) throws FileSystemException { // TODO(cgdecker): Should there be a custom exception type for this? // Also, should we try to include the Path of each file we may have failed to delete rather // than just the exceptions that occurred? FileSystemException deleteFailed = new FileSystemException( path.toString(), null, "failed to delete one or more files; see suppressed exceptions for details"); for (IOException e : exceptions) { deleteFailed.addSuppressed(e); } throw deleteFailed; }
java
{ "resource": "" }
q165053
MapMakerInternalMap.rehash
validation
static int rehash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. // TODO(kevinb): use Hashing/move this to Hashing? h += (h << 15) ^ 0xffffcd7d; h ^= (h >>> 10); h += (h << 3); h ^= (h >>> 6); h += (h << 2) + (h << 14); return h ^ (h >>> 16); }
java
{ "resource": "" }
q165054
MapMakerInternalMap.segmentFor
validation
Segment<K, V, E, S> segmentFor(int hash) { // TODO(fry): Lazily create segments? return segments[(hash >>> segmentShift) & segmentMask]; }
java
{ "resource": "" }
q165055
ImmutableList.unsafeDelegateList
validation
static <E> ImmutableList<E> unsafeDelegateList(List<? extends E> list) { switch (list.size()) { case 0: return of(); case 1: return of(list.get(0)); default: @SuppressWarnings("unchecked") List<E> castedList = (List<E>) list; return new RegularImmutableList<E>(castedList); } }
java
{ "resource": "" }
q165056
TreeRangeMap.coalescedRange
validation
private Range<K> coalescedRange(Range<K> range, V value) { Range<K> coalescedRange = range; Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry = entriesByLowerBound.lowerEntry(range.lowerBound); coalescedRange = coalesce(coalescedRange, value, lowerEntry); Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry = entriesByLowerBound.floorEntry(range.upperBound); coalescedRange = coalesce(coalescedRange, value, higherEntry); return coalescedRange; }
java
{ "resource": "" }
q165057
SubscriberRegistry.unregister
validation
void unregister(Object listener) { Multimap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener); for (Entry<Class<?>, Collection<Subscriber>> entry : listenerMethods.asMap().entrySet()) { Class<?> eventType = entry.getKey(); Collection<Subscriber> listenerMethodsForType = entry.getValue(); CopyOnWriteArraySet<Subscriber> currentSubscribers = subscribers.get(eventType); if (currentSubscribers == null || !currentSubscribers.removeAll(listenerMethodsForType)) { // if removeAll returns true, all we really know is that at least one subscriber was // removed... however, barring something very strange we can assume that if at least one // subscriber was removed, all subscribers on listener for that event type were... after // all, the definition of subscribers on a particular class is totally static throw new IllegalArgumentException( "missing event subscriber for an annotated method. Is " + listener + " registered?"); } // don't try to remove the set if it's empty; that can't be done safely without a lock // anyway, if the set is empty it'll just be wrapping an array of length 0 } }
java
{ "resource": "" }
q165058
SubscriberRegistry.getSubscribers
validation
Iterator<Subscriber> getSubscribers(Object event) { ImmutableSet<Class<?>> eventTypes = flattenHierarchy(event.getClass()); List<Iterator<Subscriber>> subscriberIterators = Lists.newArrayListWithCapacity(eventTypes.size()); for (Class<?> eventType : eventTypes) { CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType); if (eventSubscribers != null) { // eager no-copy snapshot subscriberIterators.add(eventSubscribers.iterator()); } } return Iterators.concat(subscriberIterators.iterator()); }
java
{ "resource": "" }
q165059
SubscriberRegistry.findAllSubscribers
validation
private Multimap<Class<?>, Subscriber> findAllSubscribers(Object listener) { Multimap<Class<?>, Subscriber> methodsInListener = HashMultimap.create(); Class<?> clazz = listener.getClass(); for (Method method : getAnnotatedMethods(clazz)) { Class<?>[] parameterTypes = method.getParameterTypes(); Class<?> eventType = parameterTypes[0]; methodsInListener.put(eventType, Subscriber.create(bus, listener, method)); } return methodsInListener; }
java
{ "resource": "" }
q165060
ImmutableList.sortedCopyOf
validation
public static <E extends Comparable<? super E>> ImmutableList<E> sortedCopyOf( Iterable<? extends E> elements) { Comparable<?>[] array = Iterables.toArray(elements, new Comparable<?>[0]); checkElementsNotNull((Object[]) array); Arrays.sort(array); return asImmutableList(array); }
java
{ "resource": "" }
q165061
ImmutableList.asImmutableList
validation
static <E> ImmutableList<E> asImmutableList(Object[] elements) { return asImmutableList(elements, elements.length); }
java
{ "resource": "" }
q165062
ImmutableList.asImmutableList
validation
static <E> ImmutableList<E> asImmutableList(Object[] elements, int length) { if (length == 0) { return of(); } return new RegularImmutableList<E>(elements, length); }
java
{ "resource": "" }
q165063
ImmutableList.builderWithExpectedSize
validation
@Beta public static <E> Builder<E> builderWithExpectedSize(int expectedSize) { checkNonnegative(expectedSize, "expectedSize"); return new ImmutableList.Builder<E>(expectedSize); }
java
{ "resource": "" }
q165064
ObjectArrays.concat
validation
@GwtIncompatible // Array.newInstance(Class, int) public static <T> T[] concat(T[] first, T[] second, Class<T> type) { T[] result = newArray(type, first.length + second.length); System.arraycopy(first, 0, result, 0, first.length); System.arraycopy(second, 0, result, first.length, second.length); return result; }
java
{ "resource": "" }
q165065
ObjectArrays.toArrayImpl
validation
static <T> T[] toArrayImpl(Collection<?> c, T[] array) { int size = c.size(); if (array.length < size) { array = newArray(array, size); } fillArray(c, array); if (array.length > size) { array[size] = null; } return array; }
java
{ "resource": "" }
q165066
ObjectArrays.checkElementNotNull
validation
@CanIgnoreReturnValue static Object checkElementNotNull(Object element, int index) { if (element == null) { throw new NullPointerException("at index " + index); } return element; }
java
{ "resource": "" }
q165067
Throwables.getJLA
validation
@GwtIncompatible // java.lang.reflect @NullableDecl private static Object getJLA() { try { /* * We load sun.misc.* classes using reflection since Android doesn't support these classes and * would result in compilation failure if we directly refer to these classes. */ Class<?> sharedSecrets = Class.forName(SHARED_SECRETS_CLASSNAME, false, null); Method langAccess = sharedSecrets.getMethod("getJavaLangAccess"); return langAccess.invoke(null); } catch (ThreadDeath death) { throw death; } catch (Throwable t) { /* * This is not one of AppEngine's allowed classes, so even in Sun JDKs, this can fail with * a NoClassDefFoundError. Other apps might deny access to sun.misc packages. */ return null; } }
java
{ "resource": "" }
q165068
TypeToken.canonicalizeWildcardType
validation
private static WildcardType canonicalizeWildcardType( TypeVariable<?> declaration, WildcardType type) { Type[] declared = declaration.getBounds(); List<Type> upperBounds = new ArrayList<>(); for (Type bound : type.getUpperBounds()) { if (!any(declared).isSubtypeOf(bound)) { upperBounds.add(canonicalizeWildcardsInType(bound)); } } return new Types.WildcardTypeImpl(type.getLowerBounds(), upperBounds.toArray(new Type[0])); }
java
{ "resource": "" }
q165069
ImmutableList.asImmutableList
validation
static <E> ImmutableList<E> asImmutableList(Object[] elements, int length) { switch (length) { case 0: return of(); case 1: return of((E) elements[0]); default: if (length < elements.length) { elements = Arrays.copyOf(elements, length); } return new RegularImmutableList<E>(elements); } }
java
{ "resource": "" }
q165070
ImmutableSortedMapFauxverideShim.builderWithExpectedSize
validation
@Deprecated public static <K, V> ImmutableSortedMap.Builder<K, V> builderWithExpectedSize(int expectedSize) { throw new UnsupportedOperationException(); }
java
{ "resource": "" }
q165071
ImmutableMap.entrySet
validation
@Override public ImmutableSet<Entry<K, V>> entrySet() { ImmutableSet<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; }
java
{ "resource": "" }
q165072
LineBuffer.finishLine
validation
@CanIgnoreReturnValue private boolean finishLine(boolean sawNewline) throws IOException { String separator = sawReturn ? (sawNewline ? "\r\n" : "\r") : (sawNewline ? "\n" : ""); handleLine(line.toString(), separator); line = new StringBuilder(); sawReturn = false; return sawNewline; }
java
{ "resource": "" }
q165073
Maps.asEntryTransformer
validation
static <K, V1, V2> EntryTransformer<K, V1, V2> asEntryTransformer( final Function<? super V1, V2> function) { checkNotNull(function); return new EntryTransformer<K, V1, V2>() { @Override public V2 transformEntry(K key, V1 value) { return function.apply(value); } }; }
java
{ "resource": "" }
q165074
Maps.transformEntry
validation
static <V2, K, V1> Entry<K, V2> transformEntry( final EntryTransformer<? super K, ? super V1, V2> transformer, final Entry<K, V1> entry) { checkNotNull(transformer); checkNotNull(entry); return new AbstractMapEntry<K, V2>() { @Override public K getKey() { return entry.getKey(); } @Override public V2 getValue() { return transformer.transformEntry(entry.getKey(), entry.getValue()); } }; }
java
{ "resource": "" }
q165075
Maps.asEntryToEntryFunction
validation
static <K, V1, V2> Function<Entry<K, V1>, Entry<K, V2>> asEntryToEntryFunction( final EntryTransformer<? super K, ? super V1, V2> transformer) { checkNotNull(transformer); return new Function<Entry<K, V1>, Entry<K, V2>>() { @Override public Entry<K, V2> apply(final Entry<K, V1> entry) { return transformEntry(transformer, entry); } }; }
java
{ "resource": "" }
q165076
Maps.indexMap
validation
static <E> ImmutableMap<E, Integer> indexMap(Collection<E> list) { ImmutableMap.Builder<E, Integer> builder = new ImmutableMap.Builder<>(list.size()); int i = 0; for (E e : list) { builder.put(e, i++); } return builder.build(); }
java
{ "resource": "" }
q165077
AbstractFuture.pendingToString
validation
protected @Nullable String pendingToString() { Object localValue = value; if (localValue instanceof SetFuture) { return "setFuture=[" + userObjectToString(((SetFuture) localValue).future) + "]"; } else if (this instanceof ScheduledFuture) { return "remaining delay=[" + ((ScheduledFuture) this).getDelay(TimeUnit.MILLISECONDS) + " ms]"; } return null; }
java
{ "resource": "" }
q165078
AbstractByteHasher.update
validation
protected void update(ByteBuffer b) { if (b.hasArray()) { update(b.array(), b.arrayOffset() + b.position(), b.remaining()); b.position(b.limit()); } else { for (int remaining = b.remaining(); remaining > 0; remaining--) { update(b.get()); } } }
java
{ "resource": "" }
q165079
ImmutableSortedSet.unsafeDelegateSortedSet
validation
static <E> ImmutableSortedSet<E> unsafeDelegateSortedSet( SortedSet<E> delegate, boolean isSubset) { return delegate.isEmpty() ? emptySet(delegate.comparator()) : new RegularImmutableSortedSet<E>(delegate, isSubset); }
java
{ "resource": "" }
q165080
ImmutableSetMultimap_CustomFieldSerializer.instantiate
validation
@SuppressWarnings("unchecked") public static ImmutableSetMultimap<Object, Object> instantiate(SerializationStreamReader reader) throws SerializationException { Comparator<Object> valueComparator = (Comparator<Object>) reader.readObject(); ImmutableSetMultimap.Builder<Object, Object> builder = ImmutableSetMultimap.builder(); if (valueComparator != null) { builder.orderValuesBy(valueComparator); } return (ImmutableSetMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.instantiate(reader, builder); }
java
{ "resource": "" }
q165081
AtomicLongMap.sum
validation
public long sum() { long sum = 0L; for (AtomicLong value : map.values()) { sum = sum + value.get(); } return sum; }
java
{ "resource": "" }
q165082
FinalizableReferenceQueue.loadFinalizer
validation
private static Class<?> loadFinalizer(FinalizerLoader... loaders) { for (FinalizerLoader loader : loaders) { Class<?> finalizer = loader.loadFinalizer(); if (finalizer != null) { return finalizer; } } throw new AssertionError(); }
java
{ "resource": "" }
q165083
ListenerCallQueue.dispatch
validation
public void dispatch() { // iterate by index to avoid concurrent modification exceptions for (int i = 0; i < listeners.size(); i++) { listeners.get(i).dispatch(); } }
java
{ "resource": "" }
q165084
Resources.copy
validation
public static void copy(URL from, OutputStream to) throws IOException { asByteSource(from).copyTo(to); }
java
{ "resource": "" }
q165085
EventBus.post
validation
public void post(Object event) { Iterator<Subscriber> eventSubscribers = subscribers.getSubscribers(event); if (eventSubscribers.hasNext()) { dispatcher.dispatch(event, eventSubscribers); } else if (!(event instanceof DeadEvent)) { // the event had no subscribers and was not itself a DeadEvent post(new DeadEvent(this, event)); } }
java
{ "resource": "" }
q165086
MapMaker.concurrencyLevel
validation
@CanIgnoreReturnValue public MapMaker concurrencyLevel(int concurrencyLevel) { checkState( this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s", this.concurrencyLevel); checkArgument(concurrencyLevel > 0); this.concurrencyLevel = concurrencyLevel; return this; }
java
{ "resource": "" }
q165087
AbstractBiMap.setDelegates
validation
void setDelegates(Map<K, V> forward, Map<V, K> backward) { checkState(delegate == null); checkState(inverse == null); checkArgument(forward.isEmpty()); checkArgument(backward.isEmpty()); checkArgument(forward != backward); delegate = forward; inverse = makeInverse(backward); }
java
{ "resource": "" }
q165088
ArrayTable.toArray
validation
@GwtIncompatible // reflection public V[][] toArray(Class<V> valueClass) { @SuppressWarnings("unchecked") // TODO: safe? V[][] copy = (V[][]) Array.newInstance(valueClass, rowList.size(), columnList.size()); for (int i = 0; i < rowList.size(); i++) { System.arraycopy(array[i], 0, copy[i], 0, array[i].length); } return copy; }
java
{ "resource": "" }
q165089
SequentialExecutor.execute
validation
@Override public void execute(final Runnable task) { checkNotNull(task); final Runnable submittedTask; final long oldRunCount; synchronized (queue) { // If the worker is already running (or execute() on the delegate returned successfully, and // the worker has yet to start) then we don't need to start the worker. if (workerRunningState == RUNNING || workerRunningState == QUEUED) { queue.add(task); return; } oldRunCount = workerRunCount; // If the worker is not yet running, the delegate Executor might reject our attempt to start // it. To preserve FIFO order and failure atomicity of rejected execution when the same // Runnable is executed more than once, allocate a wrapper that we know is safe to remove by // object identity. // A data structure that returned a removal handle from add() would allow eliminating this // allocation. submittedTask = new Runnable() { @Override public void run() { task.run(); } }; queue.add(submittedTask); workerRunningState = QUEUING; } try { executor.execute(worker); } catch (RuntimeException | Error t) { synchronized (queue) { boolean removed = (workerRunningState == IDLE || workerRunningState == QUEUING) && queue.removeLastOccurrence(submittedTask); // If the delegate is directExecutor(), the submitted runnable could have thrown a REE. But // that's handled by the log check that catches RuntimeExceptions in the queue worker. if (!(t instanceof RejectedExecutionException) || removed) { throw t; } } return; } /* * This is an unsynchronized read! After the read, the function returns immediately or acquires * the lock to check again. Since an IDLE state was observed inside the preceding synchronized * block, and reference field assignment is atomic, this may save reacquiring the lock when * another thread or the worker task has cleared the count and set the state. * * <p>When {@link #executor} is a directExecutor(), the value written to * {@code workerRunningState} will be available synchronously, and behaviour will be * deterministic. */ @SuppressWarnings("GuardedBy") boolean alreadyMarkedQueued = workerRunningState != QUEUING; if (alreadyMarkedQueued) { return; } synchronized (queue) { if (workerRunCount == oldRunCount && workerRunningState == QUEUING) { workerRunningState = QUEUED; } } }
java
{ "resource": "" }
q165090
Tables.transformValues
validation
@Beta public static <R, C, V1, V2> Table<R, C, V2> transformValues( Table<R, C, V1> fromTable, Function<? super V1, V2> function) { return new TransformedTable<>(fromTable, function); }
java
{ "resource": "" }
q165091
TreeMultiset.create
validation
public static <E extends Comparable> TreeMultiset<E> create(Iterable<? extends E> elements) { TreeMultiset<E> multiset = create(); Iterables.addAll(multiset, elements); return multiset; }
java
{ "resource": "" }
q165092
AggregateFuture.addCausalChain
validation
private static boolean addCausalChain(Set<Throwable> seen, Throwable t) { for (; t != null; t = t.getCause()) { boolean firstTimeSeen = seen.add(t); if (!firstTimeSeen) { /* * We've seen this, so we've seen its causes, too. No need to re-add them. (There's one case * where this isn't true, but we ignore it: If we record an exception, then someone calls * initCause() on it, and then we examine it again, we'll conclude that we've seen the whole * chain before when it fact we haven't. But this should be rare.) */ return false; } } return true; }
java
{ "resource": "" }
q165093
CacheBuilder.expireAfterWrite
validation
@J2ObjCIncompatible @GwtIncompatible // java.time.Duration @SuppressWarnings("GoodTime") // java.time.Duration decomposition public CacheBuilder<K, V> expireAfterWrite(java.time.Duration duration) { return expireAfterWrite(duration.toNanos(), TimeUnit.NANOSECONDS); }
java
{ "resource": "" }
q165094
ThreadFactoryBuilder.setPriority
validation
public ThreadFactoryBuilder setPriority(int priority) { // Thread#setPriority() already checks for validity. These error messages // are nicer though and will fail-fast. checkArgument( priority >= Thread.MIN_PRIORITY, "Thread priority (%s) must be >= %s", priority, Thread.MIN_PRIORITY); checkArgument( priority <= Thread.MAX_PRIORITY, "Thread priority (%s) must be <= %s", priority, Thread.MAX_PRIORITY); this.priority = priority; return this; }
java
{ "resource": "" }
q165095
HostAndPort.fromParts
validation
public static HostAndPort fromParts(String host, int port) { checkArgument(isValidPort(port), "Port out of range: %s", port); HostAndPort parsedHost = fromString(host); checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); return new HostAndPort(parsedHost.host, port, parsedHost.hasBracketlessColons); }
java
{ "resource": "" }
q165096
HostAndPort.fromHost
validation
public static HostAndPort fromHost(String host) { HostAndPort parsedHost = fromString(host); checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); return parsedHost; }
java
{ "resource": "" }
q165097
HostAndPort.fromString
validation
public static HostAndPort fromString(String hostPortString) { checkNotNull(hostPortString); String host; String portString = null; boolean hasBracketlessColons = false; if (hostPortString.startsWith("[")) { String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString); host = hostAndPort[0]; portString = hostAndPort[1]; } else { int colonPos = hostPortString.indexOf(':'); if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) { // Exactly 1 colon. Split into host:port. host = hostPortString.substring(0, colonPos); portString = hostPortString.substring(colonPos + 1); } else { // 0 or 2+ colons. Bare hostname or IPv6 literal. host = hostPortString; hasBracketlessColons = (colonPos >= 0); } } int port = NO_PORT; if (!Strings.isNullOrEmpty(portString)) { // Try to parse the whole port string as a number. // JDK7 accepts leading plus signs. We don't want to. checkArgument(!portString.startsWith("+"), "Unparseable port number: %s", hostPortString); try { port = Integer.parseInt(portString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Unparseable port number: " + hostPortString); } checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString); } return new HostAndPort(host, port, hasBracketlessColons); }
java
{ "resource": "" }
q165098
HostAndPort.getHostAndPortFromBracketedHost
validation
private static String[] getHostAndPortFromBracketedHost(String hostPortString) { int colonIndex = 0; int closeBracketIndex = 0; checkArgument( hostPortString.charAt(0) == '[', "Bracketed host-port string must start with a bracket: %s", hostPortString); colonIndex = hostPortString.indexOf(':'); closeBracketIndex = hostPortString.lastIndexOf(']'); checkArgument( colonIndex > -1 && closeBracketIndex > colonIndex, "Invalid bracketed host/port: %s", hostPortString); String host = hostPortString.substring(1, closeBracketIndex); if (closeBracketIndex + 1 == hostPortString.length()) { return new String[] {host, ""}; } else { checkArgument( hostPortString.charAt(closeBracketIndex + 1) == ':', "Only a colon may follow a close bracket: %s", hostPortString); for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) { checkArgument( Character.isDigit(hostPortString.charAt(i)), "Port must be numeric: %s", hostPortString); } return new String[] {host, hostPortString.substring(closeBracketIndex + 2)}; } }
java
{ "resource": "" }
q165099
GeneralRange.all
validation
static <T> GeneralRange<T> all(Comparator<? super T> comparator) { return new GeneralRange<T>(comparator, false, null, OPEN, false, null, OPEN); }
java
{ "resource": "" }