method2testcases
stringlengths
118
6.63k
### Question: PetrifyableTLongArrayList extends AbstractPetrifyable implements PetrifyableTLongList { @Override public void insert(int offset, long value) { myList.insert(offset, value); } PetrifyableTLongArrayList(); PetrifyableTLongArrayList(int capacity); PetrifyableTLongArrayList(long[] values); PetrifyableTLongArrayList(TLongCollection values); @Override boolean add(long val); @Override void add(long[] vals); @Override void add(long[] vals, int offset, int length); @Override boolean addAll(Collection<? extends Long> collection); @Override boolean addAll(long[] array); @Override boolean addAll(TLongCollection collection); @Override int binarySearch(long value); @Override int binarySearch(long value, int fromIndex, int toIndex); @Override void clear(); @Override boolean contains(long value); @Override boolean containsAll(Collection<?> collection); @Override boolean containsAll(long[] array); @Override boolean containsAll(TLongCollection collection); @Override void fill(int fromIndex, int toIndex, long val); @Override void fill(long val); @Override boolean forEach(TLongProcedure procedure); @Override boolean forEachDescending(TLongProcedure procedure); @Override long get(int offset); @Override long getNoEntryValue(); @Override long getSizeBytes(); @Override TLongList grep(TLongProcedure condition); @Override int indexOf(int offset, long value); @Override int indexOf(long value); @Override void insert(int offset, long value); @Override void insert(int offset, long[] values); @Override void insert(int offset, long[] values, int valOffset, int len); @Override TLongList inverseGrep(TLongProcedure condition); @Override boolean isEmpty(); @Override TLongIterator iterator(); @Override int lastIndexOf(int offset, long value); @Override int lastIndexOf(long value); @Override long max(); @Override long min(); @Override synchronized void petrify(); @Override void remove(int offset, int length); @Override boolean remove(long value); @Override boolean removeAll(Collection<?> collection); @Override boolean removeAll(long[] array); @Override boolean removeAll(TLongCollection collection); @Override long removeAt(int offset); @Override long replace(int offset, long val); @Override boolean retainAll(Collection<?> collection); @Override boolean retainAll(long[] array); @Override boolean retainAll(TLongCollection collection); @Override void reverse(); @Override void reverse(int from, int to); @Override long set(int offset, long val); @Override void set(int offset, long[] values); @Override void set(int offset, long[] values, int valOffset, int length); @Override void shuffle(Random rand); @Override int size(); @Override void sort(); @Override void sort(int fromIndex, int toIndex); @Override PetrifyableTLongArrayList subList(int begin, int end); @Override long sum(); @Override long[] toArray(); @Override long[] toArray(int offset, int len); @Override long[] toArray(long[] dest); @Override long[] toArray(long[] dest, int offset, int len); @Override long[] toArray(long[] dest, int sourcePos, int destPos, int len); @Override void transformValues(TLongFunction function); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testInsertAfterPetrify1() { PETRIFIED_LIST.insert(0, TEST_LONG); } @Test(expected = UnsupportedOperationException.class) public void testInsertAfterPetrify2() { PETRIFIED_LIST.insert(0, TEST_LONG_ARRAY); } @Test(expected = UnsupportedOperationException.class) public void testInsertAfterPetrify3() { PETRIFIED_LIST.insert(0, TEST_LONG_ARRAY, 0, 1); }
### Question: PetrifyableTLongArrayList extends AbstractPetrifyable implements PetrifyableTLongList { @Override public void remove(int offset, int length) { myList.remove(offset, length); } PetrifyableTLongArrayList(); PetrifyableTLongArrayList(int capacity); PetrifyableTLongArrayList(long[] values); PetrifyableTLongArrayList(TLongCollection values); @Override boolean add(long val); @Override void add(long[] vals); @Override void add(long[] vals, int offset, int length); @Override boolean addAll(Collection<? extends Long> collection); @Override boolean addAll(long[] array); @Override boolean addAll(TLongCollection collection); @Override int binarySearch(long value); @Override int binarySearch(long value, int fromIndex, int toIndex); @Override void clear(); @Override boolean contains(long value); @Override boolean containsAll(Collection<?> collection); @Override boolean containsAll(long[] array); @Override boolean containsAll(TLongCollection collection); @Override void fill(int fromIndex, int toIndex, long val); @Override void fill(long val); @Override boolean forEach(TLongProcedure procedure); @Override boolean forEachDescending(TLongProcedure procedure); @Override long get(int offset); @Override long getNoEntryValue(); @Override long getSizeBytes(); @Override TLongList grep(TLongProcedure condition); @Override int indexOf(int offset, long value); @Override int indexOf(long value); @Override void insert(int offset, long value); @Override void insert(int offset, long[] values); @Override void insert(int offset, long[] values, int valOffset, int len); @Override TLongList inverseGrep(TLongProcedure condition); @Override boolean isEmpty(); @Override TLongIterator iterator(); @Override int lastIndexOf(int offset, long value); @Override int lastIndexOf(long value); @Override long max(); @Override long min(); @Override synchronized void petrify(); @Override void remove(int offset, int length); @Override boolean remove(long value); @Override boolean removeAll(Collection<?> collection); @Override boolean removeAll(long[] array); @Override boolean removeAll(TLongCollection collection); @Override long removeAt(int offset); @Override long replace(int offset, long val); @Override boolean retainAll(Collection<?> collection); @Override boolean retainAll(long[] array); @Override boolean retainAll(TLongCollection collection); @Override void reverse(); @Override void reverse(int from, int to); @Override long set(int offset, long val); @Override void set(int offset, long[] values); @Override void set(int offset, long[] values, int valOffset, int length); @Override void shuffle(Random rand); @Override int size(); @Override void sort(); @Override void sort(int fromIndex, int toIndex); @Override PetrifyableTLongArrayList subList(int begin, int end); @Override long sum(); @Override long[] toArray(); @Override long[] toArray(int offset, int len); @Override long[] toArray(long[] dest); @Override long[] toArray(long[] dest, int offset, int len); @Override long[] toArray(long[] dest, int sourcePos, int destPos, int len); @Override void transformValues(TLongFunction function); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testRemoveAfterPetrify1() { PETRIFIED_LIST.remove(TEST_LONG); } @Test(expected = UnsupportedOperationException.class) public void testRemoveAfterPetrify2() { PETRIFIED_LIST.remove(0, 1); }
### Question: PetrifyableTLongArrayList extends AbstractPetrifyable implements PetrifyableTLongList { @Override public boolean removeAll(Collection<?> collection) { return myList.removeAll(collection); } PetrifyableTLongArrayList(); PetrifyableTLongArrayList(int capacity); PetrifyableTLongArrayList(long[] values); PetrifyableTLongArrayList(TLongCollection values); @Override boolean add(long val); @Override void add(long[] vals); @Override void add(long[] vals, int offset, int length); @Override boolean addAll(Collection<? extends Long> collection); @Override boolean addAll(long[] array); @Override boolean addAll(TLongCollection collection); @Override int binarySearch(long value); @Override int binarySearch(long value, int fromIndex, int toIndex); @Override void clear(); @Override boolean contains(long value); @Override boolean containsAll(Collection<?> collection); @Override boolean containsAll(long[] array); @Override boolean containsAll(TLongCollection collection); @Override void fill(int fromIndex, int toIndex, long val); @Override void fill(long val); @Override boolean forEach(TLongProcedure procedure); @Override boolean forEachDescending(TLongProcedure procedure); @Override long get(int offset); @Override long getNoEntryValue(); @Override long getSizeBytes(); @Override TLongList grep(TLongProcedure condition); @Override int indexOf(int offset, long value); @Override int indexOf(long value); @Override void insert(int offset, long value); @Override void insert(int offset, long[] values); @Override void insert(int offset, long[] values, int valOffset, int len); @Override TLongList inverseGrep(TLongProcedure condition); @Override boolean isEmpty(); @Override TLongIterator iterator(); @Override int lastIndexOf(int offset, long value); @Override int lastIndexOf(long value); @Override long max(); @Override long min(); @Override synchronized void petrify(); @Override void remove(int offset, int length); @Override boolean remove(long value); @Override boolean removeAll(Collection<?> collection); @Override boolean removeAll(long[] array); @Override boolean removeAll(TLongCollection collection); @Override long removeAt(int offset); @Override long replace(int offset, long val); @Override boolean retainAll(Collection<?> collection); @Override boolean retainAll(long[] array); @Override boolean retainAll(TLongCollection collection); @Override void reverse(); @Override void reverse(int from, int to); @Override long set(int offset, long val); @Override void set(int offset, long[] values); @Override void set(int offset, long[] values, int valOffset, int length); @Override void shuffle(Random rand); @Override int size(); @Override void sort(); @Override void sort(int fromIndex, int toIndex); @Override PetrifyableTLongArrayList subList(int begin, int end); @Override long sum(); @Override long[] toArray(); @Override long[] toArray(int offset, int len); @Override long[] toArray(long[] dest); @Override long[] toArray(long[] dest, int offset, int len); @Override long[] toArray(long[] dest, int sourcePos, int destPos, int len); @Override void transformValues(TLongFunction function); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testRemoveAllAfterPetrify1() { PETRIFIED_LIST.removeAll(TEST_LONG_ARRAY); } @Test(expected = UnsupportedOperationException.class) public void testRemoveAllAfterPetrify2() { PETRIFIED_LIST.removeAll(TEST_LONG_COLLECTION); } @Test(expected = UnsupportedOperationException.class) public void testRemoveAllAfterPetrify3() { PETRIFIED_LIST.removeAll(TEST_LONG_ARRAY_LIST); }
### Question: PetrifyableTLongArrayList extends AbstractPetrifyable implements PetrifyableTLongList { @Override public long removeAt(int offset) { return myList.removeAt(offset); } PetrifyableTLongArrayList(); PetrifyableTLongArrayList(int capacity); PetrifyableTLongArrayList(long[] values); PetrifyableTLongArrayList(TLongCollection values); @Override boolean add(long val); @Override void add(long[] vals); @Override void add(long[] vals, int offset, int length); @Override boolean addAll(Collection<? extends Long> collection); @Override boolean addAll(long[] array); @Override boolean addAll(TLongCollection collection); @Override int binarySearch(long value); @Override int binarySearch(long value, int fromIndex, int toIndex); @Override void clear(); @Override boolean contains(long value); @Override boolean containsAll(Collection<?> collection); @Override boolean containsAll(long[] array); @Override boolean containsAll(TLongCollection collection); @Override void fill(int fromIndex, int toIndex, long val); @Override void fill(long val); @Override boolean forEach(TLongProcedure procedure); @Override boolean forEachDescending(TLongProcedure procedure); @Override long get(int offset); @Override long getNoEntryValue(); @Override long getSizeBytes(); @Override TLongList grep(TLongProcedure condition); @Override int indexOf(int offset, long value); @Override int indexOf(long value); @Override void insert(int offset, long value); @Override void insert(int offset, long[] values); @Override void insert(int offset, long[] values, int valOffset, int len); @Override TLongList inverseGrep(TLongProcedure condition); @Override boolean isEmpty(); @Override TLongIterator iterator(); @Override int lastIndexOf(int offset, long value); @Override int lastIndexOf(long value); @Override long max(); @Override long min(); @Override synchronized void petrify(); @Override void remove(int offset, int length); @Override boolean remove(long value); @Override boolean removeAll(Collection<?> collection); @Override boolean removeAll(long[] array); @Override boolean removeAll(TLongCollection collection); @Override long removeAt(int offset); @Override long replace(int offset, long val); @Override boolean retainAll(Collection<?> collection); @Override boolean retainAll(long[] array); @Override boolean retainAll(TLongCollection collection); @Override void reverse(); @Override void reverse(int from, int to); @Override long set(int offset, long val); @Override void set(int offset, long[] values); @Override void set(int offset, long[] values, int valOffset, int length); @Override void shuffle(Random rand); @Override int size(); @Override void sort(); @Override void sort(int fromIndex, int toIndex); @Override PetrifyableTLongArrayList subList(int begin, int end); @Override long sum(); @Override long[] toArray(); @Override long[] toArray(int offset, int len); @Override long[] toArray(long[] dest); @Override long[] toArray(long[] dest, int offset, int len); @Override long[] toArray(long[] dest, int sourcePos, int destPos, int len); @Override void transformValues(TLongFunction function); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testRemoveAtAfterPetrify() { PETRIFIED_LIST.removeAt(1); }
### Question: PetrifyableTLongArrayList extends AbstractPetrifyable implements PetrifyableTLongList { @Override public long replace(int offset, long val) { return myList.replace(offset, val); } PetrifyableTLongArrayList(); PetrifyableTLongArrayList(int capacity); PetrifyableTLongArrayList(long[] values); PetrifyableTLongArrayList(TLongCollection values); @Override boolean add(long val); @Override void add(long[] vals); @Override void add(long[] vals, int offset, int length); @Override boolean addAll(Collection<? extends Long> collection); @Override boolean addAll(long[] array); @Override boolean addAll(TLongCollection collection); @Override int binarySearch(long value); @Override int binarySearch(long value, int fromIndex, int toIndex); @Override void clear(); @Override boolean contains(long value); @Override boolean containsAll(Collection<?> collection); @Override boolean containsAll(long[] array); @Override boolean containsAll(TLongCollection collection); @Override void fill(int fromIndex, int toIndex, long val); @Override void fill(long val); @Override boolean forEach(TLongProcedure procedure); @Override boolean forEachDescending(TLongProcedure procedure); @Override long get(int offset); @Override long getNoEntryValue(); @Override long getSizeBytes(); @Override TLongList grep(TLongProcedure condition); @Override int indexOf(int offset, long value); @Override int indexOf(long value); @Override void insert(int offset, long value); @Override void insert(int offset, long[] values); @Override void insert(int offset, long[] values, int valOffset, int len); @Override TLongList inverseGrep(TLongProcedure condition); @Override boolean isEmpty(); @Override TLongIterator iterator(); @Override int lastIndexOf(int offset, long value); @Override int lastIndexOf(long value); @Override long max(); @Override long min(); @Override synchronized void petrify(); @Override void remove(int offset, int length); @Override boolean remove(long value); @Override boolean removeAll(Collection<?> collection); @Override boolean removeAll(long[] array); @Override boolean removeAll(TLongCollection collection); @Override long removeAt(int offset); @Override long replace(int offset, long val); @Override boolean retainAll(Collection<?> collection); @Override boolean retainAll(long[] array); @Override boolean retainAll(TLongCollection collection); @Override void reverse(); @Override void reverse(int from, int to); @Override long set(int offset, long val); @Override void set(int offset, long[] values); @Override void set(int offset, long[] values, int valOffset, int length); @Override void shuffle(Random rand); @Override int size(); @Override void sort(); @Override void sort(int fromIndex, int toIndex); @Override PetrifyableTLongArrayList subList(int begin, int end); @Override long sum(); @Override long[] toArray(); @Override long[] toArray(int offset, int len); @Override long[] toArray(long[] dest); @Override long[] toArray(long[] dest, int offset, int len); @Override long[] toArray(long[] dest, int sourcePos, int destPos, int len); @Override void transformValues(TLongFunction function); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testReplaceAfterPetrify() { PETRIFIED_LIST.replace(0, TEST_LONG); }
### Question: PetrifyableTLongArrayList extends AbstractPetrifyable implements PetrifyableTLongList { @Override public boolean retainAll(Collection<?> collection) { return myList.retainAll(collection); } PetrifyableTLongArrayList(); PetrifyableTLongArrayList(int capacity); PetrifyableTLongArrayList(long[] values); PetrifyableTLongArrayList(TLongCollection values); @Override boolean add(long val); @Override void add(long[] vals); @Override void add(long[] vals, int offset, int length); @Override boolean addAll(Collection<? extends Long> collection); @Override boolean addAll(long[] array); @Override boolean addAll(TLongCollection collection); @Override int binarySearch(long value); @Override int binarySearch(long value, int fromIndex, int toIndex); @Override void clear(); @Override boolean contains(long value); @Override boolean containsAll(Collection<?> collection); @Override boolean containsAll(long[] array); @Override boolean containsAll(TLongCollection collection); @Override void fill(int fromIndex, int toIndex, long val); @Override void fill(long val); @Override boolean forEach(TLongProcedure procedure); @Override boolean forEachDescending(TLongProcedure procedure); @Override long get(int offset); @Override long getNoEntryValue(); @Override long getSizeBytes(); @Override TLongList grep(TLongProcedure condition); @Override int indexOf(int offset, long value); @Override int indexOf(long value); @Override void insert(int offset, long value); @Override void insert(int offset, long[] values); @Override void insert(int offset, long[] values, int valOffset, int len); @Override TLongList inverseGrep(TLongProcedure condition); @Override boolean isEmpty(); @Override TLongIterator iterator(); @Override int lastIndexOf(int offset, long value); @Override int lastIndexOf(long value); @Override long max(); @Override long min(); @Override synchronized void petrify(); @Override void remove(int offset, int length); @Override boolean remove(long value); @Override boolean removeAll(Collection<?> collection); @Override boolean removeAll(long[] array); @Override boolean removeAll(TLongCollection collection); @Override long removeAt(int offset); @Override long replace(int offset, long val); @Override boolean retainAll(Collection<?> collection); @Override boolean retainAll(long[] array); @Override boolean retainAll(TLongCollection collection); @Override void reverse(); @Override void reverse(int from, int to); @Override long set(int offset, long val); @Override void set(int offset, long[] values); @Override void set(int offset, long[] values, int valOffset, int length); @Override void shuffle(Random rand); @Override int size(); @Override void sort(); @Override void sort(int fromIndex, int toIndex); @Override PetrifyableTLongArrayList subList(int begin, int end); @Override long sum(); @Override long[] toArray(); @Override long[] toArray(int offset, int len); @Override long[] toArray(long[] dest); @Override long[] toArray(long[] dest, int offset, int len); @Override long[] toArray(long[] dest, int sourcePos, int destPos, int len); @Override void transformValues(TLongFunction function); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testRetainAllAfterPetrify1() { PETRIFIED_LIST.retainAll(TEST_LONG_ARRAY); } @Test(expected = UnsupportedOperationException.class) public void testRetainAllAfterPetrify2() { PETRIFIED_LIST.retainAll(TEST_LONG_COLLECTION); } @Test(expected = UnsupportedOperationException.class) public void testRetainAllAfterPetrify3() { PETRIFIED_LIST.retainAll(TEST_LONG_ARRAY_LIST); }
### Question: PetrifyableTLongArrayList extends AbstractPetrifyable implements PetrifyableTLongList { @Override public void reverse() { myList.reverse(); } PetrifyableTLongArrayList(); PetrifyableTLongArrayList(int capacity); PetrifyableTLongArrayList(long[] values); PetrifyableTLongArrayList(TLongCollection values); @Override boolean add(long val); @Override void add(long[] vals); @Override void add(long[] vals, int offset, int length); @Override boolean addAll(Collection<? extends Long> collection); @Override boolean addAll(long[] array); @Override boolean addAll(TLongCollection collection); @Override int binarySearch(long value); @Override int binarySearch(long value, int fromIndex, int toIndex); @Override void clear(); @Override boolean contains(long value); @Override boolean containsAll(Collection<?> collection); @Override boolean containsAll(long[] array); @Override boolean containsAll(TLongCollection collection); @Override void fill(int fromIndex, int toIndex, long val); @Override void fill(long val); @Override boolean forEach(TLongProcedure procedure); @Override boolean forEachDescending(TLongProcedure procedure); @Override long get(int offset); @Override long getNoEntryValue(); @Override long getSizeBytes(); @Override TLongList grep(TLongProcedure condition); @Override int indexOf(int offset, long value); @Override int indexOf(long value); @Override void insert(int offset, long value); @Override void insert(int offset, long[] values); @Override void insert(int offset, long[] values, int valOffset, int len); @Override TLongList inverseGrep(TLongProcedure condition); @Override boolean isEmpty(); @Override TLongIterator iterator(); @Override int lastIndexOf(int offset, long value); @Override int lastIndexOf(long value); @Override long max(); @Override long min(); @Override synchronized void petrify(); @Override void remove(int offset, int length); @Override boolean remove(long value); @Override boolean removeAll(Collection<?> collection); @Override boolean removeAll(long[] array); @Override boolean removeAll(TLongCollection collection); @Override long removeAt(int offset); @Override long replace(int offset, long val); @Override boolean retainAll(Collection<?> collection); @Override boolean retainAll(long[] array); @Override boolean retainAll(TLongCollection collection); @Override void reverse(); @Override void reverse(int from, int to); @Override long set(int offset, long val); @Override void set(int offset, long[] values); @Override void set(int offset, long[] values, int valOffset, int length); @Override void shuffle(Random rand); @Override int size(); @Override void sort(); @Override void sort(int fromIndex, int toIndex); @Override PetrifyableTLongArrayList subList(int begin, int end); @Override long sum(); @Override long[] toArray(); @Override long[] toArray(int offset, int len); @Override long[] toArray(long[] dest); @Override long[] toArray(long[] dest, int offset, int len); @Override long[] toArray(long[] dest, int sourcePos, int destPos, int len); @Override void transformValues(TLongFunction function); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testReverseAfterPetrify1() { PETRIFIED_LIST.reverse(); } @Test(expected = UnsupportedOperationException.class) public void testReverseAfterPetrify2() { PETRIFIED_LIST.reverse(0, 5); }
### Question: PetrifyableTLongArrayList extends AbstractPetrifyable implements PetrifyableTLongList { @Override public long set(int offset, long val) { return myList.set(offset, val); } PetrifyableTLongArrayList(); PetrifyableTLongArrayList(int capacity); PetrifyableTLongArrayList(long[] values); PetrifyableTLongArrayList(TLongCollection values); @Override boolean add(long val); @Override void add(long[] vals); @Override void add(long[] vals, int offset, int length); @Override boolean addAll(Collection<? extends Long> collection); @Override boolean addAll(long[] array); @Override boolean addAll(TLongCollection collection); @Override int binarySearch(long value); @Override int binarySearch(long value, int fromIndex, int toIndex); @Override void clear(); @Override boolean contains(long value); @Override boolean containsAll(Collection<?> collection); @Override boolean containsAll(long[] array); @Override boolean containsAll(TLongCollection collection); @Override void fill(int fromIndex, int toIndex, long val); @Override void fill(long val); @Override boolean forEach(TLongProcedure procedure); @Override boolean forEachDescending(TLongProcedure procedure); @Override long get(int offset); @Override long getNoEntryValue(); @Override long getSizeBytes(); @Override TLongList grep(TLongProcedure condition); @Override int indexOf(int offset, long value); @Override int indexOf(long value); @Override void insert(int offset, long value); @Override void insert(int offset, long[] values); @Override void insert(int offset, long[] values, int valOffset, int len); @Override TLongList inverseGrep(TLongProcedure condition); @Override boolean isEmpty(); @Override TLongIterator iterator(); @Override int lastIndexOf(int offset, long value); @Override int lastIndexOf(long value); @Override long max(); @Override long min(); @Override synchronized void petrify(); @Override void remove(int offset, int length); @Override boolean remove(long value); @Override boolean removeAll(Collection<?> collection); @Override boolean removeAll(long[] array); @Override boolean removeAll(TLongCollection collection); @Override long removeAt(int offset); @Override long replace(int offset, long val); @Override boolean retainAll(Collection<?> collection); @Override boolean retainAll(long[] array); @Override boolean retainAll(TLongCollection collection); @Override void reverse(); @Override void reverse(int from, int to); @Override long set(int offset, long val); @Override void set(int offset, long[] values); @Override void set(int offset, long[] values, int valOffset, int length); @Override void shuffle(Random rand); @Override int size(); @Override void sort(); @Override void sort(int fromIndex, int toIndex); @Override PetrifyableTLongArrayList subList(int begin, int end); @Override long sum(); @Override long[] toArray(); @Override long[] toArray(int offset, int len); @Override long[] toArray(long[] dest); @Override long[] toArray(long[] dest, int offset, int len); @Override long[] toArray(long[] dest, int sourcePos, int destPos, int len); @Override void transformValues(TLongFunction function); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testSetAfterPetrify1() { PETRIFIED_LIST.set(0, TEST_LONG); } @Test(expected = UnsupportedOperationException.class) public void testSetAfterPetrify2() { PETRIFIED_LIST.set(0, TEST_LONG_ARRAY); } @Test(expected = UnsupportedOperationException.class) public void testSetAfterPetrify3() { PETRIFIED_LIST.set(0, TEST_LONG_ARRAY, 0, 1); }
### Question: DefaultDataGroupAndTypeFactory implements DataGroupAndTypeFactory { @Override public DefaultDataTypeInfo createType(Toolbox toolbox, String providerType, String id, String typeName, String layerName) { return new DefaultDataTypeInfo(toolbox, providerType, id, typeName, layerName, false); } @Override DefaultDataGroupInfo createGroup(Toolbox toolbox, String providerType, String folderName, Consumer<DataGroupInfo> deleteListener); @Override DefaultDataTypeInfo createType(Toolbox toolbox, String providerType, String id, String typeName, String layerName); }### Answer: @Test public void testCreateType() { EasyMockSupport support = new EasyMockSupport(); MantleToolbox mantle = createMantle(support); Toolbox toolbox = createToolbox(support, mantle); support.replayAll(); DefaultDataGroupAndTypeFactory factory = new DefaultDataGroupAndTypeFactory(); DataTypeInfo type = factory.createType(toolbox, ourProviderType, ourTypeKey, "my type name", "My layer name"); assertEquals(ourProviderType, type.getSourcePrefix()); assertEquals(ourTypeKey, type.getTypeKey()); assertEquals("My layer name", type.getDisplayName()); assertEquals("my type name", type.getTypeName()); assertFalse(type.providerFiltersMetaData()); support.verifyAll(); }
### Question: PetrifyableTLongArrayList extends AbstractPetrifyable implements PetrifyableTLongList { @Override public void sort() { myList.sort(); } PetrifyableTLongArrayList(); PetrifyableTLongArrayList(int capacity); PetrifyableTLongArrayList(long[] values); PetrifyableTLongArrayList(TLongCollection values); @Override boolean add(long val); @Override void add(long[] vals); @Override void add(long[] vals, int offset, int length); @Override boolean addAll(Collection<? extends Long> collection); @Override boolean addAll(long[] array); @Override boolean addAll(TLongCollection collection); @Override int binarySearch(long value); @Override int binarySearch(long value, int fromIndex, int toIndex); @Override void clear(); @Override boolean contains(long value); @Override boolean containsAll(Collection<?> collection); @Override boolean containsAll(long[] array); @Override boolean containsAll(TLongCollection collection); @Override void fill(int fromIndex, int toIndex, long val); @Override void fill(long val); @Override boolean forEach(TLongProcedure procedure); @Override boolean forEachDescending(TLongProcedure procedure); @Override long get(int offset); @Override long getNoEntryValue(); @Override long getSizeBytes(); @Override TLongList grep(TLongProcedure condition); @Override int indexOf(int offset, long value); @Override int indexOf(long value); @Override void insert(int offset, long value); @Override void insert(int offset, long[] values); @Override void insert(int offset, long[] values, int valOffset, int len); @Override TLongList inverseGrep(TLongProcedure condition); @Override boolean isEmpty(); @Override TLongIterator iterator(); @Override int lastIndexOf(int offset, long value); @Override int lastIndexOf(long value); @Override long max(); @Override long min(); @Override synchronized void petrify(); @Override void remove(int offset, int length); @Override boolean remove(long value); @Override boolean removeAll(Collection<?> collection); @Override boolean removeAll(long[] array); @Override boolean removeAll(TLongCollection collection); @Override long removeAt(int offset); @Override long replace(int offset, long val); @Override boolean retainAll(Collection<?> collection); @Override boolean retainAll(long[] array); @Override boolean retainAll(TLongCollection collection); @Override void reverse(); @Override void reverse(int from, int to); @Override long set(int offset, long val); @Override void set(int offset, long[] values); @Override void set(int offset, long[] values, int valOffset, int length); @Override void shuffle(Random rand); @Override int size(); @Override void sort(); @Override void sort(int fromIndex, int toIndex); @Override PetrifyableTLongArrayList subList(int begin, int end); @Override long sum(); @Override long[] toArray(); @Override long[] toArray(int offset, int len); @Override long[] toArray(long[] dest); @Override long[] toArray(long[] dest, int offset, int len); @Override long[] toArray(long[] dest, int sourcePos, int destPos, int len); @Override void transformValues(TLongFunction function); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testSortAfterPetrify1() { PETRIFIED_LIST.sort(); } @Test(expected = UnsupportedOperationException.class) public void testSortAfterPetrify2() { PETRIFIED_LIST.sort(0, 5); }
### Question: PetrifyableTLongArrayList extends AbstractPetrifyable implements PetrifyableTLongList { @Override public void transformValues(TLongFunction function) { myList.transformValues(function); } PetrifyableTLongArrayList(); PetrifyableTLongArrayList(int capacity); PetrifyableTLongArrayList(long[] values); PetrifyableTLongArrayList(TLongCollection values); @Override boolean add(long val); @Override void add(long[] vals); @Override void add(long[] vals, int offset, int length); @Override boolean addAll(Collection<? extends Long> collection); @Override boolean addAll(long[] array); @Override boolean addAll(TLongCollection collection); @Override int binarySearch(long value); @Override int binarySearch(long value, int fromIndex, int toIndex); @Override void clear(); @Override boolean contains(long value); @Override boolean containsAll(Collection<?> collection); @Override boolean containsAll(long[] array); @Override boolean containsAll(TLongCollection collection); @Override void fill(int fromIndex, int toIndex, long val); @Override void fill(long val); @Override boolean forEach(TLongProcedure procedure); @Override boolean forEachDescending(TLongProcedure procedure); @Override long get(int offset); @Override long getNoEntryValue(); @Override long getSizeBytes(); @Override TLongList grep(TLongProcedure condition); @Override int indexOf(int offset, long value); @Override int indexOf(long value); @Override void insert(int offset, long value); @Override void insert(int offset, long[] values); @Override void insert(int offset, long[] values, int valOffset, int len); @Override TLongList inverseGrep(TLongProcedure condition); @Override boolean isEmpty(); @Override TLongIterator iterator(); @Override int lastIndexOf(int offset, long value); @Override int lastIndexOf(long value); @Override long max(); @Override long min(); @Override synchronized void petrify(); @Override void remove(int offset, int length); @Override boolean remove(long value); @Override boolean removeAll(Collection<?> collection); @Override boolean removeAll(long[] array); @Override boolean removeAll(TLongCollection collection); @Override long removeAt(int offset); @Override long replace(int offset, long val); @Override boolean retainAll(Collection<?> collection); @Override boolean retainAll(long[] array); @Override boolean retainAll(TLongCollection collection); @Override void reverse(); @Override void reverse(int from, int to); @Override long set(int offset, long val); @Override void set(int offset, long[] values); @Override void set(int offset, long[] values, int valOffset, int length); @Override void shuffle(Random rand); @Override int size(); @Override void sort(); @Override void sort(int fromIndex, int toIndex); @Override PetrifyableTLongArrayList subList(int begin, int end); @Override long sum(); @Override long[] toArray(); @Override long[] toArray(int offset, int len); @Override long[] toArray(long[] dest); @Override long[] toArray(long[] dest, int offset, int len); @Override long[] toArray(long[] dest, int sourcePos, int destPos, int len); @Override void transformValues(TLongFunction function); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testTransformValuesAfterPetrify2() { PETRIFIED_LIST.transformValues(new TLongFunction() { @Override public long execute(long value) { return 0; } }); }
### Question: DataTypeInfoUtilities { public static synchronized void copyDataTypeInfo(DataTypeInfo toCopy, DefaultDataTypeInfo theCopy, Object source) { boolean isActive = toCopy.getParent().activationProperty().isActive(); if (!isActive) { activate(toCopy); } theCopy.getMetaDataInfo().setGeometryColumn(toCopy.getMetaDataInfo().getGeometryColumn()); theCopy.getMetaDataInfo().setDataTypeInfo(theCopy); for (String colName : toCopy.getMetaDataInfo().getKeyNames()) { if (toCopy.getMetaDataInfo().getSpecialTypeForKey(colName) != null) { theCopy.getMetaDataInfo().setSpecialKey(colName, toCopy.getMetaDataInfo().getSpecialTypeForKey(colName), source); } theCopy.getMetaDataInfo().addKey(colName, toCopy.getMetaDataInfo().getKeyClassType(colName), source); } theCopy.getMapVisualizationInfo().setVisualizationType(toCopy.getMapVisualizationInfo().getVisualizationType()); if (!isActive) { deactivate(toCopy); } } private DataTypeInfoUtilities(); static synchronized void copyDataTypeInfo(DataTypeInfo toCopy, DefaultDataTypeInfo theCopy, Object source); static synchronized void ensureHasMetadata(DataTypeInfo info); }### Answer: @Test public void testCopyDataTypeInfo() throws PropertyChangeException, InterruptedException { EasyMockSupport support = new EasyMockSupport(); DefaultMetaDataInfo mdi = new DefaultMetaDataInfo(); mdi.setGeometryColumn("geom"); mdi.addKey("column1", Integer.class, this); mdi.addKey("geom", String.class, this); mdi.addKey("Lat", Double.class, this); mdi.setSpecialKey("Lat", LatitudeKey.DEFAULT, this); DefaultDataTypeInfo toCopy = new DefaultDataTypeInfo(null, "one", "first", "theFirst", "I am First", false, mdi); DefaultMapFeatureVisualizationInfo visInfo = new DefaultMapFeatureVisualizationInfo(MapVisualizationType.POINT_ELEMENTS); toCopy.setMapVisualizationInfo(visInfo); DefaultDataGroupInfo group = new DefaultDataGroupInfo(false, null, "test", "first"); toCopy.setParent(group); group.activationProperty().setActive(false); ActivationListener listener = createListener(support); group.activationProperty().addListener(listener); DefaultMetaDataInfo copiedMdi = new DefaultMetaDataInfo(); DefaultDataTypeInfo theCopy = new DefaultDataTypeInfo(null, "two", "two", "theFirst", "I am second", false, copiedMdi); DefaultMapFeatureVisualizationInfo theCopyVisInfo = new DefaultMapFeatureVisualizationInfo(MapVisualizationType.UNKNOWN); theCopy.setMapVisualizationInfo(theCopyVisInfo); support.replayAll(); DataTypeInfoUtilities.copyDataTypeInfo(toCopy, theCopy, this); assertNotSame(mdi, theCopy.getMetaDataInfo()); assertEquals("geom", theCopy.getMetaDataInfo().getGeometryColumn()); assertEquals(theCopy, ((DefaultMetaDataInfo)theCopy.getMetaDataInfo()).getDataTypeInfo()); assertEquals(Integer.class, theCopy.getMetaDataInfo().getKeyClassType("column1")); assertEquals(String.class, theCopy.getMetaDataInfo().getKeyClassType("geom")); assertEquals(Double.class, theCopy.getMetaDataInfo().getKeyClassType("Lat")); assertEquals("Lat", theCopy.getMetaDataInfo().getLatitudeKey()); assertEquals(MapVisualizationType.POINT_ELEMENTS, theCopy.getMapVisualizationInfo().getVisualizationType()); support.verifyAll(); }
### Question: AnimationExaminationUtils { public static Pair<TimeSpan, Duration> getSpanAndDuration(AnimationPlan plan) { List<? extends TimeSpan> sequence = plan.getAnimationSequence(); Duration maxDuration = Seconds.ZERO; for (TimeSpan span : sequence) { if (span.getDuration().compareTo(maxDuration) > 0) { maxDuration = span.getDuration(); } } Duration duration = new DurationUnitsProvider().getLargestIntegerUnitType(maxDuration); if (duration == null || duration.getMagnitude().intValue() != 1) { duration = Months.ONE; } Date start = determineStartDate(sequence.get(0), duration.getClass()); Date end = determineEndDate(sequence.get(sequence.size() - 1), duration.getClass()); TimeSpan span = TimeSpan.get(start, end); return new Pair<TimeSpan, Duration>(span, duration); } private AnimationExaminationUtils(); static Pair<TimeSpan, Duration> getSpanAndDuration(AnimationPlan plan); }### Answer: @Test public void testGetSpanAndDuration() throws ParseException { List<TimeSpan> sequence = getSpansForString(ourThreeMonths1); AnimationPlan plan = new DefaultAnimationPlan(sequence, EndBehavior.WRAP); Pair<TimeSpan, Duration> spanAndDur = AnimationExaminationUtils.getSpanAndDuration(plan); Date spanStart = new GregorianCalendar(2013, 9, 1).getTime(); Date spanEnd = new GregorianCalendar(2013, 11, 31).getTime(); TimeSpan monthSpan = TimeSpan.get(spanStart, spanEnd); Assert.assertEquals(monthSpan, spanAndDur.getFirstObject()); Assert.assertEquals(Months.ONE, spanAndDur.getSecondObject()); sequence = getSpansForString(ourThreeMonths2); plan = new DefaultAnimationPlan(sequence, EndBehavior.WRAP); spanAndDur = AnimationExaminationUtils.getSpanAndDuration(plan); Assert.assertEquals(monthSpan, spanAndDur.getFirstObject()); Assert.assertEquals(Months.ONE, spanAndDur.getSecondObject()); sequence = getSpansForString(ourThreeMonths3); plan = new DefaultAnimationPlan(sequence, EndBehavior.WRAP); spanAndDur = AnimationExaminationUtils.getSpanAndDuration(plan); Assert.assertEquals(monthSpan, spanAndDur.getFirstObject()); Assert.assertEquals(Months.ONE, spanAndDur.getSecondObject()); sequence = getSpansForString(ourFiveWeeks); plan = new DefaultAnimationPlan(sequence, EndBehavior.WRAP); spanAndDur = AnimationExaminationUtils.getSpanAndDuration(plan); spanStart = new GregorianCalendar(2013, 11, 1).getTime(); spanEnd = new GregorianCalendar(2014, 0, 4).getTime(); Assert.assertEquals(TimeSpan.get(spanStart, spanEnd), spanAndDur.getFirstObject()); Assert.assertEquals(Weeks.ONE, spanAndDur.getSecondObject()); sequence = getSpansForString(ourDays); plan = new DefaultAnimationPlan(sequence, EndBehavior.WRAP); spanAndDur = AnimationExaminationUtils.getSpanAndDuration(plan); spanEnd = new GregorianCalendar(2014, 0, 5).getTime(); Assert.assertEquals(TimeSpan.get(spanStart, spanEnd), spanAndDur.getFirstObject()); Assert.assertEquals(Days.ONE, spanAndDur.getSecondObject()); }
### Question: ConcurrentLazyMap extends LazyMap<K, V> { @Override public V get(Object key, Factory<? super K, ? extends V> factory) { Utilities.checkNull(factory, "factory"); if (key != null && !getKeyType().isInstance(key)) { return getIfExists(key); } V value = getIfExists(key); if (value != null) { return value; } @SuppressWarnings("unchecked") K k = (K)key; Lock lock = getLock(k); lock.lock(); try { value = getIfExists(key); if (value == null) { value = factory.create(k); getMap().put(k, value); } return value; } finally { lock.unlock(); } } ConcurrentLazyMap(Map<K, V> map, Class<? extends K> keyType); ConcurrentLazyMap(Map<K, V> map, Class<? extends K> keyType, Factory<? super K, ? extends V> factory); static ConcurrentLazyMap<K, V> create(Map<K, V> map, Class<? extends K> keyType); static ConcurrentLazyMap<K, V> create(Map<K, V> map, Class<? extends K> keyType, Factory<? super K, ? extends V> factory); @Override V get(Object key, Factory<? super K, ? extends V> factory); Lock getLock(K key); @Override V put(K key, V value); @Override void putAll(Map<? extends K, ? extends V> m); }### Answer: @Test public void testGet() throws InterruptedException, ExecutionException { final AtomicInteger runningCount = new AtomicInteger(); final AtomicBoolean pause5 = new AtomicBoolean(true); final AtomicBoolean pause6 = new AtomicBoolean(true); Map<Integer, Float> map = Collections.synchronizedMap(New.<Integer, Float>map()); final Map<Integer, Float> clm = new ConcurrentLazyMap<Integer, Float>(map, Integer.class, new LazyMap.Factory<Integer, Float>() { @Override public Float create(Integer key) { AtomicBoolean pause = key.intValue() == 5 ? pause5 : pause6; synchronized (pause) { while (pause.get()) { try { pause.wait(); } catch (InterruptedException e) { } } } return Float.valueOf(key.floatValue()); } }); ExecutorService exec = Executors.newFixedThreadPool(3); Future<Float> future5a = exec.submit(new Callable<Float>() { @Override public Float call() { synchronized (runningCount) { runningCount.incrementAndGet(); runningCount.notifyAll(); } return clm.get(Integer.valueOf(5)); } }); Future<Float> future5b = exec.submit(new Callable<Float>() { @Override public Float call() { synchronized (runningCount) { runningCount.incrementAndGet(); runningCount.notifyAll(); } return clm.get(Integer.valueOf(5)); } }); Future<Float> future6 = exec.submit(new Callable<Float>() { @Override public Float call() { synchronized (runningCount) { runningCount.incrementAndGet(); runningCount.notifyAll(); } return clm.get(Integer.valueOf(6)); } }); synchronized (runningCount) { while (runningCount.get() < 3) { runningCount.wait(); } } Assert.assertFalse(future5a.isDone()); Assert.assertFalse(future5b.isDone()); Assert.assertFalse(future6.isDone()); synchronized (pause6) { pause6.set(false); pause6.notifyAll(); } Assert.assertEquals(6f, future6.get().floatValue(), 0f); Assert.assertFalse(future5a.isDone()); Assert.assertFalse(future5b.isDone()); Assert.assertTrue(future6.isDone()); synchronized (pause5) { pause5.set(false); pause5.notifyAll(); } Assert.assertSame(future5a.get(), future5b.get()); Assert.assertEquals(5f, future5a.get().floatValue(), 0f); }
### Question: ElementData { public MetaDataProvider getMetaDataProvider() { return myMetaDataProvider; } ElementData(); ElementData(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); boolean found(); Long getID(); MapGeometrySupport getMapGeometrySupport(); MetaDataProvider getMetaDataProvider(); TimeSpan getTimeSpan(); VisualizationState getVisualizationState(); final void updateValues(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); }### Answer: @Test public void testGetMetaDataProvider() { assertEquals(myMetaDataProvider, myTestObject.getMetaDataProvider()); }
### Question: ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public int size() { return myQueue.size(); } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer: @Test public void testSizeZero() { assertEquals(0, myObservableBuffer.size()); }
### Question: ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public boolean offer(final E element) { boolean changed = false; synchronized (myQueue) { beginChange(); while (remainingCapacity() < 1) { final E removedElement = myQueue.removeFirst(); if (removedElement != null) { nextRemove(0, removedElement); } } changed = myQueue.offer(element); if (changed) { nextAdd(myQueue.size() - 1, myQueue.size()); } endChange(); } return changed; } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer: @Test public void testOfferUnderCapacity() { myObservableBuffer.offer("one"); myObservableBuffer.offer("two"); myObservableBuffer.offer("three"); myObservableBuffer.offer("four"); Object[] array = myObservableBuffer.toArray(); assertEquals(4, array.length); assertEquals("one", array[0]); assertEquals("two", array[1]); assertEquals("three", array[2]); assertEquals("four", array[3]); } @Test public void testOfferOverCapacity() { myObservableBuffer.offer("one"); myObservableBuffer.offer("two"); myObservableBuffer.offer("three"); myObservableBuffer.offer("four"); myObservableBuffer.offer("five"); myObservableBuffer.offer("six"); myObservableBuffer.offer("seven"); Object[] array = myObservableBuffer.toArray(); assertEquals(5, array.length); assertEquals("three", array[0]); assertEquals("four", array[1]); assertEquals("five", array[2]); assertEquals("six", array[3]); assertEquals("seven", array[4]); }
### Question: ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public boolean add(final E e) { if (remainingCapacity() == 0) { throw new IllegalStateException("Queue full"); } boolean changed = false; synchronized (myQueue) { beginChange(); try { if (myQueue.add(e)) { changed = true; nextAdd(myQueue.size() - 1, myQueue.size()); } } finally { endChange(); } } return changed; } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer: @Test public void testAddOne() { myObservableBuffer.add("one"); Object[] array = myObservableBuffer.toArray(); assertEquals(1, array.length); assertEquals("one", array[0]); } @Test public void testAddUnderCapacity() { myObservableBuffer.add("one"); myObservableBuffer.add("two"); myObservableBuffer.add("three"); myObservableBuffer.add("four"); Object[] array = myObservableBuffer.toArray(); assertEquals(4, array.length); assertEquals("one", array[0]); assertEquals("two", array[1]); assertEquals("three", array[2]); assertEquals("four", array[3]); } @Test(expected = IllegalStateException.class) public void testAddOverCapacity() { myObservableBuffer.add("one"); myObservableBuffer.add("two"); myObservableBuffer.add("three"); myObservableBuffer.add("four"); myObservableBuffer.add("five"); myObservableBuffer.add("six"); myObservableBuffer.add("seven"); }
### Question: ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public E poll() { E removedItem = null; synchronized (myQueue) { beginChange(); try { removedItem = myQueue.pollLast(); nextRemove(0, removedItem); } finally { endChange(); } } return removedItem; } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer: @Test public void testPollEmpty() { assertNull(myObservableBuffer.poll()); }
### Question: ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public E element() { if (myQueue.isEmpty()) { throw new NoSuchElementException(); } return myQueue.peekLast(); } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer: @Test(expected = NoSuchElementException.class) public void testElementEmpty() { myObservableBuffer.element(); }
### Question: ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public E peek() { return myQueue.peekLast(); } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer: @Test public void testPeekEmpty() { assertNull(myObservableBuffer.peek()); }
### Question: ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public E get(final int index) { if (index < 0 || index >= myQueue.size()) { throw new IndexOutOfBoundsException(0); } E item = null; synchronized (myQueue) { final Iterator<E> iterator = myQueue.iterator(); for (int i = 0; i < index; i++) { iterator.next(); } item = iterator.next(); } return item; } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer: @Test(expected = IndexOutOfBoundsException.class) public void testGetIntNegative() { myObservableBuffer.get(-1); } @Test(expected = IndexOutOfBoundsException.class) public void testGetIntZeroEmpty() { myObservableBuffer.get(0); }
### Question: LazyMap extends WrappedMap<K, V> { @Override public V get(Object key) throws IllegalStateException { Factory<? super K, ? extends V> factory = getFactory(); if (factory == null) { throw new IllegalStateException("No factory installed."); } return get(key, factory); } LazyMap(Map<K, V> map, Class<? extends K> keyType); LazyMap(Map<K, V> map, Class<? extends K> keyType, Factory<? super K, ? extends V> factory); static LazyMap<K, Collection<E>> create(Map<K, Collection<E>> map, Class<K> keyType, CollectionProvider<E> provider); static LazyMap<K, List<E>> create(Map<K, List<E>> map, Class<K> keyType, ListProvider<E> provider); static LazyMap<K, Set<E>> create(Map<K, Set<E>> map, Class<K> keyType, SetProvider<E> provider); static LazyMap<K, V> create(Map<K, V> map, Class<? extends K> keyType); static LazyMap<K, V> create(Map<K, V> map, Class<? extends K> keyType, Factory<? super K, ? extends V> factory); static Factory<Object, Collection<V>> providerToFactory(final CollectionProvider<V> provider); static Factory<Object, List<V>> providerToFactory(final ListProvider<V> provider); static Factory<Object, Set<V>> providerToFactory(final SetProvider<V> provider); @Override V get(Object key); V get(Object key, Factory<? super K, ? extends V> factory); V getIfExists(Object key); @Override V put(K key, V value); @Override void putAll(Map<? extends K, ? extends V> m); }### Answer: @Test public void testContainsKey() { Assert.assertTrue(myLazyMap.containsKey(null)); Assert.assertTrue(myLazyMap.containsKey(Integer.valueOf(1))); Assert.assertFalse(myLazyMap.containsKey(Integer.valueOf(0))); myLazyMap.get(Integer.valueOf(0)); Assert.assertTrue(myLazyMap.containsKey(Integer.valueOf(0))); } @Test public void testContainsValue() { Assert.assertTrue(myLazyMap.containsValue(NULL_VALUE1)); Assert.assertTrue(myLazyMap.containsValue("1")); Assert.assertFalse(myLazyMap.containsValue("0")); myLazyMap.get(Integer.valueOf(0)); Assert.assertTrue(myLazyMap.containsValue("0")); } @SuppressWarnings("unlikely-arg-type") @Test public void testGet() { Assert.assertEquals(NULL_VALUE1, myLazyMap.get(null)); Assert.assertEquals("1", myLazyMap.get(Integer.valueOf(1))); Assert.assertEquals("2", myLazyMap.get(Integer.valueOf(2))); Assert.assertEquals("3", myLazyMap.get(Integer.valueOf(3))); Assert.assertEquals(FOUR, myLazyMap.get(Integer.valueOf(4))); Assert.assertEquals("5", myLazyMap.get(Integer.valueOf(5))); Assert.assertNull(myLazyMap.get(new Object())); Assert.assertNull(myLazyMap.get(Float.valueOf(1f))); }
### Question: StateControllerImpl implements StateController { @Override public void saveState(String id, String description, Collection<? extends String> tags, Collection<? extends String> modules, boolean saveToApplication, OutputStream outputStream) { StateType state = new StateType(); myModuleStateManager.saveState(id, description, tags, modules, state); if (outputStream != null) { try { new StateV4ReaderWriter().write(state, outputStream); } catch (JAXBException e) { LOGGER.error(e, e); } } if (saveToApplication) { myModuleStateManager.registerState(id, description, tags, modules, state); hookState(id, state); } } StateControllerImpl(Toolbox toolbox); @Override void deactivateAllStates(); @Override Collection<? extends String> getAvailableModules(); @Override Collection<? extends String> getAvailableStates(); @Override Collection<? extends String> getModulesThatCanSaveState(); @Override Collection<? extends String> getModulesThatSaveStateByDefault(); @Override Map<String, Collection<? extends String>> getStateDependenciesForModules(Collection<? extends String> modules); @Override String getStateDescription(String state); @Override Collection<? extends String> getStateTags(String state); @Override boolean isStateActive(String state); @Override void removeStates(Collection<? extends String> stateIds); @Override void saveState(String id, String description, Collection<? extends String> tags, Collection<? extends String> modules, boolean saveToApplication, OutputStream outputStream); @Override void toggleState(String id); @Override void hookState(String id, StateType state); }### Answer: @Test public void testSaveState() throws SAXException, IOException, ParserConfigurationException { ModuleStateManager moduleStateManager = EasyMock.createMock(ModuleStateManager.class); String id = "stateid"; String description = "State description"; Collection<? extends String> tags = Arrays.asList("tag1", "tag2", "tag3"); @SuppressWarnings("unchecked") Collection<? extends String> modules = EasyMock.createMock(Collection.class); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final Capture<StateType> stateCapture = EasyMock.newCapture(); moduleStateManager.saveState(EasyMock.eq(id), EasyMock.eq(description), EasyMock.same(tags), EasyMock.same(modules), EasyMock.isA(StateType.class)); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() { StateType state = (StateType)EasyMock.getCurrentArguments()[4]; stateCapture.setValue(state); return null; } }); moduleStateManager.registerState(EasyMock.eq(id), EasyMock.eq(description), EasyMock.same(tags), EasyMock.same(modules), EasyMockHelper.eq(stateCapture)); EasyMockSupport support = new EasyMockSupport(); Toolbox toolbox = createToolbox(support, moduleStateManager); Collection<String> idCollection = New.collection(); EasyMock.expect(moduleStateManager.getRegisteredStateIds()).andReturn(idCollection); EasyMock.replay(moduleStateManager, modules); support.replayAll(); StateControllerImpl controller = new StateControllerImpl(toolbox); controller.saveState(id, description, tags, modules, true, outputStream); support.verifyAll(); EasyMock.verify(moduleStateManager, modules); XMLUtilities.newDocumentBuilderNS().parse(new ByteArrayInputStream(outputStream.toByteArray())); }
### Question: LazyMap extends WrappedMap<K, V> { @Override public V put(K key, V value) { synchronized (getMap()) { return super.put(key, value); } } LazyMap(Map<K, V> map, Class<? extends K> keyType); LazyMap(Map<K, V> map, Class<? extends K> keyType, Factory<? super K, ? extends V> factory); static LazyMap<K, Collection<E>> create(Map<K, Collection<E>> map, Class<K> keyType, CollectionProvider<E> provider); static LazyMap<K, List<E>> create(Map<K, List<E>> map, Class<K> keyType, ListProvider<E> provider); static LazyMap<K, Set<E>> create(Map<K, Set<E>> map, Class<K> keyType, SetProvider<E> provider); static LazyMap<K, V> create(Map<K, V> map, Class<? extends K> keyType); static LazyMap<K, V> create(Map<K, V> map, Class<? extends K> keyType, Factory<? super K, ? extends V> factory); static Factory<Object, Collection<V>> providerToFactory(final CollectionProvider<V> provider); static Factory<Object, List<V>> providerToFactory(final ListProvider<V> provider); static Factory<Object, Set<V>> providerToFactory(final SetProvider<V> provider); @Override V get(Object key); V get(Object key, Factory<? super K, ? extends V> factory); V getIfExists(Object key); @Override V put(K key, V value); @Override void putAll(Map<? extends K, ? extends V> m); }### Answer: @Test public void testPut() { Assert.assertEquals("1", myLazyMap.put(Integer.valueOf(1), ONE)); Assert.assertEquals(ONE, myWrappedMap.get(Integer.valueOf(1))); Assert.assertEquals(NULL_VALUE1, myLazyMap.put(null, NULL_VALUE2)); Assert.assertEquals(NULL_VALUE2, myWrappedMap.get(null)); }
### Question: LazyMap extends WrappedMap<K, V> { @Override public void putAll(Map<? extends K, ? extends V> m) { synchronized (getMap()) { super.putAll(m); } } LazyMap(Map<K, V> map, Class<? extends K> keyType); LazyMap(Map<K, V> map, Class<? extends K> keyType, Factory<? super K, ? extends V> factory); static LazyMap<K, Collection<E>> create(Map<K, Collection<E>> map, Class<K> keyType, CollectionProvider<E> provider); static LazyMap<K, List<E>> create(Map<K, List<E>> map, Class<K> keyType, ListProvider<E> provider); static LazyMap<K, Set<E>> create(Map<K, Set<E>> map, Class<K> keyType, SetProvider<E> provider); static LazyMap<K, V> create(Map<K, V> map, Class<? extends K> keyType); static LazyMap<K, V> create(Map<K, V> map, Class<? extends K> keyType, Factory<? super K, ? extends V> factory); static Factory<Object, Collection<V>> providerToFactory(final CollectionProvider<V> provider); static Factory<Object, List<V>> providerToFactory(final ListProvider<V> provider); static Factory<Object, Set<V>> providerToFactory(final SetProvider<V> provider); @Override V get(Object key); V get(Object key, Factory<? super K, ? extends V> factory); V getIfExists(Object key); @Override V put(K key, V value); @Override void putAll(Map<? extends K, ? extends V> m); }### Answer: @Test public void testPutAll() { Map<Integer, String> map = new HashMap<>(); map.put(null, NULL_VALUE2); map.put(Integer.valueOf(1), ONE); map.put(Integer.valueOf(2), TWO); map.put(Integer.valueOf(3), THREE); myLazyMap.putAll(map); Assert.assertEquals(NULL_VALUE2, myLazyMap.get(null)); Assert.assertEquals(ONE, myLazyMap.get(Integer.valueOf(1))); Assert.assertEquals(TWO, myLazyMap.get(Integer.valueOf(2))); Assert.assertEquals(THREE, myLazyMap.get(Integer.valueOf(3))); }
### Question: LimitedFertilityBlockingQueue extends LinkedBlockingQueue<E> { @Override public E take() throws InterruptedException { return take(myFactory); } LimitedFertilityBlockingQueue(int maxChildren, Factory<? extends E> factory); LimitedFertilityBlockingQueue(int capacity, int maxChildren, Factory<? extends E> factory); int getCount(); int getMaxChildren(); @Override E poll(); E poll(Factory<? extends E> factory); E poll(Factory<? extends E> factory, @Nullable Consumer<? super E> adapter); E poll(Factory<? extends E> factory, long timeout, TimeUnit unit); E poll(Factory<? extends E> factory, @Nullable Consumer<? super E> adapter, long timeout, TimeUnit unit); @Override E poll(long timeout, TimeUnit unit); @Override E take(); E take(Factory<? extends E> factory); E take(Factory<? extends E> factory, @Nullable Consumer<? super E> adapter); }### Answer: @Test public void testTake() throws InterruptedException, ExecutionException { LimitedFertilityBlockingQueue.Factory<Integer> factory = new FactoryImplementation(); final LimitedFertilityBlockingQueue<Integer> queue = new LimitedFertilityBlockingQueue<>(10, factory); for (int index = 0; index < 10; ++index) { Assert.assertEquals(Integer.valueOf(index), queue.take()); } Callable<Integer> task = new Callable<Integer>() { @Override public Integer call() throws InterruptedException { return queue.take(); } }; Future<Integer> future = Executors.newSingleThreadExecutor().submit(task); try { future.get(100L, TimeUnit.MILLISECONDS); Assert.fail(SHOULD_HAVE_TIMED_OUT); } catch (TimeoutException e) { } Assert.assertTrue(queue.add(Integer.valueOf(11))); Assert.assertEquals(Integer.valueOf(11), future.get()); } @Test public void testTakeFactory() throws InterruptedException, ExecutionException { final LimitedFertilityBlockingQueue.Factory<Integer> factory = new FactoryImplementation(); final LimitedFertilityBlockingQueue<Integer> queue = new LimitedFertilityBlockingQueue<>(10, null); for (int index = 0; index < 10; ++index) { Assert.assertEquals(Integer.valueOf(index), queue.take(factory)); } Callable<Integer> task = new Callable<Integer>() { @Override public Integer call() throws InterruptedException { return queue.take(factory); } }; Future<Integer> future = Executors.newSingleThreadExecutor().submit(task); try { future.get(100L, TimeUnit.MILLISECONDS); Assert.fail(SHOULD_HAVE_TIMED_OUT); } catch (TimeoutException e) { } Assert.assertTrue(queue.add(Integer.valueOf(11))); Assert.assertEquals(Integer.valueOf(11), future.get()); } @Test public void testTakeFactoryConsumer() throws InterruptedException, ExecutionException { final LimitedFertilityBlockingQueue.Factory<Integer> factory = new FactoryImplementation(); final ConsumerImplementation consumer = new ConsumerImplementation(); final LimitedFertilityBlockingQueue<Integer> queue = new LimitedFertilityBlockingQueue<>(10, null); for (int index = 0; index < 10; ++index) { Assert.assertEquals(Integer.valueOf(index), queue.take(factory, consumer)); } Assert.assertTrue(consumer.getValues().isEmpty()); Callable<Integer> task = new Callable<Integer>() { @Override public Integer call() throws InterruptedException { return queue.take(factory, consumer); } }; Future<Integer> future = Executors.newSingleThreadExecutor().submit(task); try { future.get(100L, TimeUnit.MILLISECONDS); Assert.fail(SHOULD_HAVE_TIMED_OUT); } catch (TimeoutException e) { } Assert.assertTrue(queue.add(Integer.valueOf(11))); Assert.assertEquals(Integer.valueOf(11), future.get()); Assert.assertEquals(1, consumer.getValues().size()); Assert.assertEquals(Integer.valueOf(11), consumer.getValues().get(0)); }
### Question: EllipseController { public void applyUnits() { List<String> units = New.list(); Collection<Class<? extends Length>> availableUnits = myUnitsRegistry.getAvailableUnits(Length.class, false); for (Class<? extends Length> lengthType : availableUnits) { String selectionLabel = Length.getSelectionLabel(lengthType); units.add(selectionLabel); } myModel.getAvailableUnits().addAll(units); if (StringUtils.isEmpty(myModel.getSemiMajorUnits()) || StringUtils.isEmpty(myModel.getSemiMinorUnits())) { String defaultUnit = Length.getSelectionLabel(myUnitsRegistry.getPreferredUnits(Length.class)); if (!units.contains(defaultUnit)) { defaultUnit = units.get(0); } if (StringUtils.isEmpty(myModel.getSemiMajorUnits())) { myModel.setSemiMajorUnits(defaultUnit); } if (StringUtils.isEmpty(myModel.getSemiMinorUnits())) { myModel.setSemiMinorUnits(defaultUnit); } } } EllipseController(UnitsRegistry unitsRegistry, EllipseModel model); void applyUnits(); }### Answer: @Test public void test() { EasyMockSupport support = new EasyMockSupport(); UnitsRegistry unitRegistry = createRegistry(support, Feet.class); support.replayAll(); EllipseModel model = new EllipseModel(); EllipseController controller = new EllipseController(unitRegistry, model); controller.applyUnits(); assertEquals(New.list("nautical miles", "statute miles", "feet"), model.getAvailableUnits()); assertEquals("feet", model.getSemiMajorUnits()); assertEquals("feet", model.getSemiMinorUnits()); support.verifyAll(); } @Test public void testAutoDefault() { EasyMockSupport support = new EasyMockSupport(); UnitsRegistry unitRegistry = createRegistry(support, AutoscaleImperial.class); support.replayAll(); EllipseModel model = new EllipseModel(); EllipseController controller = new EllipseController(unitRegistry, model); controller.applyUnits(); assertEquals(New.list("nautical miles", "statute miles", "feet"), model.getAvailableUnits()); assertEquals("nautical miles", model.getSemiMajorUnits()); assertEquals("nautical miles", model.getSemiMinorUnits()); support.verifyAll(); }
### Question: StreamUtilities { public static <T> boolean anyMatch(Iterable<? extends T> input, Predicate<? super T> filter) { for (T in : input) { if (filter.test(in)) { return true; } } return false; } private StreamUtilities(); static boolean anyMatch(Iterable<? extends T> input, Predicate<? super T> filter); static List<T> filter(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static T[] filter(T[] input, Predicate<? super T> predicate); static T filterOne(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static Stream<T> filterDowncast(Stream<?> input, Class<T> type); static Collection<R> map(Collection<? extends T> input, Function<? super T, ? extends R> mapper, CollectionProvider<R> collectionProvider); @SuppressWarnings("unchecked") static List<R> map(Iterable<? extends T> input, Function<? super T, ? extends R> mapper); }### Answer: @Test public void testAnyMatch() { boolean result; result = StreamUtilities.anyMatch(Collections.emptyList(), null); Assert.assertFalse(result); result = StreamUtilities.anyMatch(INPUT, new Predicate<String>() { @Override public boolean test(String s) { return s.charAt(0) == 'A'; } }); Assert.assertTrue(result); result = StreamUtilities.anyMatch(INPUT, new Predicate<String>() { @Override public boolean test(String s) { return s.charAt(0) == 'C'; } }); Assert.assertFalse(result); }
### Question: StreamUtilities { public static <T> List<T> filter(Collection<? extends T> input, Predicate<? super T> predicate) { List<T> list; if (predicate != null) { list = CollectionUtilities.hasContent(input) ? input.stream().filter(predicate).collect(Collectors.toList()) : New.list(); } else { list = New.list(input); } return list; } private StreamUtilities(); static boolean anyMatch(Iterable<? extends T> input, Predicate<? super T> filter); static List<T> filter(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static T[] filter(T[] input, Predicate<? super T> predicate); static T filterOne(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static Stream<T> filterDowncast(Stream<?> input, Class<T> type); static Collection<R> map(Collection<? extends T> input, Function<? super T, ? extends R> mapper, CollectionProvider<R> collectionProvider); @SuppressWarnings("unchecked") static List<R> map(Iterable<? extends T> input, Function<? super T, ? extends R> mapper); }### Answer: @Test public void testFilter() { Collection<String> actual; Collection<String> expected; expected = New.list(0); actual = StreamUtilities.filter(Collections.<String>emptyList(), null); Assert.assertEquals(expected, actual); expected = Arrays.asList(new String[] { "Apple", "Apricot" }); actual = StreamUtilities.filter(INPUT, new Predicate<String>() { @Override public boolean test(String s) { return s.charAt(0) == 'A'; } }); Assert.assertEquals(expected, actual); actual = StreamUtilities.filter(INPUT, new Predicate<Object>() { @Override public boolean test(Object o) { return o.toString().charAt(0) == 'A'; } }); Assert.assertEquals(expected, actual); } @Test public void testFilterArray() { String[] expected = new String[] { "Apple", "Apricot" }; String[] actual; actual = StreamUtilities.filter(INPUT_ARRAY, new Predicate<String>() { @Override public boolean test(String s) { return s.charAt(0) == 'A'; } }); Assert.assertTrue(Arrays.equals(expected, actual)); }
### Question: StreamUtilities { public static <T> T filterOne(Collection<? extends T> input, Predicate<? super T> predicate) { return predicate != null ? input.stream().filter(predicate).findFirst().orElse(null) : null; } private StreamUtilities(); static boolean anyMatch(Iterable<? extends T> input, Predicate<? super T> filter); static List<T> filter(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static T[] filter(T[] input, Predicate<? super T> predicate); static T filterOne(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static Stream<T> filterDowncast(Stream<?> input, Class<T> type); static Collection<R> map(Collection<? extends T> input, Function<? super T, ? extends R> mapper, CollectionProvider<R> collectionProvider); @SuppressWarnings("unchecked") static List<R> map(Iterable<? extends T> input, Function<? super T, ? extends R> mapper); }### Answer: @Test public void testFilterOne() { String expected; String actual; expected = null; actual = StreamUtilities.filterOne(Collections.<String>emptyList(), null); Assert.assertEquals(expected, actual); expected = "Apple"; actual = StreamUtilities.filterOne(INPUT, new Predicate<String>() { @Override public boolean test(String s) { return s.charAt(0) == 'A'; } }); Assert.assertEquals(expected, actual); actual = StreamUtilities.filterOne(INPUT, new Predicate<Object>() { @Override public boolean test(Object o) { return o.toString().charAt(0) == 'A'; } }); Assert.assertEquals(expected, actual); }
### Question: StreamUtilities { @SuppressWarnings("unchecked") public static <T> Stream<T> filterDowncast(Stream<?> input, Class<T> type) { return input.filter(obj -> type.isInstance(obj)).map(obj -> (T)obj); } private StreamUtilities(); static boolean anyMatch(Iterable<? extends T> input, Predicate<? super T> filter); static List<T> filter(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static T[] filter(T[] input, Predicate<? super T> predicate); static T filterOne(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static Stream<T> filterDowncast(Stream<?> input, Class<T> type); static Collection<R> map(Collection<? extends T> input, Function<? super T, ? extends R> mapper, CollectionProvider<R> collectionProvider); @SuppressWarnings("unchecked") static List<R> map(Iterable<? extends T> input, Function<? super T, ? extends R> mapper); }### Answer: @Test public void testFilterDowcast() { List<Number> input = Arrays.asList(Integer.valueOf(1), Long.valueOf(2)); Assert.assertEquals(Arrays.asList(Integer.valueOf(1)), StreamUtilities.filterDowncast(input.stream(), Integer.class).collect(Collectors.toList())); }
### Question: TinySet extends AbstractProxySet<E> { public static <T> Set<T> add(Set<T> input, T e) { if (input.isEmpty()) { return Collections.<T>singleton(e); } else if (input.size() == 1) { Set<T> result = New.set(2); result.addAll(input); if (result.add(e)) { return result; } return input; } else { input.add(e); return input; } } static Set<T> add(Set<T> input, T e); static Set<T> addAll(Set<T> input, Collection<? extends T> c); static Set<T> remove(Set<T> set, Object o); static Set<T> removeAll(Set<T> set, Collection<T> c); static Set<T> retainAll(Set<T> mySet, Collection<?> c); @Override boolean add(E e); @Override boolean addAll(Collection<? extends E> c); @Override void clear(); @Override boolean remove(Object o); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); }### Answer: @Test public void testAdd() { TinySet<Object> set = new TinySet<>(); checkSize0(set); Assert.assertTrue(set.add(TEST_OBJ1)); checkSize1(set); Assert.assertFalse(set.add(TEST_OBJ1)); checkSize1(set); Assert.assertTrue(set.add(TEST_OBJ2)); checkSizeN(set, 2); Assert.assertTrue(set.add(TEST_OBJ3)); checkSizeN(set, 3); } @Test public void testStaticAdd() { Set<Object> set = Collections.emptySet(); checkSize0(set); set = TinySet.add(set, TEST_OBJ1); checkSize1(set); Assert.assertTrue(set.contains(TEST_OBJ1)); set = TinySet.add(set, TEST_OBJ1); checkSize1(set); Assert.assertTrue(set.contains(TEST_OBJ1)); set = TinySet.add(set, TEST_OBJ2); checkSizeN(set, 2); Assert.assertTrue(set.contains(TEST_OBJ2)); set = TinySet.add(set, TEST_OBJ3); checkSizeN(set, 3); Assert.assertTrue(set.contains(TEST_OBJ3)); }
### Question: TinySet extends AbstractProxySet<E> { public static <T> Set<T> addAll(Set<T> input, Collection<? extends T> c) { if (c.isEmpty()) { return input; } else if (input.isEmpty()) { if (c.size() == 1) { return Collections.<T>singleton(c.iterator().next()); } Set<T> result = New.set(c); if (result.size() == 1) { result = Collections.<T>singleton(c.iterator().next()); } return result; } else if (input.size() == 1) { Set<T> result = New.set(c.size() + 1); result.addAll(input); if (result.addAll(c)) { return result; } return input; } else { input.addAll(c); return input; } } static Set<T> add(Set<T> input, T e); static Set<T> addAll(Set<T> input, Collection<? extends T> c); static Set<T> remove(Set<T> set, Object o); static Set<T> removeAll(Set<T> set, Collection<T> c); static Set<T> retainAll(Set<T> mySet, Collection<?> c); @Override boolean add(E e); @Override boolean addAll(Collection<? extends E> c); @Override void clear(); @Override boolean remove(Object o); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); }### Answer: @Test public void testAddAll() { TinySet<Object> set = new TinySet<>(); checkSize0(set); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1))); checkSize1(set); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2))); checkSizeN(set, 2); Assert.assertFalse(set.addAll(Arrays.asList(TEST_OBJ1))); checkSizeN(set, 2); Assert.assertFalse(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2))); checkSizeN(set, 2); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); checkSizeN(set, 3); Assert.assertFalse(set.addAll(Collections.emptySet())); checkSizeN(set, 3); } @Test public void testStaticAddAll() { Set<Object> set = Collections.emptySet(); checkSize0(set); set = TinySet.addAll(set, Collections.emptySet()); checkSize0(set); set = TinySet.addAll(set, Arrays.asList(TEST_OBJ1)); checkSize1(set); set = TinySet.addAll(set, Arrays.asList(TEST_OBJ1, TEST_OBJ2)); checkSizeN(set, 2); set = TinySet.addAll(set, Arrays.asList(TEST_OBJ1)); checkSizeN(set, 2); set = TinySet.addAll(set, Arrays.asList(TEST_OBJ1, TEST_OBJ2)); checkSizeN(set, 2); set = TinySet.addAll(set, Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3)); checkSizeN(set, 3); }
### Question: TinySet extends AbstractProxySet<E> { @Override public void clear() { mySet = Collections.emptySet(); } static Set<T> add(Set<T> input, T e); static Set<T> addAll(Set<T> input, Collection<? extends T> c); static Set<T> remove(Set<T> set, Object o); static Set<T> removeAll(Set<T> set, Collection<T> c); static Set<T> retainAll(Set<T> mySet, Collection<?> c); @Override boolean add(E e); @Override boolean addAll(Collection<? extends E> c); @Override void clear(); @Override boolean remove(Object o); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); }### Answer: @Test public void testClear() { TinySet<Object> set = new TinySet<>(); set.clear(); checkSize0(set); Assert.assertTrue(set.add(TEST_OBJ1)); checkSize1(set); set.clear(); checkSize0(set); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); checkSizeN(set, 3); set.clear(); checkSize0(set); }
### Question: TinySet extends AbstractProxySet<E> { public static <T> Set<T> remove(Set<T> set, Object o) { if (set.isEmpty()) { return set; } else if (set.size() == 1) { if (set.contains(o)) { return Collections.emptySet(); } return set; } else { if (set.remove(o)) { return resetStorage(set); } return set; } } static Set<T> add(Set<T> input, T e); static Set<T> addAll(Set<T> input, Collection<? extends T> c); static Set<T> remove(Set<T> set, Object o); static Set<T> removeAll(Set<T> set, Collection<T> c); static Set<T> retainAll(Set<T> mySet, Collection<?> c); @Override boolean add(E e); @Override boolean addAll(Collection<? extends E> c); @Override void clear(); @Override boolean remove(Object o); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); }### Answer: @Test public void testRemove() { TinySet<Object> set = new TinySet<>(); Assert.assertFalse(set.remove(TEST_OBJ2)); checkSize0(set); Assert.assertTrue(set.add(TEST_OBJ1)); checkSize1(set); Assert.assertFalse(set.remove(TEST_OBJ2)); checkSize1(set); Assert.assertTrue(set.remove(TEST_OBJ1)); checkSize0(set); Assert.assertFalse(set.remove(TEST_OBJ1)); checkSize0(set); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); checkSizeN(set, 3); Assert.assertTrue(set.remove(TEST_OBJ1)); checkSizeN(set, 2); Assert.assertFalse(set.remove(TEST_OBJ1)); checkSizeN(set, 2); Assert.assertTrue(set.remove(TEST_OBJ3)); checkSize1(set); Assert.assertTrue(set.remove(TEST_OBJ2)); checkSize0(set); }
### Question: TinySet extends AbstractProxySet<E> { public static <T> Set<T> removeAll(Set<T> set, Collection<T> c) { if (set.isEmpty()) { return set; } else if (set.size() == 1) { if (c.contains(set.iterator().next())) { return Collections.emptySet(); } return set; } else { if (set.removeAll(c)) { return resetStorage(set); } return set; } } static Set<T> add(Set<T> input, T e); static Set<T> addAll(Set<T> input, Collection<? extends T> c); static Set<T> remove(Set<T> set, Object o); static Set<T> removeAll(Set<T> set, Collection<T> c); static Set<T> retainAll(Set<T> mySet, Collection<?> c); @Override boolean add(E e); @Override boolean addAll(Collection<? extends E> c); @Override void clear(); @Override boolean remove(Object o); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); }### Answer: @Test public void testRemoveAll() { TinySet<Object> set = new TinySet<>(); Assert.assertFalse(set.removeAll(Collections.emptySet())); checkSize0(set); Assert.assertTrue(set.add(TEST_OBJ1)); checkSize1(set); Assert.assertFalse(set.removeAll(Collections.emptySet())); checkSize1(set); Assert.assertTrue(set.removeAll(Arrays.asList(TEST_OBJ1))); checkSize0(set); Assert.assertFalse(set.removeAll(Arrays.asList(TEST_OBJ1))); checkSize0(set); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); checkSizeN(set, 3); Assert.assertFalse(set.removeAll(Collections.emptySet())); checkSizeN(set, 3); Assert.assertTrue(set.removeAll(Arrays.asList(TEST_OBJ1))); checkSizeN(set, 2); Assert.assertFalse(set.removeAll(Arrays.asList(TEST_OBJ1))); checkSizeN(set, 2); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); checkSizeN(set, 3); Assert.assertTrue(set.removeAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2))); checkSize1(set); Assert.assertFalse(set.removeAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2))); checkSize1(set); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); checkSizeN(set, 3); Assert.assertTrue(set.removeAll(Arrays.asList(TEST_OBJ1, TEST_OBJ3, TEST_OBJ2))); checkSize0(set); Assert.assertFalse(set.removeAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2))); checkSize0(set); }
### Question: TinySet extends AbstractProxySet<E> { public static <T> Set<T> retainAll(Set<T> mySet, Collection<?> c) { if (mySet.isEmpty()) { return mySet; } else if (mySet.size() == 1) { if (c.contains(mySet.iterator().next())) { return mySet; } return Collections.emptySet(); } else if (mySet.retainAll(c)) { return resetStorage(mySet); } else { return mySet; } } static Set<T> add(Set<T> input, T e); static Set<T> addAll(Set<T> input, Collection<? extends T> c); static Set<T> remove(Set<T> set, Object o); static Set<T> removeAll(Set<T> set, Collection<T> c); static Set<T> retainAll(Set<T> mySet, Collection<?> c); @Override boolean add(E e); @Override boolean addAll(Collection<? extends E> c); @Override void clear(); @Override boolean remove(Object o); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); }### Answer: @Test public void testRetainAll() { TinySet<Object> set = new TinySet<>(); Assert.assertFalse(set.retainAll(Arrays.asList(TEST_OBJ1))); checkSize0(set); Assert.assertTrue(set.add(TEST_OBJ1)); checkSize1(set); Assert.assertFalse(set.retainAll(Arrays.asList(TEST_OBJ1))); checkSize1(set); Assert.assertTrue(set.retainAll(Collections.emptySet())); checkSize0(set); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); checkSizeN(set, 3); Assert.assertTrue(set.retainAll(Collections.emptySet())); checkSize0(set); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); Assert.assertTrue(set.retainAll(Arrays.asList(TEST_OBJ1))); checkSize1(set); Assert.assertFalse(set.retainAll(Arrays.asList(TEST_OBJ1))); checkSize1(set); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); checkSizeN(set, 3); Assert.assertTrue(set.retainAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2))); checkSizeN(set, 2); Assert.assertFalse(set.retainAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2))); checkSizeN(set, 2); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); checkSizeN(set, 3); Assert.assertFalse(set.retainAll(Arrays.asList(TEST_OBJ1, TEST_OBJ3, TEST_OBJ2))); checkSizeN(set, 3); }
### Question: NoEffectPredicate implements Predicate<T> { @Override public boolean test(T input) { return Objects.equals(myFunction.apply(input), input); } NoEffectPredicate(Function<? super T, ? extends T> function); @Override boolean test(T input); }### Answer: @Test public void test() { Assert.assertTrue( new NoEffectPredicate<Boolean>(new ConstantFunction<Boolean, Boolean>(Boolean.TRUE)).test(Boolean.TRUE)); Assert.assertFalse( new NoEffectPredicate<Boolean>(new ConstantFunction<Boolean, Boolean>(Boolean.TRUE)).test(Boolean.FALSE)); Assert.assertFalse(new NoEffectPredicate<Boolean>(new ConstantFunction<Boolean, Boolean>(Boolean.TRUE)).test(null)); Assert.assertFalse(new NoEffectPredicate<Boolean>(new ConstantFunction<Boolean, Boolean>(null)).test(Boolean.TRUE)); }
### Question: ColorUtilities { public static Color blendColors(Color color1, Color color2) { if (color1.getAlpha() < COLOR_COMPONENT_MAX_VALUE) { float alpha = (float)color1.getAlpha() / COLOR_COMPONENT_MAX_VALUE; return new Color((color1.getRed() * alpha + color2.getRed() * (1f - alpha)) / COLOR_COMPONENT_MAX_VALUE, (color1.getGreen() * alpha + color2.getGreen() * (1f - alpha)) / COLOR_COMPONENT_MAX_VALUE, (color1.getBlue() * alpha + color2.getBlue() * (1f - alpha)) / COLOR_COMPONENT_MAX_VALUE); } return color1; } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testBlendColors() { Assert.assertEquals(new Color(51, 0, 204), ColorUtilities.blendColors(new Color(255, 0, 0, 51), Color.BLUE)); }
### Question: ColorUtilities { public static Color brighten(Color input, double factor) { if (factor < BRIGHTNESS_FACTOR_MIN || factor > BRIGHTNESS_FACTOR_MAX) { throw new IllegalArgumentException("Color brighten factor must be between 0.01 and 0.99"); } int r = input.getRed(); int g = input.getGreen(); int b = input.getBlue(); int i = (int)(BLACK_BRIGHTEN_MIN / (1.0 - factor)); if (r == 0 && g == 0 && b == 0) { return new Color(i, i, i); } if (r > 0 && r < i) { r = i; } if (g > 0 && g < i) { g = i; } if (b > 0 && b < i) { b = i; } return new Color(Math.min((int)(r / factor), 255), Math.min((int)(g / factor), 255), Math.min((int)(b / factor), 255), input.getAlpha()); } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testBrighten() { Color color1 = new Color(40, 40, 40); Assert.assertEquals(color1.brighter(), ColorUtilities.brighten(color1, .7)); Color color2 = new Color(40, 40, 40, 10); Assert.assertEquals(ColorUtilities.opacitizeColor(color2.brighter(), 10), ColorUtilities.brighten(color2, .7)); }
### Question: ColorUtilities { public static Color convertFromColorString(String color) { Color aColor = null; if (color != null) { try { Field colorField = Color.class.getField(color.toUpperCase()); try { aColor = (Color)colorField.get(null); } catch (IllegalAccessException e) { LOGGER.error("Could not access field by reflection.", e); } } catch (NoSuchFieldException e) { String[] colors = color.split("-"); if (colors.length == 4) { try { aColor = new java.awt.Color(Integer.parseInt(colors[0]), Integer.parseInt(colors[1]), Integer.parseInt(colors[2]), Integer.parseInt(colors[3])); } catch (NumberFormatException nfe) { LOGGER.warn("Failed to parse color [" + color + "]: " + nfe, nfe); } catch (IllegalArgumentException iae) { LOGGER.warn("Failed to parse color [" + color + "]: " + iae, iae); } } } } return aColor; } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testConvertFromColorString() { Assert.assertEquals(Color.RED, ColorUtilities.convertFromColorString("red")); Assert.assertEquals(Color.RED, ColorUtilities.convertFromColorString("RED")); Assert.assertEquals(new Color(250, 0, 0, 255), ColorUtilities.convertFromColorString("250-0-0-255")); Assert.assertEquals(new Color(250, 0, 0, 254), ColorUtilities.convertFromColorString("250-0-0-254")); Assert.assertEquals(new Color(0, 250, 0, 255), ColorUtilities.convertFromColorString("0-250-0-255")); Assert.assertEquals(new Color(0, 250, 0, 254), ColorUtilities.convertFromColorString("0-250-0-254")); Assert.assertEquals(new Color(0, 0, 250, 255), ColorUtilities.convertFromColorString("0-0-250-255")); Assert.assertEquals(new Color(0, 0, 250, 254), ColorUtilities.convertFromColorString("0-0-250-254")); Assert.assertNull(ColorUtilities.convertFromColorString("")); Assert.assertNull(ColorUtilities.convertFromColorString("255")); }
### Question: ColorUtilities { public static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex) throws NumberFormatException { if (color == null || color.length() == 0 || color.length() > 6) { throw new NumberFormatException("For input string: \"" + color + "\""); } long inputVal = Long.parseLong(color, 16); int outputVal = 0; outputVal |= 0xff0000 & MathUtil.byteShift(inputVal, redIndex - 1); outputVal |= 0xff00 & MathUtil.byteShift(inputVal, greenIndex - 2); outputVal |= 0xff & MathUtil.byteShift(inputVal, blueIndex - 3); outputVal |= 0xff000000; return new Color(outputVal, true); } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testConvertFromHexString() { Assert.assertEquals(new Color(0x12, 0x12, 0x12, 0x12), ColorUtilities.convertFromHexString("12345678", 0, 0, 0, 0)); Assert.assertEquals(new Color(0x12, 0x34, 0x56, 0x78), ColorUtilities.convertFromHexString("12345678", 0, 1, 2, 3)); Assert.assertEquals(new Color(0x78, 0x56, 0x34, 0x12), ColorUtilities.convertFromHexString("12345678", 3, 2, 1, 0)); Assert.assertEquals(new Color(0xff, 0xff, 0xff, 0xff), ColorUtilities.convertFromHexString("ffffffff", 3, 2, 1, 0)); } @Test(expected = NumberFormatException.class) public void testConvertFromHexStringBadInput1() { ColorUtilities.convertFromHexString("", 0, 0, 0, 0); } @Test(expected = NumberFormatException.class) public void testConvertFromHexStringBadInput2() { ColorUtilities.convertFromHexString(" 12345678", 0, 0, 0, 0); } @Test(expected = NumberFormatException.class) public void testConvertFromHexStringBadInput3() { ColorUtilities.convertFromHexString("ffffffff0", 3, 2, 1, 0); } @Test(expected = NumberFormatException.class) public void testConvertFromHexStringNullInput() { ColorUtilities.convertFromHexString(null, 0, 0, 0, 0); }
### Question: ScaledImageController implements Observer { public void close() { myModel.deleteObserver(this); } ScaledImageController(ScaledImageModel model); void close(); @Override void update(Observable o, Object arg); }### Answer: @Test public void testClose() { ScaledImageModel model = new ScaledImageModel(); ScaledImageController controller = new ScaledImageController(model); assertEquals(1, model.countObservers()); controller.close(); assertEquals(0, model.countObservers()); }
### Question: ColorUtilities { public static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex) { int inputVal = color.getRGB(); int outputVal = 0; outputVal |= MathUtil.byteShift(inputVal & 0x00ff0000, 0 - redIndex); outputVal |= MathUtil.byteShift(inputVal & 0x0000ff00, 1 - greenIndex); outputVal |= MathUtil.byteShift(inputVal & 0x000000ff, 2 - blueIndex); return Integer.toHexString(outputVal); } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testConvertToHexStringColorIntIntInt() { Assert.assertEquals("123456", ColorUtilities.convertToHexString(new Color(0x12, 0x34, 0x56, 0x78), 0, 1, 2)); Assert.assertEquals("345678", ColorUtilities.convertToHexString(new Color(0x78, 0x56, 0x34, 0x12), 2, 1, 0)); Assert.assertEquals("ffffff", ColorUtilities.convertToHexString(new Color(0xff, 0xff, 0xff, 0xff), 2, 1, 0)); } @Test public void testConvertToHexStringColorIntIntIntInt() { Assert.assertEquals("12345678", ColorUtilities.convertToHexString(new Color(0x12, 0x34, 0x56, 0x78), 0, 1, 2, 3)); Assert.assertEquals("12345678", ColorUtilities.convertToHexString(new Color(0x78, 0x56, 0x34, 0x12), 3, 2, 1, 0)); Assert.assertEquals("ffffffff", ColorUtilities.convertToHexString(new Color(0xff, 0xff, 0xff, 0xff), 3, 2, 1, 0)); }
### Question: ColorUtilities { public static String convertToRGBAColorString(Color aColor) { if (aColor == null) { return null; } StringBuilder sb = new StringBuilder(); sb.append(aColor.getRed()).append('-').append(aColor.getGreen()).append('-').append(aColor.getBlue()).append('-') .append(aColor.getAlpha()); return sb.toString(); } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testConvertToRGBAColorString() { Assert.assertEquals("255-0-0-255", ColorUtilities.convertToRGBAColorString(new Color(255, 0, 0, 255))); Assert.assertEquals("255-0-0-0", ColorUtilities.convertToRGBAColorString(new Color(255, 0, 0, 0))); Assert.assertEquals("0-255-0-255", ColorUtilities.convertToRGBAColorString(new Color(0, 255, 0, 255))); Assert.assertEquals("0-255-0-0", ColorUtilities.convertToRGBAColorString(new Color(0, 255, 0, 0))); Assert.assertEquals("0-0-255-255", ColorUtilities.convertToRGBAColorString(new Color(0, 0, 255, 255))); Assert.assertEquals("0-0-255-0", ColorUtilities.convertToRGBAColorString(new Color(0, 0, 255, 0))); }
### Question: ColorUtilities { public static Color darken(Color input, double factor) { if (factor < BRIGHTNESS_FACTOR_MIN || factor > BRIGHTNESS_FACTOR_MAX) { throw new IllegalArgumentException("Color brighten factor must be between 0.01 and 0.99"); } return new Color(Math.max((int)(input.getRed() * factor), 0), Math.max((int)(input.getGreen() * factor), 0), Math.max((int)(input.getBlue() * factor), 0), input.getAlpha()); } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testDarken() { Color color1 = new Color(40, 40, 40); Assert.assertEquals(color1.darker(), ColorUtilities.darken(color1, .7)); Color color2 = new Color(40, 40, 40, 10); Assert.assertEquals(ColorUtilities.opacitizeColor(color2.darker(), 10), ColorUtilities.darken(color2, .7)); }
### Question: ColorUtilities { public static Color lighten(Color color) { float[] hsb = new float[3]; Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), hsb); hsb[1] = hsb[1] / 2; return new Color(Color.HSBtoRGB(hsb[0], hsb[1], hsb[2])); } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testLighten() { float[] originalHSB = new float[3]; Color.RGBtoHSB(Color.BLUE.getRed(), Color.BLUE.getGreen(), Color.BLUE.getBlue(), originalHSB); Color light1 = ColorUtilities.lighten(Color.BLUE); float[] light1HSB = new float[3]; Color.RGBtoHSB(light1.getRed(), light1.getGreen(), light1.getBlue(), light1HSB); Color light2 = ColorUtilities.lighten(light1); float[] light2HSB = new float[3]; Color.RGBtoHSB(light2.getRed(), light2.getGreen(), light2.getBlue(), light2HSB); Color light3 = ColorUtilities.lighten(light2); float[] light3HSB = new float[3]; Color.RGBtoHSB(light3.getRed(), light3.getGreen(), light3.getBlue(), light3HSB); Color light4 = ColorUtilities.lighten(light3); float[] light4HSB = new float[3]; Color.RGBtoHSB(light4.getRed(), light4.getGreen(), light4.getBlue(), light4HSB); Color light5 = ColorUtilities.lighten(light4); float[] light5HSB = new float[3]; Color.RGBtoHSB(light5.getRed(), light5.getGreen(), light5.getBlue(), light5HSB); Assert.assertEquals(light1HSB[0], originalHSB[0], 0); Assert.assertEquals(light1HSB[1], .5, 0.01); Assert.assertEquals(light1HSB[2], originalHSB[2], 0); Assert.assertEquals(light2HSB[0], originalHSB[0], 0); Assert.assertEquals(light2HSB[1], .25, 0.01); Assert.assertEquals(light2HSB[2], originalHSB[2], 0); Assert.assertEquals(light3HSB[0], originalHSB[0], 0); Assert.assertEquals(light3HSB[1], .125, 0.01); Assert.assertEquals(light3HSB[2], originalHSB[2], 0); Assert.assertEquals(light4HSB[0], originalHSB[0], 0); Assert.assertEquals(light4HSB[1], .0625, 0.01); Assert.assertEquals(light4HSB[2], originalHSB[2], 0); Assert.assertEquals(light5HSB[0], originalHSB[0], 0); Assert.assertEquals(light5HSB[1], .03125, 0.01); Assert.assertEquals(light5HSB[2], originalHSB[2], 0); }
### Question: ColorUtilities { public static int getBrightness(Color color) { Utilities.checkNull(color, "color"); final float redFactor = 0.241f; final float greenFactor = 0.691f; final float blueFactor = 0.068f; return (int)Math.round(Math.sqrt(redFactor * color.getRed() * color.getRed() + greenFactor * color.getGreen() * color.getGreen() + blueFactor * color.getBlue() * color.getBlue())); } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testGetBrightness() { Assert.assertEquals(0, ColorUtilities.getBrightness(Color.BLACK)); Assert.assertEquals(122, ColorUtilities.getBrightness(new Color(223, 53, 111))); Assert.assertEquals(255, ColorUtilities.getBrightness(Color.WHITE)); for (int index = 0; index < 256; ++index) { Assert.assertEquals(index, ColorUtilities.getBrightness(new Color(index, index, index))); } } @Test(expected = IllegalArgumentException.class) public void testGetBrightnessNullArg() { ColorUtilities.getBrightness(null); }
### Question: BoundingBoxModel extends Observable { public void setBoundingBox(Collection<LineSegment2d> boundingBox) { myBoundingBox.clear(); myBoundingBox.addAll(boundingBox); setChanged(); notifyObservers(BOUNDING_BOX_PROP); } Collection<LineSegment2d> getBoundingBox(); void setBoundingBox(Collection<LineSegment2d> boundingBox); static final String BOUNDING_BOX_PROP; }### Answer: @Test public void testSetBoundingBox() { BoundingBoxModel model = new BoundingBoxModel(); List<LineSegment2d> boundingBox = New.list(new LineSegment2d(new Vector2d(0, 0), new Vector2d(10, 10))); EasyMockSupport support = new EasyMockSupport(); Observer observer = createObserver(support, model); support.replayAll(); model.addObserver(observer); model.setBoundingBox(boundingBox); assertEquals(boundingBox.get(0), model.getBoundingBox().iterator().next()); support.verifyAll(); }
### Question: ColorUtilities { public static boolean isEqual(Color c1, Color c2) { return Utilities.sameInstance(c1, c2) || c1 != null && c1.equals(c2); } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testIsEqual() { Assert.assertTrue(ColorUtilities.isEqual(Color.RED, Color.RED)); Assert.assertTrue(ColorUtilities.isEqual(Color.RED, new Color(255, 0, 0, 255))); Assert.assertFalse(ColorUtilities.isEqual(Color.RED, new Color(255, 0, 0, 254))); Assert.assertTrue(ColorUtilities.isEqual(null, null)); Assert.assertFalse(ColorUtilities.isEqual(Color.RED, null)); Assert.assertFalse(ColorUtilities.isEqual(null, Color.RED)); }
### Question: ColorUtilities { public static boolean isEqualIgnoreAlpha(Color c1, Color c2) { boolean equal = false; if (c1 == null && c2 == null) { equal = true; } else if (c1 != null && c2 != null) { equal = c1.getRed() == c2.getRed() && c1.getBlue() == c2.getBlue() && c1.getGreen() == c2.getGreen(); } return equal; } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testIsEqualIgnoreAlpha() { Assert.assertTrue(ColorUtilities.isEqualIgnoreAlpha(Color.RED, Color.RED)); Assert.assertTrue(ColorUtilities.isEqualIgnoreAlpha(Color.RED, new Color(255, 0, 0, 255))); Assert.assertTrue(ColorUtilities.isEqualIgnoreAlpha(Color.RED, new Color(255, 0, 0, 254))); Assert.assertTrue(ColorUtilities.isEqualIgnoreAlpha(null, null)); Assert.assertFalse(ColorUtilities.isEqualIgnoreAlpha(Color.RED, null)); Assert.assertFalse(ColorUtilities.isEqualIgnoreAlpha(null, Color.RED)); }
### Question: ColorUtilities { public static Color opacitizeColor(Color startingColor, float alpha) { if (alpha < 0f || alpha > 1f) { throw new IllegalArgumentException("Alpha [" + alpha + "] cannot be less than 0 or greater than 1."); } if (startingColor == null || startingColor.getAlpha() == alpha) { return startingColor; } return new Color(startingColor.getRGB() & 0xffffff | (int)(alpha * 0xff + 0.5) << 24, true); } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer: @Test public void testOpacitizeColorFloat() { Assert.assertNull(ColorUtilities.opacitizeColor(null, 1f)); Assert.assertEquals(new Color(.1f, .2f, .3f, .5f), ColorUtilities.opacitizeColor(new Color(.1f, .2f, .3f, .4f), .5f)); Assert.assertEquals(new Color(0f, 1f, 0f, 0f), ColorUtilities.opacitizeColor(new Color(0f, 1f, 0f, 1f), 0f)); Assert.assertEquals(new Color(0f, 1f, 0f, 1f), ColorUtilities.opacitizeColor(new Color(0f, 1f, 0f, 1f), 1f)); } @Test(expected = IllegalArgumentException.class) public void testOpacitizeColorFloatBadInput1() { ColorUtilities.opacitizeColor(Color.RED, -Float.MIN_VALUE); } @Test(expected = IllegalArgumentException.class) public void testOpacitizeColorFloatBadInput12() { ColorUtilities.opacitizeColor(Color.RED, 1.0000001f); } @Test public void testOpacitizeColorInt() { Assert.assertNull(ColorUtilities.opacitizeColor(null, 1f)); Assert.assertEquals(new Color(1, 2, 3, 5), ColorUtilities.opacitizeColor(new Color(1, 2, 3, 4), 5)); Assert.assertEquals(new Color(0, 1, 0, 0), ColorUtilities.opacitizeColor(new Color(0, 1, 0, 1), 0)); Assert.assertEquals(new Color(0, 1, 0, 255), ColorUtilities.opacitizeColor(new Color(0, 1, 0, 255), 255)); } @Test(expected = IllegalArgumentException.class) public void testOpacitizeColorIntBadInput1() { ColorUtilities.opacitizeColor(Color.RED, -1); } @Test(expected = IllegalArgumentException.class) public void testOpacitizeColorIntBadInput12() { ColorUtilities.opacitizeColor(Color.RED, 256); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public boolean borders(long value) { return value == myStartValue - 1 || value == myEndValue + 1; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testBordersWithRangeBlock() { RangeLongBlock block = new RangeLongBlock(5, 10); RangeLongBlock before = new RangeLongBlock(1, 3); RangeLongBlock borderBefore = new RangeLongBlock(1, 4); RangeLongBlock overlapLeading = new RangeLongBlock(1, 5); RangeLongBlock equals = new RangeLongBlock(5, 10); RangeLongBlock subset = new RangeLongBlock(6, 9); RangeLongBlock superset = new RangeLongBlock(4, 11); RangeLongBlock overlapTrailing = new RangeLongBlock(9, 11); RangeLongBlock borderAfter = new RangeLongBlock(11, 12); RangeLongBlock after = new RangeLongBlock(12, 13); Assert.assertFalse(block.borders(before)); Assert.assertTrue(block.borders(borderBefore)); Assert.assertFalse(block.borders(overlapLeading)); Assert.assertFalse(block.borders(equals)); Assert.assertFalse(block.borders(subset)); Assert.assertFalse(block.borders(superset)); Assert.assertFalse(block.borders(overlapTrailing)); Assert.assertTrue(block.borders(borderAfter)); Assert.assertFalse(block.borders(after)); } @Test public void testBordersWithValue() { RangeLongBlock aBlock = new RangeLongBlock(3, 5); Assert.assertTrue(aBlock.borders(2)); Assert.assertTrue(aBlock.borders(6)); Assert.assertFalse(aBlock.borders(3)); Assert.assertFalse(aBlock.borders(4)); Assert.assertFalse(aBlock.borders(5)); Assert.assertFalse(aBlock.borders(1)); Assert.assertFalse(aBlock.borders(7)); }
### Question: BoundingBoxOverlay implements Overlay { @Override public void draw(Graphics graphics) { graphics.setColor(Colors.QUERY_REGION); for (LineSegment2d segment : myModel.getBoundingBox()) { Vector2d vertexA = segment.getVertexA(); Vector2d vertexB = segment.getVertexB(); graphics.drawLine((int)vertexA.getX(), (int)vertexA.getY(), (int)vertexB.getX(), (int)vertexB.getY()); } } BoundingBoxOverlay(MapModel mapModel); @Override void close(); @Override void draw(Graphics graphics); }### Answer: @Test public void test() { MapModel mapModel = new MapModel(); GeographicBoundingBox boundingBox = new GeographicBoundingBox(LatLonAlt.createFromDegrees(0d, 0d), LatLonAlt.createFromDegrees(45d, 90d)); mapModel.setRegion(boundingBox); mapModel.setHeightWidth(400, 400); mapModel.setViewport(new ScreenBoundingBox(new ScreenPosition(0d, 0d), new ScreenPosition(400, 400))); GraphicsMock graphics = new GraphicsMock(); BoundingBoxOverlay overlay = new BoundingBoxOverlay(mapModel); overlay.draw(graphics); Vector2d lowerLeft = new Vector2d(200, 200); Vector2d lowerRight = new Vector2d(300, 200); Vector2d upperLeft = new Vector2d(200, 100); Vector2d upperRight = new Vector2d(300, 100); List<LineSegment2d> expectedSegments = New.list(new LineSegment2d(lowerLeft, lowerRight), new LineSegment2d(lowerRight, upperRight), new LineSegment2d(upperRight, upperLeft), new LineSegment2d(upperLeft, lowerLeft)); List<LineSegment2d> actualSegments = graphics.getDrawnLines(); for (LineSegment2d expectedSegment : expectedSegments) { boolean isActual = false; for (LineSegment2d actualSegment : actualSegments) { if (actualSegment.getVertexA().equals(expectedSegment.getVertexA()) && actualSegment.getVertexB().equals(expectedSegment.getVertexB()) || actualSegment.getVertexA().equals(expectedSegment.getVertexB()) && actualSegment.getVertexB().equals(expectedSegment.getVertexA())) { isActual = true; break; } } assertTrue("Did not find segment " + expectedSegment, isActual); } }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { @Override public int compareTo(RangeLongBlock o) { if (myStartValue == o.myStartValue && myEndValue == o.myEndValue) { return 0; } else if (myEndValue < o.myStartValue || o.myEndValue < myStartValue) { return myEndValue < o.myStartValue ? -1 : 1; } else { return myStartValue < o.myStartValue ? -1 : 1; } } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testCompareTo() { RangeLongBlock aBlock = new RangeLongBlock(1, 10); RangeLongBlock bBlock = new RangeLongBlock(1, 10); RangeLongBlock cBlock = new RangeLongBlock(2, 4); RangeLongBlock dBlock = new RangeLongBlock(1, 4); RangeLongBlock eBlock = new RangeLongBlock(2, 10); RangeLongBlock fBlock = new RangeLongBlock(-3, -1); RangeLongBlock gBlock = new RangeLongBlock(33, 34); Assert.assertEquals(0, aBlock.compareTo(bBlock)); Assert.assertEquals(-1, aBlock.compareTo(cBlock)); Assert.assertEquals(1, aBlock.compareTo(dBlock)); Assert.assertEquals(-1, aBlock.compareTo(eBlock)); Assert.assertEquals(1, aBlock.compareTo(fBlock)); Assert.assertEquals(-1, aBlock.compareTo(gBlock)); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public boolean containsValue(long value) { return value >= myStartValue && value <= myEndValue; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testContainsValue() { RangeLongBlock aBlock = new RangeLongBlock(3, 7); Assert.assertTrue(aBlock.containsValue(3)); Assert.assertTrue(aBlock.containsValue(4)); Assert.assertTrue(aBlock.containsValue(5)); Assert.assertTrue(aBlock.containsValue(6)); Assert.assertTrue(aBlock.containsValue(7)); Assert.assertFalse(aBlock.containsValue(2)); Assert.assertFalse(aBlock.containsValue(8)); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } RangeLongBlock other = (RangeLongBlock)obj; return myEndValue == other.myEndValue && myStartValue == other.myStartValue; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testCopyCtor() { RangeLongBlock aBlock = new RangeLongBlock(1, 10); Object copyObj = new RangeLongBlock(aBlock); Assert.assertTrue(aBlock.equals(copyObj)); } @Test public void testEquals() { RangeLongBlock aBlock = new RangeLongBlock(1, 10); RangeLongBlock bBlock = new RangeLongBlock(1, 10); RangeLongBlock cBlock = new RangeLongBlock(2, 4); RangeLongBlock dBlock = new RangeLongBlock(1, 4); RangeLongBlock eBlock = new RangeLongBlock(2, 10); RangeLongBlock fBlock = new RangeLongBlock(-3, -1); RangeLongBlock gBlock = new RangeLongBlock(33, 34); Assert.assertTrue(aBlock.equals(bBlock)); Assert.assertTrue(!aBlock.equals(cBlock)); Assert.assertTrue(!aBlock.equals(dBlock)); Assert.assertTrue(!aBlock.equals(eBlock)); Assert.assertTrue(!aBlock.equals(fBlock)); Assert.assertTrue(!aBlock.equals(gBlock)); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { protected void expand(long value) { if (value < myStartValue - 1 || value > myEndValue + 1) { throw new IllegalArgumentException("Expanding RangeLongBlock Can Only Be Done With Neighboring Values"); } if (value == myStartValue - 1) { myStartValue = value; } else if (value == myEndValue + 1) { myEndValue = value; } } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testExpand() { RangeLongBlock aBlock = new RangeLongBlock(3, 5); boolean gotIllegalArgumentException = false; try { aBlock.expand(1); } catch (IllegalArgumentException e) { gotIllegalArgumentException = true; } Assert.assertTrue(gotIllegalArgumentException); gotIllegalArgumentException = false; try { aBlock.expand(7); } catch (IllegalArgumentException e) { gotIllegalArgumentException = true; } Assert.assertTrue(gotIllegalArgumentException); aBlock.expand(2); Assert.assertEquals(2, aBlock.getStart()); aBlock.expand(6); Assert.assertEquals(6, aBlock.getEnd()); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public boolean formsContiguousRange(RangeLongBlock other) { RangeRelationType relation = getRelation(other); return relation != RangeRelationType.BEFORE && relation != RangeRelationType.AFTER; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testFormsContiguousRange() { RangeLongBlock block = new RangeLongBlock(5, 10); RangeLongBlock before = new RangeLongBlock(1, 3); RangeLongBlock borderBefore = new RangeLongBlock(1, 4); RangeLongBlock overlapLeading = new RangeLongBlock(1, 5); RangeLongBlock equals = new RangeLongBlock(5, 10); RangeLongBlock subset = new RangeLongBlock(6, 9); RangeLongBlock superset = new RangeLongBlock(4, 11); RangeLongBlock overlapTrailing = new RangeLongBlock(9, 11); RangeLongBlock borderAfter = new RangeLongBlock(11, 12); RangeLongBlock after = new RangeLongBlock(12, 13); Assert.assertFalse(block.formsContiguousRange(before)); Assert.assertTrue(block.formsContiguousRange(borderBefore)); Assert.assertTrue(block.formsContiguousRange(overlapLeading)); Assert.assertTrue(block.formsContiguousRange(equals)); Assert.assertTrue(block.formsContiguousRange(subset)); Assert.assertTrue(block.formsContiguousRange(superset)); Assert.assertTrue(block.formsContiguousRange(overlapTrailing)); Assert.assertTrue(block.formsContiguousRange(borderAfter)); Assert.assertFalse(block.formsContiguousRange(after)); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public RangeRelationType getRelation(RangeLongBlock block) { RangeRelationType result = null; if (block.myEndValue < myStartValue) { if (block.myEndValue == myStartValue - 1) { result = RangeRelationType.BORDERS_BEFORE; } else { result = RangeRelationType.BEFORE; } } else if (block.myStartValue > myEndValue) { if (block.myStartValue - 1 == myEndValue) { result = RangeRelationType.BORDERS_AFTER; } else { result = RangeRelationType.AFTER; } } else if (equals(block)) { result = RangeRelationType.EQUAL; } else { if (block.myStartValue >= myStartValue && block.myEndValue <= myEndValue) { result = RangeRelationType.SUBSET; } else if (block.myStartValue <= myStartValue && block.myEndValue >= myEndValue) { result = RangeRelationType.SUPERSET; } else if (block.myStartValue < myStartValue && block.myEndValue <= myEndValue) { result = RangeRelationType.OVERLAPS_FRONT_EDGE; } else { result = RangeRelationType.OVERLAPS_BACK_EDGE; } } return result; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testGetRelation() { RangeLongBlock block = new RangeLongBlock(5, 10); RangeLongBlock before = new RangeLongBlock(1, 3); RangeLongBlock borderBefore = new RangeLongBlock(1, 4); RangeLongBlock overlapLeading = new RangeLongBlock(1, 5); RangeLongBlock equals = new RangeLongBlock(5, 10); RangeLongBlock subset = new RangeLongBlock(6, 9); RangeLongBlock superset = new RangeLongBlock(4, 11); RangeLongBlock overlapTrailing = new RangeLongBlock(9, 11); RangeLongBlock borderAfter = new RangeLongBlock(11, 12); RangeLongBlock after = new RangeLongBlock(12, 13); Assert.assertEquals(RangeRelationType.BEFORE, block.getRelation(before)); Assert.assertEquals(RangeRelationType.BORDERS_BEFORE, block.getRelation(borderBefore)); Assert.assertEquals(RangeRelationType.OVERLAPS_FRONT_EDGE, block.getRelation(overlapLeading)); Assert.assertEquals(RangeRelationType.EQUAL, block.getRelation(equals)); Assert.assertEquals(RangeRelationType.SUBSET, block.getRelation(subset)); Assert.assertEquals(RangeRelationType.SUPERSET, block.getRelation(superset)); Assert.assertEquals(RangeRelationType.OVERLAPS_BACK_EDGE, block.getRelation(overlapTrailing)); Assert.assertEquals(RangeRelationType.BORDERS_AFTER, block.getRelation(borderAfter)); Assert.assertEquals(RangeRelationType.AFTER, block.getRelation(after)); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public RangeLongBlock intersection(RangeLongBlock other) { RangeLongBlock intersection = null; RangeRelationType relation = getRelation(other); switch (relation) { case AFTER: case BEFORE: case BORDERS_AFTER: case BORDERS_BEFORE: break; case EQUAL: case SUPERSET: intersection = new RangeLongBlock(myStartValue, myEndValue); break; case OVERLAPS_BACK_EDGE: intersection = new RangeLongBlock(other.myStartValue, myEndValue); break; case OVERLAPS_FRONT_EDGE: intersection = new RangeLongBlock(myStartValue, other.myEndValue); break; case SUBSET: intersection = new RangeLongBlock(other.myStartValue, other.myEndValue); break; default: break; } return intersection; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testIntersection() { RangeLongBlock block = new RangeLongBlock(5, 10); RangeLongBlock before = new RangeLongBlock(1, 3); RangeLongBlock intersect = block.intersection(before); Assert.assertNull(intersect); RangeLongBlock borderBefore = new RangeLongBlock(1, 4); intersect = block.intersection(borderBefore); Assert.assertNull(intersect); RangeLongBlock overlapLeading = new RangeLongBlock(1, 6); intersect = block.intersection(overlapLeading); Assert.assertEquals(5, intersect.getStart()); Assert.assertEquals(6, intersect.getEnd()); RangeLongBlock equals = new RangeLongBlock(5, 10); intersect = block.intersection(equals); Assert.assertEquals(5, intersect.getStart()); Assert.assertEquals(10, intersect.getEnd()); RangeLongBlock subset = new RangeLongBlock(6, 9); intersect = block.intersection(subset); Assert.assertEquals(6, intersect.getStart()); Assert.assertEquals(9, intersect.getEnd()); RangeLongBlock superset = new RangeLongBlock(4, 11); intersect = block.intersection(superset); Assert.assertEquals(5, intersect.getStart()); Assert.assertEquals(10, intersect.getEnd()); RangeLongBlock overlapTrailing = new RangeLongBlock(9, 11); intersect = block.intersection(overlapTrailing); Assert.assertEquals(9, intersect.getStart()); Assert.assertEquals(10, intersect.getEnd()); RangeLongBlock borderAfter = new RangeLongBlock(11, 12); intersect = block.intersection(borderAfter); Assert.assertNull(intersect); RangeLongBlock after = new RangeLongBlock(12, 13); intersect = block.intersection(after); Assert.assertNull(intersect); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { @Override public Iterator<Long> iterator() { return new BlockLongIterator(this); } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testIterator() { RangeLongBlock aBlock = new RangeLongBlock(1, 5); Iterator<Long> itr = aBlock.iterator(); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(1, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(2, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(3, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(4, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(5, itr.next().longValue()); Assert.assertTrue(!itr.hasNext()); TestHelper.testNoSuchElement(itr); TestHelper.testUnsupportedRemove(itr); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two) { RangeLongBlock merged = null; if (one.formsContiguousRange(two)) { long start = one.myStartValue < two.myStartValue ? one.myStartValue : two.myStartValue; long end = one.myEndValue > two.myEndValue ? one.myEndValue : two.myEndValue; merged = new RangeLongBlock(start, end); } return merged; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testMerge() { RangeLongBlock block = new RangeLongBlock(5, 10); RangeLongBlock before = new RangeLongBlock(1, 3); boolean hadIllegalArgumentException = false; try { block.merge(before); } catch (IllegalArgumentException e) { hadIllegalArgumentException = true; } Assert.assertTrue(hadIllegalArgumentException); RangeLongBlock borderBefore = new RangeLongBlock(1, 4); block = new RangeLongBlock(5, 10); block.merge(borderBefore); Assert.assertEquals(1, block.getStart()); Assert.assertEquals(10, block.getEnd()); RangeLongBlock overlapLeading = new RangeLongBlock(3, 5); block = new RangeLongBlock(5, 10); block.merge(overlapLeading); Assert.assertEquals(3, block.getStart()); Assert.assertEquals(10, block.getEnd()); RangeLongBlock equals = new RangeLongBlock(5, 10); block = new RangeLongBlock(5, 10); block.merge(equals); Assert.assertEquals(5, block.getStart()); Assert.assertEquals(10, block.getEnd()); RangeLongBlock subset = new RangeLongBlock(6, 9); block = new RangeLongBlock(5, 10); block.merge(subset); Assert.assertEquals(5, block.getStart()); Assert.assertEquals(10, block.getEnd()); RangeLongBlock superset = new RangeLongBlock(4, 11); block = new RangeLongBlock(5, 10); block.merge(superset); Assert.assertEquals(4, block.getStart()); Assert.assertEquals(11, block.getEnd()); RangeLongBlock overlapTrailing = new RangeLongBlock(9, 11); block = new RangeLongBlock(5, 10); block.merge(overlapTrailing); Assert.assertEquals(5, block.getStart()); Assert.assertEquals(11, block.getEnd()); RangeLongBlock borderAfter = new RangeLongBlock(11, 12); block = new RangeLongBlock(5, 10); block.merge(borderAfter); Assert.assertEquals(5, block.getStart()); Assert.assertEquals(12, block.getEnd()); block = new RangeLongBlock(5, 10); RangeLongBlock after = new RangeLongBlock(12, 13); hadIllegalArgumentException = false; try { block.merge(after); } catch (IllegalArgumentException e) { hadIllegalArgumentException = true; } Assert.assertTrue(hadIllegalArgumentException); }
### Question: BoundingBoxOverlay implements Overlay { @Override public void close() { myController.close(); } BoundingBoxOverlay(MapModel mapModel); @Override void close(); @Override void draw(Graphics graphics); }### Answer: @Test public void testClose() { MapModel mapModel = new MapModel(); BoundingBoxOverlay overlay = new BoundingBoxOverlay(mapModel); assertEquals(1, mapModel.countObservers()); overlay.close(); assertEquals(0, mapModel.countObservers()); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public boolean overlaps(RangeLongBlock other) { return containsValue(other.myStartValue) || containsValue(other.myEndValue) || other.containsValue(myStartValue) || other.containsValue(myEndValue); } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testOverlaps() { RangeLongBlock block = new RangeLongBlock(5, 10); RangeLongBlock before = new RangeLongBlock(1, 3); RangeLongBlock borderBefore = new RangeLongBlock(1, 4); RangeLongBlock overlapLeading = new RangeLongBlock(1, 5); RangeLongBlock equals = new RangeLongBlock(5, 10); RangeLongBlock subset = new RangeLongBlock(6, 9); RangeLongBlock superset = new RangeLongBlock(4, 11); RangeLongBlock overlapTrailing = new RangeLongBlock(9, 11); RangeLongBlock borderAfter = new RangeLongBlock(11, 12); RangeLongBlock after = new RangeLongBlock(12, 13); Assert.assertFalse(block.overlaps(before)); Assert.assertFalse(block.overlaps(borderBefore)); Assert.assertTrue(block.overlaps(overlapLeading)); Assert.assertTrue(block.overlaps(subset)); Assert.assertTrue(block.overlaps(equals)); Assert.assertTrue(block.overlaps(superset)); Assert.assertTrue(block.overlaps(overlapTrailing)); Assert.assertFalse(block.overlaps(borderAfter)); Assert.assertFalse(block.overlaps(after)); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public int size() { return (int)(myEndValue - myStartValue) + 1; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testSizeFunction() { RangeLongBlock aBlock = new RangeLongBlock(1, 10); Assert.assertTrue(aBlock.size() == 10); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values) { List<RangeLongBlock> resultBlocks = new LinkedList<>(); if (values != null && !values.isEmpty()) { if (values.size() == 1) { long val = values.iterator().next().longValue(); resultBlocks.add(new RangeLongBlock(val)); } else { List<Long> valuesToUse = new ArrayList<>(values); Collections.sort(valuesToUse); Iterator<Long> valueItr = valuesToUse.iterator(); long lastStart = valueItr.next().longValue(); long lastVal = lastStart; long curVal = 0; while (valueItr.hasNext()) { curVal = valueItr.next().longValue(); if (curVal != lastVal && curVal != lastVal + 1) { resultBlocks.add(new RangeLongBlock(lastStart, lastVal)); lastStart = curVal; } if (!valueItr.hasNext()) { resultBlocks.add(new RangeLongBlock(lastStart, curVal)); } lastVal = curVal; } } } return resultBlocks; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testStaticCreateRangeLongBlocks() { long[] primativeArray = { 1, 2, 2, 4, 6, 7, 8, -1, 99, 11, 98, 12, -2, 13 }; Long[] objectArray = new Long[primativeArray.length]; Collection<Long> collection = new LinkedList<>(); for (int i = 0; i < primativeArray.length; i++) { objectArray[i] = Long.valueOf(primativeArray[i]); collection.add(Long.valueOf(primativeArray[i])); } LinkedList<RangeLongBlock> blocks = new LinkedList<>(); blocks.add(new RangeLongBlock(-1, -2)); blocks.add(new RangeLongBlock(1, 2)); blocks.add(new RangeLongBlock(4, 4)); blocks.add(new RangeLongBlock(6, 8)); blocks.add(new RangeLongBlock(11, 13)); blocks.add(new RangeLongBlock(98, 99)); List<RangeLongBlock> fromPrim = RangeLongBlock.createRangeLongBlocks(primativeArray); Assert.assertEquals(blocks, fromPrim); List<RangeLongBlock> fromObjectArray = RangeLongBlock.createRangeLongBlocks(objectArray); Assert.assertEquals(blocks, fromObjectArray); List<RangeLongBlock> fromCollection = RangeLongBlock.createRangeLongBlocks(collection); Assert.assertEquals(blocks, fromCollection); }
### Question: RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public static boolean isContiguous(long[] values) { if (values.length == 1) { return true; } boolean contiguous = true; for (int i = 1; i < values.length && contiguous; i++) { if (values[i - 1] != values[i] && values[i - 1] != values[i] - 1) { contiguous = false; break; } } return contiguous; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer: @Test public void testStaticIsContiguous() { long[] contigSet = { 5, 6, 7, 8 }; long[] contigSetWithDupes = { 5, 6, 7, 7, 8 }; long[] nonContigSet = { 5, 6, 8, 9 }; long[] unorderedButCongitIfSorted = { 7, 5, 6, 8 }; long[] random = { 23, 88, 234, -12 }; long[] oneValue = { 8 }; long[] contigReverse = { 9, 8, 7, 6 }; Assert.assertTrue(RangeLongBlock.isContiguous(contigSet)); Assert.assertTrue(RangeLongBlock.isContiguous(contigSetWithDupes)); Assert.assertFalse(RangeLongBlock.isContiguous(nonContigSet)); Assert.assertFalse(RangeLongBlock.isContiguous(unorderedButCongitIfSorted)); Arrays.sort(unorderedButCongitIfSorted); Assert.assertTrue(RangeLongBlock.isContiguous(unorderedButCongitIfSorted)); Assert.assertFalse(RangeLongBlock.isContiguous(random)); Arrays.sort(random); Assert.assertFalse(RangeLongBlock.isContiguous(random)); Assert.assertTrue(RangeLongBlock.isContiguous(oneValue)); Assert.assertFalse(RangeLongBlock.isContiguous(contigReverse)); Arrays.sort(contigReverse); Assert.assertTrue(RangeLongBlock.isContiguous(contigReverse)); }
### Question: DefaultRangedLongSet implements RangedLongSet { @Override public Iterator<Long> iterator() { return new LongIterableIterator(getBlocks()); } DefaultRangedLongSet(); DefaultRangedLongSet(Collection<Long> values); DefaultRangedLongSet(DefaultRangedLongSet other); DefaultRangedLongSet(long singularValue); DefaultRangedLongSet(long[] values); DefaultRangedLongSet(Long[] values); DefaultRangedLongSet(RangeLongBlock block); @Override boolean add(long value); @Override boolean add(Long value); @Override boolean add(RangedLongSet otherSet); @Override boolean addAll(Collection<? extends Long> values); @Override boolean addAll(long[] values); @Override boolean addAll(Long[] values); @Override boolean addBlock(RangeLongBlock insertBlock); @Override boolean addBlocks(Collection<RangeLongBlock> blocksToAdd); @Override int blockCount(); @Override void clear(); @Override boolean contains(Long value); @Override boolean contains(Object value); @Override boolean containsAll(Collection<?> c); @Override boolean equals(Object obj); @Override List<RangeLongBlock> getBlocks(); @Override RangedLongSet getDifference(long[] values); @Override RangedLongSet getDifference(RangedLongSet other); @Override RangedLongSet getIntersection(Collection<Long> values); @Override RangedLongSet getIntersection(long[] values); @Override RangedLongSet getIntersection(Long[] values); @Override RangedLongSet getIntersection(RangedLongSet otherSet); @Override RangedLongSet getIntersection(RangeLongBlock blockToIntersect); @Override Long getMaximum(); @Override Long getMinimum(); @Override RangedLongSet getUnion(RangedLongSet other); @Override long[] getValues(); @Override int hashCode(); @Override boolean hasValue(long value); @Override boolean intersects(RangeLongBlock block); @Override boolean isEmpty(); @Override Iterator<Long> iterator(); @Override boolean remove(Collection<? extends Long> valueList); @Override boolean remove(long value); @Override boolean remove(Long value); @Override boolean remove(long[] values); @Override boolean remove(Long[] values); @Override boolean remove(Object o); @Override boolean remove(RangedLongSet otherSet); @Override boolean removeAll(Collection<?> stuff); @Override boolean removeBlock(RangeLongBlock blockToRemove); @Override boolean removeBlocks(Collection<RangeLongBlock> blocksToRemove); @Override boolean retainAll(Collection<?> stuff); @Override int size(); @Override Object[] toArray(); @SuppressWarnings("unchecked") @Override T[] toArray(T[] arg0); @Override String toString(); @Override long valueCount(); }### Answer: @Test public void testIterator() { long[] set = { 1, 2, 3, 5, 6, 7, 9, 10, 11 }; DefaultRangedLongSet rls = new DefaultRangedLongSet(set); Iterator<Long> itr = rls.iterator(); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(1, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(2, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(3, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(5, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(6, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(7, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(9, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(10, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(11, itr.next().longValue()); Assert.assertTrue(!itr.hasNext()); TestHelper.testNoSuchElement(itr); TestHelper.testUnsupportedRemove(itr); }
### Question: EncryptedPrivateKeyAndCertChain implements Cloneable { public boolean validate() { return myAlias != null && myCertificateChain != null && myEncryptedPrivateKey != null && myKeyAlgorithm != null; } @Override EncryptedPrivateKeyAndCertChain clone(); String getAlias(); List<? extends X509Certificate> getCertificateChain(); PrivateKey getPrivateKey(CipherFactory cipherFactory); SimplePrivateKeyProvider getPrivateKeyProvider(final CipherFactory cipherFactory); void setAlias(String alias); void setCertificateChain(Collection<? extends X509Certificate> chain); void setPrivateKey(PrivateKey pk, CipherFactory cipherFactory); void setPrivateKeyProvider(PrivateKeyProvider in, CipherFactory cipherFactory); @Override String toString(); boolean validate(); }### Answer: @Test public void testValidate() throws JAXBException, GeneralSecurityException { EncryptedPrivateKeyAndCertChain obj; obj = new EncryptedPrivateKeyAndCertChain(); Assert.assertFalse(obj.validate()); obj = new EncryptedPrivateKeyAndCertChain(); obj.setAlias(TEST_ALIAS); Assert.assertFalse(obj.validate()); obj = new EncryptedPrivateKeyAndCertChain(); obj.setPrivateKey(getRSAPrivateKey(), ourCipherFactory); Assert.assertFalse(obj.validate()); obj = new EncryptedPrivateKeyAndCertChain(); obj.setCertificateChain(getRSACertChain()); Assert.assertFalse(obj.validate()); obj = new EncryptedPrivateKeyAndCertChain(); obj.setPrivateKey(getRSAPrivateKey(), ourCipherFactory); obj.setCertificateChain(getRSACertChain()); Assert.assertFalse(obj.validate()); obj = new EncryptedPrivateKeyAndCertChain(); obj.setAlias(TEST_ALIAS); obj.setCertificateChain(getRSACertChain()); Assert.assertFalse(obj.validate()); obj = new EncryptedPrivateKeyAndCertChain(); obj.setAlias(TEST_ALIAS); obj.setPrivateKey(getRSAPrivateKey(), ourCipherFactory); Assert.assertFalse(obj.validate()); obj = new EncryptedPrivateKeyAndCertChain(); obj.setAlias(TEST_ALIAS); obj.setPrivateKey(getRSAPrivateKey(), ourCipherFactory); obj.setCertificateChain(getRSACertChain()); Assert.assertTrue(obj.validate()); }
### Question: BoundingBoxController implements Observer { public void close() { myModel.deleteObserver(this); myMapModel.deleteObserver(this); } BoundingBoxController(MapModel mapModel, BoundingBoxModel model); void close(); @Override void update(Observable o, Object arg); }### Answer: @Test public void testClose() { MapModel mapModel = new MapModel(); mapModel.setHeightWidth(400, 400); BoundingBoxModel model = new BoundingBoxModel(); BoundingBoxController controller = new BoundingBoxController(mapModel, model); assertEquals(1, mapModel.countObservers()); assertEquals(1, model.countObservers()); controller.close(); assertEquals(0, mapModel.countObservers()); assertEquals(0, model.countObservers()); }
### Question: MathUtil { public static double average(double a, double b) { return (a + b) * 0.5; } private MathUtil(); static int addSafe(int a, int b); static long addSafe(long a, long b); static double average(double a, double b); static double average(int... values); static boolean between(double val, double min, double max); static boolean between(int val, int min, int max); static boolean between(long val, long min, long max); static long bitShift(long inputVal, int shift); static long byteShift(long inputVal, int shift); static double clamp(double input, double min, double max); static float clamp(float input, float min, float max); static int clamp(int input, int min, int max); static long clamp(long input, long min, long max); static boolean contains(int[] input, int value); static boolean equals(double[] arr1, double[] arr2); static double findLeastPositive(double[] values); static int gcd(int i, int j); static int gcd(int i, int j, int... vals); static int gcd(int[] vals); static float getModulatedFloat(long value, long min, long max); static boolean isPowerOfTwo(int number); static boolean isZero(double val); static boolean isZero(double val, double tolerance); static double lerp(double percent, double startValue, double endValue); static double log(double value, double base); static double map(int value, double min, double max); static double map(long value, double min, double max); @SuppressWarnings("PMD.AvoidUsingShortType") static double map(short value, double min, double max); static ValueWithCount<Integer> mode(int[] values, int... valuesToIgnore); static int nearestPowerOfTwo(int number); static double normalize(double value, double min, double max); static int randomInt(int min, int max); static double reduceSinAngle(double radians); static double roundDecimalPlace(double value, int place); static int roundDownTo(int value, int modulus); static long roundDownTo(long value, long modulus); static int roundUpTo(int value, int modulus); static long roundUpTo(long value, long modulus); static boolean sameSign(double a, double b); static boolean sameSign(int a, int b); static double standardDeviation(int... values); static int subtractSafe(int a, int b); static long subtractSafe(long a, long b); static final double DBL_EPSILON; static final double DBL_LARGE_EPSILON; static final double DEG_TO_RAD; static final float FLOAT_EPSILON; static final double HALF_PI; static final double INV_PI; static final double TWO_PI; static final double INV_TWO_PI; static final double ONE_THIRD; static final double QUARTER_PI; static final double RAD_TO_DEG; static final Random RAND; static final double SQRT2; }### Answer: @Test public void testAverage() { Assert.assertEquals(5., MathUtil.average(2, 4, 4, 4, 5, 5, 7, 9), 0.); Assert.assertEquals(2., MathUtil.average(2), 0.); Assert.assertTrue(Double.isNaN(MathUtil.average())); }
### Question: MathUtil { public static long bitShift(long inputVal, int shift) { return shift > 0 ? inputVal << shift : shift < 0 ? inputVal >> shift * -1 : inputVal; } private MathUtil(); static int addSafe(int a, int b); static long addSafe(long a, long b); static double average(double a, double b); static double average(int... values); static boolean between(double val, double min, double max); static boolean between(int val, int min, int max); static boolean between(long val, long min, long max); static long bitShift(long inputVal, int shift); static long byteShift(long inputVal, int shift); static double clamp(double input, double min, double max); static float clamp(float input, float min, float max); static int clamp(int input, int min, int max); static long clamp(long input, long min, long max); static boolean contains(int[] input, int value); static boolean equals(double[] arr1, double[] arr2); static double findLeastPositive(double[] values); static int gcd(int i, int j); static int gcd(int i, int j, int... vals); static int gcd(int[] vals); static float getModulatedFloat(long value, long min, long max); static boolean isPowerOfTwo(int number); static boolean isZero(double val); static boolean isZero(double val, double tolerance); static double lerp(double percent, double startValue, double endValue); static double log(double value, double base); static double map(int value, double min, double max); static double map(long value, double min, double max); @SuppressWarnings("PMD.AvoidUsingShortType") static double map(short value, double min, double max); static ValueWithCount<Integer> mode(int[] values, int... valuesToIgnore); static int nearestPowerOfTwo(int number); static double normalize(double value, double min, double max); static int randomInt(int min, int max); static double reduceSinAngle(double radians); static double roundDecimalPlace(double value, int place); static int roundDownTo(int value, int modulus); static long roundDownTo(long value, long modulus); static int roundUpTo(int value, int modulus); static long roundUpTo(long value, long modulus); static boolean sameSign(double a, double b); static boolean sameSign(int a, int b); static double standardDeviation(int... values); static int subtractSafe(int a, int b); static long subtractSafe(long a, long b); static final double DBL_EPSILON; static final double DBL_LARGE_EPSILON; static final double DEG_TO_RAD; static final float FLOAT_EPSILON; static final double HALF_PI; static final double INV_PI; static final double TWO_PI; static final double INV_TWO_PI; static final double ONE_THIRD; static final double QUARTER_PI; static final double RAD_TO_DEG; static final Random RAND; static final double SQRT2; }### Answer: @Test public void testBitShift() { Assert.assertEquals(4, MathUtil.bitShift(1, 2)); Assert.assertEquals(2, MathUtil.bitShift(1, 1)); Assert.assertEquals(1, MathUtil.bitShift(1, 0)); Assert.assertEquals(0, MathUtil.bitShift(1, -1)); Assert.assertEquals(0, MathUtil.bitShift(1, -2)); Assert.assertEquals(8, MathUtil.bitShift(2, 2)); Assert.assertEquals(4, MathUtil.bitShift(2, 1)); Assert.assertEquals(2, MathUtil.bitShift(2, 0)); Assert.assertEquals(1, MathUtil.bitShift(2, -1)); Assert.assertEquals(0, MathUtil.bitShift(2, -2)); }
### Question: MapModel extends Observable { public void setHeightWidth(int height, int width) { if (myHeight != height || myWidth != width) { myHeight = height; myWidth = width; setChanged(); notifyObservers(SIZE_PROP); } } int getHeight(); Quadrilateral<GeographicPosition> getRegion(); ScreenBoundingBox getViewport(); int getWidth(); void setHeightWidth(int height, int width); void setRegion(Quadrilateral<GeographicPosition> region); void setViewport(ScreenBoundingBox viewport); static final String REGION_PROP; static final String SIZE_PROP; }### Answer: @Test public void testSetHeightWidth() { EasyMockSupport support = new EasyMockSupport(); MapModel model = new MapModel(); Observer observer = createObserver(support, model, MapModel.SIZE_PROP, 3); model.addObserver(observer); support.replayAll(); model.setHeightWidth(100, 200); assertEquals(100, model.getHeight()); assertEquals(200, model.getWidth()); model.setHeightWidth(100, 200); model.setHeightWidth(200, 200); assertEquals(200, model.getHeight()); assertEquals(200, model.getWidth()); model.setHeightWidth(200, 100); assertEquals(200, model.getHeight()); assertEquals(100, model.getWidth()); support.verifyAll(); }
### Question: ElementData { public TimeSpan getTimeSpan() { return myTimeSpan; } ElementData(); ElementData(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); boolean found(); Long getID(); MapGeometrySupport getMapGeometrySupport(); MetaDataProvider getMetaDataProvider(); TimeSpan getTimeSpan(); VisualizationState getVisualizationState(); final void updateValues(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); }### Answer: @Test public void testGetTimeSpan() { assertEquals(myTimeSpan, myTestObject.getTimeSpan()); }
### Question: MathUtil { public static boolean contains(int[] input, int value) { for (int in : input) { if (in == value) { return true; } } return false; } private MathUtil(); static int addSafe(int a, int b); static long addSafe(long a, long b); static double average(double a, double b); static double average(int... values); static boolean between(double val, double min, double max); static boolean between(int val, int min, int max); static boolean between(long val, long min, long max); static long bitShift(long inputVal, int shift); static long byteShift(long inputVal, int shift); static double clamp(double input, double min, double max); static float clamp(float input, float min, float max); static int clamp(int input, int min, int max); static long clamp(long input, long min, long max); static boolean contains(int[] input, int value); static boolean equals(double[] arr1, double[] arr2); static double findLeastPositive(double[] values); static int gcd(int i, int j); static int gcd(int i, int j, int... vals); static int gcd(int[] vals); static float getModulatedFloat(long value, long min, long max); static boolean isPowerOfTwo(int number); static boolean isZero(double val); static boolean isZero(double val, double tolerance); static double lerp(double percent, double startValue, double endValue); static double log(double value, double base); static double map(int value, double min, double max); static double map(long value, double min, double max); @SuppressWarnings("PMD.AvoidUsingShortType") static double map(short value, double min, double max); static ValueWithCount<Integer> mode(int[] values, int... valuesToIgnore); static int nearestPowerOfTwo(int number); static double normalize(double value, double min, double max); static int randomInt(int min, int max); static double reduceSinAngle(double radians); static double roundDecimalPlace(double value, int place); static int roundDownTo(int value, int modulus); static long roundDownTo(long value, long modulus); static int roundUpTo(int value, int modulus); static long roundUpTo(long value, long modulus); static boolean sameSign(double a, double b); static boolean sameSign(int a, int b); static double standardDeviation(int... values); static int subtractSafe(int a, int b); static long subtractSafe(long a, long b); static final double DBL_EPSILON; static final double DBL_LARGE_EPSILON; static final double DEG_TO_RAD; static final float FLOAT_EPSILON; static final double HALF_PI; static final double INV_PI; static final double TWO_PI; static final double INV_TWO_PI; static final double ONE_THIRD; static final double QUARTER_PI; static final double RAD_TO_DEG; static final Random RAND; static final double SQRT2; }### Answer: @Test public void testContains() { Assert.assertTrue(MathUtil.contains(new int[] { 1, 2, 3 }, 2)); Assert.assertTrue(MathUtil.contains(new int[] { 2 }, 2)); Assert.assertFalse(MathUtil.contains(new int[] { 1, 2, 3 }, 4)); Assert.assertFalse(MathUtil.contains(new int[] {}, 4)); }
### Question: MathUtil { public static int roundDownTo(int value, int modulus) { return value >= 0 ? value - value % modulus : value + (value % modulus == 0 ? 0 : -modulus - value % modulus); } private MathUtil(); static int addSafe(int a, int b); static long addSafe(long a, long b); static double average(double a, double b); static double average(int... values); static boolean between(double val, double min, double max); static boolean between(int val, int min, int max); static boolean between(long val, long min, long max); static long bitShift(long inputVal, int shift); static long byteShift(long inputVal, int shift); static double clamp(double input, double min, double max); static float clamp(float input, float min, float max); static int clamp(int input, int min, int max); static long clamp(long input, long min, long max); static boolean contains(int[] input, int value); static boolean equals(double[] arr1, double[] arr2); static double findLeastPositive(double[] values); static int gcd(int i, int j); static int gcd(int i, int j, int... vals); static int gcd(int[] vals); static float getModulatedFloat(long value, long min, long max); static boolean isPowerOfTwo(int number); static boolean isZero(double val); static boolean isZero(double val, double tolerance); static double lerp(double percent, double startValue, double endValue); static double log(double value, double base); static double map(int value, double min, double max); static double map(long value, double min, double max); @SuppressWarnings("PMD.AvoidUsingShortType") static double map(short value, double min, double max); static ValueWithCount<Integer> mode(int[] values, int... valuesToIgnore); static int nearestPowerOfTwo(int number); static double normalize(double value, double min, double max); static int randomInt(int min, int max); static double reduceSinAngle(double radians); static double roundDecimalPlace(double value, int place); static int roundDownTo(int value, int modulus); static long roundDownTo(long value, long modulus); static int roundUpTo(int value, int modulus); static long roundUpTo(long value, long modulus); static boolean sameSign(double a, double b); static boolean sameSign(int a, int b); static double standardDeviation(int... values); static int subtractSafe(int a, int b); static long subtractSafe(long a, long b); static final double DBL_EPSILON; static final double DBL_LARGE_EPSILON; static final double DEG_TO_RAD; static final float FLOAT_EPSILON; static final double HALF_PI; static final double INV_PI; static final double TWO_PI; static final double INV_TWO_PI; static final double ONE_THIRD; static final double QUARTER_PI; static final double RAD_TO_DEG; static final Random RAND; static final double SQRT2; }### Answer: @Test public void testRoundDownToIntInt() { for (int i = -8; i < 0; ++i) { Assert.assertEquals(-8, MathUtil.roundDownTo(i, 8)); } for (int i = 0; i < 8; ++i) { Assert.assertEquals(0, MathUtil.roundDownTo(i, 8)); } for (int i = 8; i < 16; ++i) { Assert.assertEquals(8, MathUtil.roundDownTo(i, 8)); } Assert.assertEquals(16, MathUtil.roundDownTo(16, 8)); } @Test public void testRoundDownToLongLong() { for (long i = 0L; i < 8L; ++i) { Assert.assertEquals(0L, MathUtil.roundDownTo(i, 8L)); } for (long i = 8L; i < 16L; ++i) { Assert.assertEquals(8L, MathUtil.roundDownTo(i, 8L)); } Assert.assertEquals(16L, MathUtil.roundDownTo(16L, 8L)); }
### Question: MapModel extends Observable { public void setRegion(Quadrilateral<GeographicPosition> region) { myRegion = region; setChanged(); notifyObservers(REGION_PROP); } int getHeight(); Quadrilateral<GeographicPosition> getRegion(); ScreenBoundingBox getViewport(); int getWidth(); void setHeightWidth(int height, int width); void setRegion(Quadrilateral<GeographicPosition> region); void setViewport(ScreenBoundingBox viewport); static final String REGION_PROP; static final String SIZE_PROP; }### Answer: @Test public void testSetRegion() { EasyMockSupport support = new EasyMockSupport(); GeographicBoundingBox region = new GeographicBoundingBox(LatLonAlt.createFromDegrees(-45d, -90d), LatLonAlt.createFromDegrees(0, 0)); MapModel model = new MapModel(); Observer observer = createObserver(support, model, MapModel.REGION_PROP, 1); model.addObserver(observer); support.replayAll(); model.setRegion(region); assertEquals(region, model.getRegion()); support.verifyAll(); }
### Question: MathUtil { public static double standardDeviation(int... values) { double average = average(values); double sumOfSquares = 0; double diff; for (int value : values) { diff = value - average; sumOfSquares += diff * diff; } return Math.sqrt(sumOfSquares / values.length); } private MathUtil(); static int addSafe(int a, int b); static long addSafe(long a, long b); static double average(double a, double b); static double average(int... values); static boolean between(double val, double min, double max); static boolean between(int val, int min, int max); static boolean between(long val, long min, long max); static long bitShift(long inputVal, int shift); static long byteShift(long inputVal, int shift); static double clamp(double input, double min, double max); static float clamp(float input, float min, float max); static int clamp(int input, int min, int max); static long clamp(long input, long min, long max); static boolean contains(int[] input, int value); static boolean equals(double[] arr1, double[] arr2); static double findLeastPositive(double[] values); static int gcd(int i, int j); static int gcd(int i, int j, int... vals); static int gcd(int[] vals); static float getModulatedFloat(long value, long min, long max); static boolean isPowerOfTwo(int number); static boolean isZero(double val); static boolean isZero(double val, double tolerance); static double lerp(double percent, double startValue, double endValue); static double log(double value, double base); static double map(int value, double min, double max); static double map(long value, double min, double max); @SuppressWarnings("PMD.AvoidUsingShortType") static double map(short value, double min, double max); static ValueWithCount<Integer> mode(int[] values, int... valuesToIgnore); static int nearestPowerOfTwo(int number); static double normalize(double value, double min, double max); static int randomInt(int min, int max); static double reduceSinAngle(double radians); static double roundDecimalPlace(double value, int place); static int roundDownTo(int value, int modulus); static long roundDownTo(long value, long modulus); static int roundUpTo(int value, int modulus); static long roundUpTo(long value, long modulus); static boolean sameSign(double a, double b); static boolean sameSign(int a, int b); static double standardDeviation(int... values); static int subtractSafe(int a, int b); static long subtractSafe(long a, long b); static final double DBL_EPSILON; static final double DBL_LARGE_EPSILON; static final double DEG_TO_RAD; static final float FLOAT_EPSILON; static final double HALF_PI; static final double INV_PI; static final double TWO_PI; static final double INV_TWO_PI; static final double ONE_THIRD; static final double QUARTER_PI; static final double RAD_TO_DEG; static final Random RAND; static final double SQRT2; }### Answer: @Test public void testStandardDeviation() { Assert.assertEquals(2., MathUtil.standardDeviation(2, 4, 4, 4, 5, 5, 7, 9), 0.); Assert.assertEquals(0., MathUtil.standardDeviation(2), 0.); Assert.assertTrue(Double.isNaN(MathUtil.standardDeviation())); }
### Question: BufferUtilities { public static ByteBuffer clone(ByteBuffer buf) { final ByteBuffer result = buf.isDirect() ? ByteBuffer.allocateDirect(buf.capacity()) : ByteBuffer.allocate(buf.capacity()); final ByteBuffer dup = buf.duplicate(); dup.rewind().limit(dup.capacity()); result.put(dup); result.position(buf.position()); result.limit(buf.limit()); result.order(buf.order()); return result; } private BufferUtilities(); static void addSequenceToBuffer(int begin, int count, IntBuffer buf); static ByteBuffer clone(ByteBuffer buf); static ByteBuffer newByteBuffer(int capacity); static ByteBuffer newByteBuffer(int capacity, boolean direct); static FloatBuffer newFloatBuffer(int capacity); static IntBuffer newIntBuffer(int capacity); static ByteBuffer newRepeatingByteBuffer(int numberOfRepeats, ByteBuffer sequence); static IntBuffer newSequentialIntBuffer(int begin, int count); static byte[] toByteArray(ByteBuffer data); static IntBuffer toIntBuffer(int[] array); static IntBuffer toIntBuffer(TIntList list); }### Answer: @Test public void testCloneByteBuffer() { byte[] arr = new byte[20]; RANDOM.nextBytes(arr); ByteBuffer buf; ByteBuffer clone; buf = ByteBuffer.wrap(arr, 5, 10); clone = BufferUtilities.clone(buf); Assert.assertNotSame(arr, clone.array()); Assert.assertEquals(buf.position(), clone.position()); Assert.assertEquals(buf.limit(), clone.limit()); Assert.assertEquals(buf.capacity(), clone.capacity()); Assert.assertTrue(buf.isDirect() == clone.isDirect()); buf.position(0).limit(buf.capacity()); clone.position(0).limit(buf.capacity()); Assert.assertTrue(buf.equals(clone)); clone.put(5, (byte)(clone.get(5) ^ 1)); Assert.assertFalse(buf.equals(clone)); buf = buf.asReadOnlyBuffer(); clone = BufferUtilities.clone(buf); Assert.assertNotSame(arr, clone.array()); Assert.assertEquals(buf.position(), clone.position()); Assert.assertEquals(buf.limit(), clone.limit()); Assert.assertEquals(buf.capacity(), clone.capacity()); Assert.assertTrue(buf.isDirect() == clone.isDirect()); buf.position(0).limit(buf.capacity()); clone.position(0).limit(buf.capacity()); Assert.assertTrue(buf.equals(clone)); clone.put(5, (byte)(clone.get(5) ^ 1)); Assert.assertFalse(buf.equals(clone)); buf = ByteBuffer.allocateDirect(arr.length); buf.put(arr); clone = BufferUtilities.clone(buf); Assert.assertEquals(buf.position(), clone.position()); Assert.assertEquals(buf.limit(), clone.limit()); Assert.assertEquals(buf.capacity(), clone.capacity()); buf.position(0).limit(buf.capacity()); clone.position(0).limit(buf.capacity()); Assert.assertTrue(buf.equals(clone)); clone.put(5, (byte)(clone.get(5) ^ 1)); Assert.assertFalse(buf.equals(clone)); }
### Question: Aggregator { public void addItem(T item) { if (myBatchSize > 1) { myItems.add(item); if (myItems.size() >= myBatchSize) { processAll(); } } else { myProcessor.accept(Collections.singletonList(item)); } } Aggregator(int batchSize, Consumer<List<T>> processor); static void process(Collection<? extends T> items, int batchSize, Consumer<List<T>> processor); void addItem(T item); void addItems(Collection<? extends T> items); void processAll(); }### Answer: @Test public void testAggregation() { StringJoiner joiner = new StringJoiner("-"); Aggregator<String> aggregator = new Aggregator<>(3, items -> items.forEach(joiner::add)); aggregator.addItem("hey"); Assert.assertEquals("", joiner.toString()); aggregator.addItem("there"); Assert.assertEquals("", joiner.toString()); aggregator.addItem("dude"); Assert.assertEquals("hey-there-dude", joiner.toString()); } @Test public void testNoAggregation() { StringJoiner joiner = new StringJoiner("-"); Aggregator<String> aggregator = new Aggregator<>(1, items -> items.forEach(joiner::add)); aggregator.addItem("hey"); Assert.assertEquals("hey", joiner.toString()); aggregator.addItem("there"); Assert.assertEquals("hey-there", joiner.toString()); }
### Question: URLEncodingUtilities { public static URL encodeURL(URL url) { URL encodedURL = null; if (url != null) { UrlBuilder builder = new UrlBuilder(url); builder.setQueryParameters(encodeQueryParameters(builder.getQueryParameters())); try { encodedURL = builder.toURL(); } catch (MalformedURLException e) { encodedURL = url; } } return encodedURL; } private URLEncodingUtilities(); static URL encodeURL(URL url); }### Answer: @Test public void testEncodeURL() throws MalformedURLException { URL input = new URL("http: URL expected = new URL("http: URL actual = URLEncodingUtilities.encodeURL(input); Assert.assertEquals(expected.toString(), actual.toString()); } @Test public void testEncodeURLNoQuery() throws MalformedURLException { URL input = new URL("http: URL actual = URLEncodingUtilities.encodeURL(input); Assert.assertEquals(input.toString(), actual.toString()); } @Test public void testEncodeURLNull() { Assert.assertNull(URLEncodingUtilities.encodeURL(null)); }
### Question: UrlBuilder { public void addPath(String path) { myPath = StringUtilities.concat(myPath, ensureStartsWith(path, '/')); } UrlBuilder(); UrlBuilder(String url); UrlBuilder(URL url); void addPath(String path); void addQuery(String query); String getHost(); String getPath(); int getPort(); String getProtocol(); String getQuery(); Map<String, String> getQueryParameters(); String getRef(); void setHost(String host); void setPath(String path); void setPort(int port); void setProtocol(String protocol); void setQuery(String query); void setQueryParameters(Map<String, String> queryParameters); void setRef(String ref); void setUrl(URL url); @Override String toString(); URL toURL(); }### Answer: @Test public void testAddPath() { URL input = createUrl("http: URL expected = createUrl("http: UrlBuilder builder = new UrlBuilder(input); builder.addPath("more"); try { Assert.assertEquals(expected.toString(), builder.toURL().toString()); } catch (MalformedURLException e) { Assert.fail(e.getMessage()); } }
### Question: BackgroundModel extends Observable { public void add(Collection<TileGeometry> geometry) { myGeometries.addAll(geometry); setChanged(); notifyObservers(GEOMETRIES_PROP); } void add(Collection<TileGeometry> geometry); Collection<TileGeometry> getGeometries(); List<Double> getGeometryScaleFactors(); void remove(Collection<TileGeometry> geometry); static final String GEOMETRIES_PROP; }### Answer: @Test public void testAdd() { EasyMockSupport support = new EasyMockSupport(); BackgroundModel model = new BackgroundModel(); Observer observer = createObserver(support, model); support.replayAll(); model.addObserver(observer); TileGeometry[] geometries = createGeometries(); model.add(New.list(geometries)); assertEquals(2, model.getGeometries().size()); assertTrue(model.getGeometries().contains(geometries[0])); assertTrue(model.getGeometries().contains(geometries[1])); support.verifyAll(); }
### Question: UrlBuilder { public void addQuery(String query) { if (!StringUtils.isBlank(query)) { getQueryParameters().putAll(getQueryParameters(query)); myQuery = null; } } UrlBuilder(); UrlBuilder(String url); UrlBuilder(URL url); void addPath(String path); void addQuery(String query); String getHost(); String getPath(); int getPort(); String getProtocol(); String getQuery(); Map<String, String> getQueryParameters(); String getRef(); void setHost(String host); void setPath(String path); void setPort(int port); void setProtocol(String protocol); void setQuery(String query); void setQueryParameters(Map<String, String> queryParameters); void setRef(String ref); void setUrl(URL url); @Override String toString(); URL toURL(); }### Answer: @Test public void testAddQuery() { URL input = createUrl("http: URL expected = createUrl("http: UrlBuilder builder = new UrlBuilder(input); builder.addQuery("e=f"); try { Assert.assertEquals(expected.toString(), builder.toURL().toString()); } catch (MalformedURLException e) { Assert.fail(e.getMessage()); } }
### Question: UrlBuilder { public void setPath(String path) { myPath = ensureStartsWith(path, '/'); } UrlBuilder(); UrlBuilder(String url); UrlBuilder(URL url); void addPath(String path); void addQuery(String query); String getHost(); String getPath(); int getPort(); String getProtocol(); String getQuery(); Map<String, String> getQueryParameters(); String getRef(); void setHost(String host); void setPath(String path); void setPort(int port); void setProtocol(String protocol); void setQuery(String query); void setQueryParameters(Map<String, String> queryParameters); void setRef(String ref); void setUrl(URL url); @Override String toString(); URL toURL(); }### Answer: @Test public void testSetPath() { URL input = createUrl("http: URL expected = createUrl("http: UrlBuilder builder = new UrlBuilder(input); builder.setPath("something/getKml.pl"); try { Assert.assertEquals(expected.toString(), builder.toURL().toString()); } catch (MalformedURLException e) { Assert.fail(e.getMessage()); } builder.setPath("/something/getKml.pl"); try { Assert.assertEquals(expected.toString(), builder.toURL().toString()); } catch (MalformedURLException e) { Assert.fail(e.getMessage()); } }
### Question: UrlBuilder { public URL toURL() throws MalformedURLException { return new URL(toString()); } UrlBuilder(); UrlBuilder(String url); UrlBuilder(URL url); void addPath(String path); void addQuery(String query); String getHost(); String getPath(); int getPort(); String getProtocol(); String getQuery(); Map<String, String> getQueryParameters(); String getRef(); void setHost(String host); void setPath(String path); void setPort(int port); void setProtocol(String protocol); void setQuery(String query); void setQueryParameters(Map<String, String> queryParameters); void setRef(String ref); void setUrl(URL url); @Override String toString(); URL toURL(); }### Answer: @Test public void testToURL() { URL input = createUrl("http: UrlBuilder builder = new UrlBuilder(input); Assert.assertEquals("http", builder.getProtocol()); Assert.assertEquals("www.blah.com", builder.getHost()); Assert.assertEquals(8080, builder.getPort()); Assert.assertEquals("/something/getKml.pl", builder.getPath()); Assert.assertEquals("a=b&c=d", builder.getQuery()); Assert.assertEquals("ref", builder.getRef()); Assert.assertEquals("b", builder.getQueryParameters().get("a")); try { Assert.assertEquals(input.toString(), builder.toURL().toString()); } catch (MalformedURLException e) { Assert.fail(e.getMessage()); } }
### Question: UrlUtilities { public static boolean isFile(URL url) { boolean isFile = false; String protocol = url.getProtocol(); if ("file".equalsIgnoreCase(protocol) || "jar".equalsIgnoreCase(protocol)) { isFile = true; } return isFile; } private UrlUtilities(); static String getBaseURL(URL u); static String getBaseURL(String u); static ThreeTuple<String, String, Integer> getProtocolHostPort(String url, int defaultPort); static boolean isFragmentPresent(URL url); static String getFragment(URL url); static boolean isFile(URL url); static URL toURL(String urlString); static URL toURLNew(String urlOrPathString); static String concatUrlFragments(String... fragments); }### Answer: @Test public void testIsFile() throws MalformedURLException { URL fileUrl = new URL("file:/C:/test.txt"); URL javaFileUrl = new URL("jar:file:/C:/Program%20Files/OpenSphere/OpenSphere-KML-plugin.jar!" + "/images/maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png"); URL httpUrl = new URL("http: assertTrue(UrlUtilities.isFile(fileUrl)); assertTrue(UrlUtilities.isFile(javaFileUrl)); assertFalse(UrlUtilities.isFile(httpUrl)); }
### Question: UrlUtilities { public static ThreeTuple<String, String, Integer> getProtocolHostPort(String url, int defaultPort) { int wheresTheColon = url.indexOf(':'); int hostBeginIndex = wheresTheColon + 3; String protocol = url.substring(0, wheresTheColon); int hostEndIndex = url.indexOf('/', hostBeginIndex); String host = url.substring(hostBeginIndex); if (hostEndIndex > 0) { host = host.substring(0, hostEndIndex - hostBeginIndex); } int rtmpPort = defaultPort; int portIndex = host.indexOf(':'); if (portIndex > 0) { String portString = host.substring(portIndex + 1); rtmpPort = Integer.parseInt(portString); host = host.substring(0, portIndex); } return new ThreeTuple<>(protocol, host, Integer.valueOf(rtmpPort)); } private UrlUtilities(); static String getBaseURL(URL u); static String getBaseURL(String u); static ThreeTuple<String, String, Integer> getProtocolHostPort(String url, int defaultPort); static boolean isFragmentPresent(URL url); static String getFragment(URL url); static boolean isFile(URL url); static URL toURL(String urlString); static URL toURLNew(String urlOrPathString); static String concatUrlFragments(String... fragments); }### Answer: @Test public void testGetProtocolHostPort() { ThreeTuple<String, String, Integer> protoHostPort = UrlUtilities.getProtocolHostPort("http: assertEquals("http", protoHostPort.getFirstObject()); assertEquals("somehost", protoHostPort.getSecondObject()); assertEquals(80, protoHostPort.getThirdObject().intValue()); protoHostPort = UrlUtilities.getProtocolHostPort("rtmpt: assertEquals("rtmpt", protoHostPort.getFirstObject()); assertEquals("host", protoHostPort.getSecondObject()); assertEquals(80, protoHostPort.getThirdObject().intValue()); protoHostPort = UrlUtilities.getProtocolHostPort("rtmp: assertEquals("rtmp", protoHostPort.getFirstObject()); assertEquals("host", protoHostPort.getSecondObject()); assertEquals(1935, protoHostPort.getThirdObject().intValue()); protoHostPort = UrlUtilities.getProtocolHostPort("https: assertEquals("https", protoHostPort.getFirstObject()); assertEquals("somehost", protoHostPort.getSecondObject()); assertEquals(8080, protoHostPort.getThirdObject().intValue()); }
### Question: UrlUtilities { public static URL toURLNew(String urlOrPathString) { URL url = null; if (StringUtils.isNotEmpty(urlOrPathString)) { String urlString = hasValidProtocol(urlOrPathString) ? fixFileProtocol(urlOrPathString) : addFileProtocol(urlOrPathString); url = toURL(urlString); } return url; } private UrlUtilities(); static String getBaseURL(URL u); static String getBaseURL(String u); static ThreeTuple<String, String, Integer> getProtocolHostPort(String url, int defaultPort); static boolean isFragmentPresent(URL url); static String getFragment(URL url); static boolean isFile(URL url); static URL toURL(String urlString); static URL toURLNew(String urlOrPathString); static String concatUrlFragments(String... fragments); }### Answer: @SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME") @Test public void testToURLNew() throws MalformedURLException { assertEquals(null, UrlUtilities.toURLNew(null)); assertEquals(null, UrlUtilities.toURLNew("")); assertEquals(new URL("http: assertEquals(new URL("file: assertEquals(new URL("file: assertEquals(new URL("file: assertEquals(new URL("file: assertEquals(new URL("file: assertEquals(new URL("file: }
### Question: FixedThreadPoolExecutor extends AbstractExecutorService { @Override @SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "No ThreadPoolExecutor available to pass.") public void execute(Runnable command) { myAddLock.lock(); try { if (myShuttingDown || !myQueue.add(command)) { myHandler.rejectedExecution(command, null); } } finally { myAddLock.unlock(); } } FixedThreadPoolExecutor(int nThreads); FixedThreadPoolExecutor(int nThreads, NamedThreadFactory factory, SuppressableRejectedExecutionHandler handler); FixedThreadPoolExecutor(int nThreads, ThreadFactory factory); FixedThreadPoolExecutor(int nThreads, ThreadFactory factory, BlockingQueue<Runnable> queue); FixedThreadPoolExecutor(int nThreads, ThreadFactory factory, BlockingQueue<Runnable> queue, RejectedExecutionHandler handler); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override @SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "No ThreadPoolExecutor available to pass.") void execute(Runnable command); BlockingQueue<Runnable> getQueue(); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override void shutdown(); @Override List<Runnable> shutdownNow(); }### Answer: @Test @Ignore public void testExecute() throws InterruptedException { ThreadFactory factory = new ThreadFactoryImplementation(null); int nThreads = 20; int iterations = 100; double jdkLatency = 0.; double optimizedLatency = 0.; int totalIterations = 0; for (int numTasks = 1; numTasks <= 10000; numTasks *= 5) { totalIterations += iterations; for (int i = 0; i < iterations; i++) { ExecutorService jdkExecutor = Executors.newFixedThreadPool(nThreads, factory); jdkLatency += testExecutor(jdkExecutor, numTasks); jdkExecutor.shutdownNow(); } for (int i = 0; i < iterations; i++) { FixedThreadPoolExecutor optimizedExecutor = new FixedThreadPoolExecutor(nThreads, factory); optimizedLatency += testExecutor(optimizedExecutor, numTasks); optimizedExecutor.shutdownNow(); } } Assert.assertTrue("Average latency for " + FixedThreadPoolExecutor.class.getName() + " was " + (float)(optimizedLatency / totalIterations / 1e6) + " ms, which is slower than " + ThreadPoolExecutor.class.getName() + ", which took " + (float)(jdkLatency / totalIterations / 1e6) + " ms.", jdkLatency > optimizedLatency); }
### Question: FixedThreadPoolExecutor extends AbstractExecutorService { @Override public void shutdown() { myShuttingDown = true; synchronized (myWorkers) { for (Worker worker : myWorkers) { worker.interruptIfIdle(); } } } FixedThreadPoolExecutor(int nThreads); FixedThreadPoolExecutor(int nThreads, NamedThreadFactory factory, SuppressableRejectedExecutionHandler handler); FixedThreadPoolExecutor(int nThreads, ThreadFactory factory); FixedThreadPoolExecutor(int nThreads, ThreadFactory factory, BlockingQueue<Runnable> queue); FixedThreadPoolExecutor(int nThreads, ThreadFactory factory, BlockingQueue<Runnable> queue, RejectedExecutionHandler handler); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override @SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "No ThreadPoolExecutor available to pass.") void execute(Runnable command); BlockingQueue<Runnable> getQueue(); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override void shutdown(); @Override List<Runnable> shutdownNow(); }### Answer: @Test public void testShutdown() throws InterruptedException, ExecutionException { ThreadGroup group = createTestThreadGroup(); ThreadFactory factory = new ThreadFactoryImplementation(group); FixedThreadPoolExecutor executor = new FixedThreadPoolExecutor(1, factory); Runnable task1 = EasyMock.createStrictMock(Runnable.class); task1.run(); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws InterruptedException { Thread.sleep(500); return null; } }); EasyMock.replay(task1); Runnable task2 = EasyMock.createStrictMock(Runnable.class); task2.run(); EasyMock.replay(task2); executor.execute(task1); executor.execute(task2); executor.shutdown(); Assert.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); Thread.yield(); if (group.activeCount() > 0) { Thread.sleep(500); } Assert.assertEquals(0, group.activeCount()); EasyMock.verify(task1); EasyMock.verify(task2); }
### Question: FixedThreadPoolExecutor extends AbstractExecutorService { @Override public List<Runnable> shutdownNow() { myStopExecuting = true; myAddLock.lock(); try { myShuttingDown = true; } finally { myAddLock.unlock(); } List<Runnable> unrun = new ArrayList<>(); myQueue.drainTo(unrun); synchronized (myWorkers) { for (Worker worker : myWorkers) { worker.interrupt(); } } return unrun; } FixedThreadPoolExecutor(int nThreads); FixedThreadPoolExecutor(int nThreads, NamedThreadFactory factory, SuppressableRejectedExecutionHandler handler); FixedThreadPoolExecutor(int nThreads, ThreadFactory factory); FixedThreadPoolExecutor(int nThreads, ThreadFactory factory, BlockingQueue<Runnable> queue); FixedThreadPoolExecutor(int nThreads, ThreadFactory factory, BlockingQueue<Runnable> queue, RejectedExecutionHandler handler); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override @SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "No ThreadPoolExecutor available to pass.") void execute(Runnable command); BlockingQueue<Runnable> getQueue(); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override void shutdown(); @Override List<Runnable> shutdownNow(); }### Answer: @Test public void testShutdownNow() throws InterruptedException { if (StringUtils.isEmpty(System.getenv("SLOW_MACHINE"))) { ThreadGroup group = createTestThreadGroup(); ThreadFactory factory = new ThreadFactoryImplementation(group); FixedThreadPoolExecutor executor = new FixedThreadPoolExecutor(1, factory); final CountDownLatch latch = new CountDownLatch(1); Runnable task1 = EasyMock.createStrictMock(Runnable.class); task1.run(); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws InterruptedException { latch.countDown(); Thread.sleep(500); return null; } }); EasyMock.replay(task1); Runnable task2 = EasyMock.createStrictMock(Runnable.class); EasyMock.replay(task2); Runnable task3 = EasyMock.createStrictMock(Runnable.class); EasyMock.replay(task3); Runnable task4 = EasyMock.createStrictMock(Runnable.class); EasyMock.replay(task4); Future<?> future1 = executor.submit(task1); executor.execute(task2); executor.execute(task3); executor.execute(task4); Assert.assertTrue(latch.await(1, TimeUnit.SECONDS)); List<Runnable> unrun = executor.shutdownNow(); Assert.assertEquals(3, unrun.size()); Assert.assertEquals(task2, unrun.get(0)); Assert.assertEquals(task3, unrun.get(1)); Assert.assertEquals(task4, unrun.get(2)); Assert.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); Thread.yield(); if (group.activeCount() > 0) { Thread.sleep(500); } Assert.assertEquals(0, group.activeCount()); try { future1.get(); Assert.fail("Should have been interrupted."); } catch (ExecutionException e) { Assert.assertEquals(InterruptedException.class, e.getCause().getCause().getClass()); } EasyMock.verify(task1); } }
### Question: InlineExecutorService extends AbstractExecutorService { @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); while (nanos > 0) { myLock.lock(); try { if (isTerminated()) { return true; } nanos = myCondition.awaitNanos(nanos); } finally { myLock.unlock(); } } return isTerminated(); } InlineExecutorService(); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override final void execute(Runnable command); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override void shutdown(); @Override List<Runnable> shutdownNow(); }### Answer: @Test public void testAwaitTermination() throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(2); final CountDownLatch latch = new CountDownLatch(2); final AtomicBoolean flag1 = new AtomicBoolean(); final AtomicBoolean flag2 = new AtomicBoolean(); final ExecutorService service = new InlineExecutorService(); pool.execute(new TestRunnable(service, latch, flag1, 100L)); pool.execute(new TestRunnable(service, latch, flag2, 100L)); latch.await(); Assert.assertFalse(service.isShutdown()); service.shutdown(); Assert.assertTrue(service.isShutdown()); Assert.assertFalse(service.isTerminated()); Assert.assertFalse(service.awaitTermination(1, TimeUnit.MILLISECONDS)); Assert.assertFalse(flag1.get()); Assert.assertFalse(flag2.get()); Assert.assertTrue(service.awaitTermination(1000, TimeUnit.MILLISECONDS)); Assert.assertTrue(service.isShutdown()); Assert.assertTrue(service.isTerminated()); Assert.assertTrue(flag1.get()); Assert.assertTrue(flag2.get()); }
### Question: BackgroundModel extends Observable { public void remove(Collection<TileGeometry> geometry) { for (TileGeometry aGeometry : geometry) { myGeometries.remove(aGeometry); } setChanged(); notifyObservers(GEOMETRIES_PROP); } void add(Collection<TileGeometry> geometry); Collection<TileGeometry> getGeometries(); List<Double> getGeometryScaleFactors(); void remove(Collection<TileGeometry> geometry); static final String GEOMETRIES_PROP; }### Answer: @Test public void testRemove() { EasyMockSupport support = new EasyMockSupport(); BackgroundModel model = new BackgroundModel(); Observer observer = createObserver(support, model); TileGeometry[] geometries = createGeometries(); model.add(New.list(geometries)); support.replayAll(); model.addObserver(observer); model.remove(New.list(geometries[0])); assertEquals(1, model.getGeometries().size()); assertEquals(geometries[1], model.getGeometries().iterator().next()); support.verifyAll(); }
### Question: InlineExecutorService extends AbstractExecutorService { @Override public void shutdown() { myShutdown = true; } InlineExecutorService(); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override final void execute(Runnable command); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override void shutdown(); @Override List<Runnable> shutdownNow(); }### Answer: @Test public void testShutdown() { Runnable command = new Runnable() { @Override public void run() { } }; ExecutorService service = new InlineExecutorService(); service.execute(command); Assert.assertFalse(service.isShutdown()); service.shutdown(); Assert.assertTrue(service.isShutdown()); try { service.execute(command); Assert.fail("Command should not have been executed."); } catch (RejectedExecutionException e) { Assert.assertTrue(true); } }
### Question: InlineExecutorService extends AbstractExecutorService { @Override public List<Runnable> shutdownNow() { shutdown(); myLock.lock(); try { for (Thread thread : myThreads) { thread.interrupt(); } } finally { myLock.unlock(); } return Collections.emptyList(); } InlineExecutorService(); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override final void execute(Runnable command); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override void shutdown(); @Override List<Runnable> shutdownNow(); }### Answer: @Test public void testShutdownNow() throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(2); final CountDownLatch latch = new CountDownLatch(2); final AtomicBoolean flag1 = new AtomicBoolean(); final AtomicBoolean flag2 = new AtomicBoolean(); final ExecutorService service = new InlineExecutorService(); pool.execute(new TestRunnable(service, latch, flag1, 5000L)); pool.execute(new TestRunnable(service, latch, flag2, 5000L)); latch.await(); Assert.assertFalse(service.isShutdown()); service.shutdownNow(); Assert.assertTrue(service.isShutdown()); Assert.assertTrue(service.awaitTermination(1000L, TimeUnit.MILLISECONDS)); Assert.assertTrue(flag1.get()); Assert.assertTrue(flag2.get()); }
### Question: SequentialExecutor implements Executor { @Override public void execute(Runnable command) { boolean needExecute; synchronized (myWorkQueue) { myWorkQueue.add(command); if (myPending) { needExecute = false; } else { needExecute = true; myPending = true; } } if (needExecute) { myExecutor.execute(myTask); } } SequentialExecutor(Executor executor); @Override void execute(Runnable command); }### Answer: @Test public void test() throws InterruptedException { if (StringUtils.isEmpty(System.getenv("SLOW_MACHINE"))) { final ExecutorService actualExecutor = Executors.newFixedThreadPool(5); SequentialExecutor executor = new SequentialExecutor(actualExecutor); int count = 100; TestRunnable[] arr = new TestRunnable[count]; for (int index = 0; index < count;) { arr[index++] = new TestRunnable(); } for (int index = 0; index < count;) { executor.execute(arr[index++]); } executor.execute(new Runnable() { @Override public void run() { actualExecutor.shutdown(); } }); actualExecutor.awaitTermination(1L, TimeUnit.SECONDS); for (int index = 1; index < count; ++index) { Assert.assertTrue("Runnable at index " + (index - 1) + " did not run", arr[index - 1].getRunStop() > 0L); Assert.assertTrue("Start time at index " + index + " [" + arr[index].getRunStart() + "] should have been >= stop time of index " + (index - 1) + " [" + arr[index - 1].getRunStop() + "]", arr[index].getRunStart() >= arr[index - 1].getRunStop()); } } }
### Question: InterruptingExecutor implements ScheduledExecutorService { @Override public void shutdown() { myShutdown = true; myOvertimeGuard.setCancelAfterNextRun(); if (myExecutor instanceof ExecutorService) { ((ExecutorService)myExecutor).shutdown(); } } InterruptingExecutor(Executor wrappedExecutor, long timeLimitMilliseconds); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override synchronized void execute(Runnable command); @Override List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks); @Override List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit); @Override T invokeAny(Collection<? extends Callable<T>> tasks); @Override T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit); @SuppressWarnings("cast") @Override ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit); @Override void shutdown(); @Override List<Runnable> shutdownNow(); @Override Future<T> submit(Callable<T> task); @SuppressWarnings("cast") @Override Future<?> submit(Runnable task); @Override Future<T> submit(Runnable task, T result); }### Answer: @Test public void testShutdown() { Executor wrappedExecutor = Executors.newFixedThreadPool(1); long timeLimitMilliseconds = 100000L; InterruptingExecutor exec = new InterruptingExecutor(wrappedExecutor, timeLimitMilliseconds); RunnableImplementation command = new RunnableImplementation(timeLimitMilliseconds, 0L); exec.execute(command); ThreadUtilities.sleep(50L); exec.shutdownNow(); ThreadUtilities.sleep(50L); Assert.assertEquals("Command should have been interrupted once.", 1, command.getInterruptedCount()); }