method2testcases
stringlengths
118
6.63k
### Question: NotEqualsCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) != 0) return true; } return false; } NotEqualsCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }### Answer: @Test public void testNotEquals() { Criteria eq = new NotEqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val2"); assertTrue(eq.test(entity.build())); } @Test public void testEquals() { Criteria eq = new NotEqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val1"); assertFalse(eq.test(entity.build())); }
### Question: Iterables2 { public static <T> Iterable<List<T>> groupBy(final Iterable<? extends T> iterable, final Function<? super T, ?> groupingFunction) { requireNonNull(iterable); requireNonNull(groupingFunction); return () -> Iterators2.groupBy(iterable.iterator(), groupingFunction); } private Iterables2(); static Iterable<T> simpleIterable(final Iterable<T> iterable); static Iterable<T> distinct(final Iterable<T> iterable); static Iterable<List<T>> groupBy(final Iterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); }### Answer: @Test public void groupByTest() { List<Integer> testdata = asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); Iterable<List<Integer>> grouped = groupBy(testdata, input -> input / 5); assertEquals(2, size(grouped)); assertEquals(asList(0, 1, 2, 3, 4), get(grouped, 0)); assertEquals(asList(5, 6, 7, 8, 9), get(grouped, 1)); grouped = groupBy(testdata, input -> null); assertEquals(1, size(grouped)); assertEquals(testdata, get(grouped, 0)); grouped = groupBy(testdata, input -> input); assertEquals(10, size(grouped)); for (int i = 0; i< testdata.size(); i++) { List<Integer> group = get(grouped, i); assertEquals(1, group.size()); assertEquals(new Integer(i), group.get(0)); } } @Test(expected = NullPointerException.class) public void groupByNullIteratorTest() { groupBy(null, input -> null); } @Test(expected = NullPointerException.class) public void groupByNullEquivTest() { groupBy(emptyList(), null); }
### Question: LessThanCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) < 0) return true; } return false; } LessThanCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }### Answer: @Test public void test() { LessThanCriteria criteria = new LessThanCriteria<>("key1", 5, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id"); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 10); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 4); assertTrue(criteria.test(entity.build())); }
### Question: HasNotCriteria extends TermCriteria { @Override public boolean test(AttributeStore obj) { if(obj.get(getTerm()) == null) return true; Collection<Attribute> attributes = obj.getAttributes(getTerm()); if(attributes.size() > 0 && clazz == null) return false; for(Attribute attribute : attributes) { if(attribute.getValue().getClass().equals(clazz)) return false; } return true; } HasNotCriteria(String term, Class<T> clazz, ParentCriteria parentCriteria); HasNotCriteria(String term, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }### Answer: @Test public void test() { HasNotCriteria criteria = new HasNotCriteria("key1", null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key2", "val2"); assertTrue(criteria.test(entity.build())); entity = entity.attr("key1", "val1"); assertFalse(criteria.test(entity.build())); }
### Question: RangeCriteria extends TermCriteria { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (comparator.compare((T)(attribute.getValue()), start) >= 0 && comparator.compare((T)(attribute.getValue()), end) <= 0) { return true; } } return false; } RangeCriteria(String term, T start, T end, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void test() { RangeCriteria criteria = new RangeCriteria<>("key1", 5, 10, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id"); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 11); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 4); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 5); assertTrue(criteria.test(entity.build())); entity = entity.attr("key1", 6); assertTrue(criteria.test(entity.build())); } @Test public void acceptAnyTupleWithinRange() { RangeCriteria criteria = new RangeCriteria<>("key1", 5, 10, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", 4) .attr("key1", 6); assertTrue(criteria.test(entity.build())); }
### Question: NodeUtils { public static Criteria criteriaFromNode(Node node) { return criteriaFromNode(node, naturalOrder(), null); } NodeUtils(); static boolean isLeaf(Node node); static boolean isEmpty(Node node); static boolean parentContainsOnlyLeaves(ParentNode parentNode); static boolean isRangeLeaf(Leaf leaf); static Criteria criteriaFromNode(Node node); static Criteria criteriaFromNode(Node node, Comparator rangeComparator); }### Answer: @Test public void testCriteriaFromNode_fullTree() { Node node = QueryBuilder.create().or().and().eq("key1", "val1").eq("key2", "val2").end().eq("key3", "val3").end().build(); Criteria criteria = NodeUtils.criteriaFromNode(node); assertTrue(criteria instanceof OrCriteria); assertTrue(criteria.children().get(0) instanceof AndCriteria); assertTrue(criteria.children().get(0).children().get(0) instanceof EqualsCriteria); assertTrue(criteria.children().get(0).children().get(1) instanceof EqualsCriteria); assertTrue(criteria.children().get(1).children().get(0) instanceof EqualsCriteria); }
### Question: AbstractCloseableIterable implements CloseableIterable<T> { @Override public void close() { if (!closed) { doClose(); closed = true; } } @Override void close(); @Override Iterator<T> iterator(); }### Answer: @SuppressWarnings({"rawtypes", "unchecked"}) @Test public void closeTest() throws Exception { MockIterable iterable = new MockIterable(emptyList()); iterable.close(); assertTrue(iterable.isClosed()); }
### Question: CloseableIterators { public static <F, T> CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function) { return wrap(Iterators.transform(iterator, function::apply), iterator); } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }### Answer: @Test public void testTransform() { CloseableIterator<Integer> addOne = transform(testIterator(), input -> input + 1); CloseableIterator<Integer> multTen = transform(addOne, input -> input * 10); assertTrue(elementsEqual(asList(20, 30, 40, 50, 60).iterator(), multTen)); assertFalse(multTen.hasNext()); multTen.close(); }
### Question: GlobalIndexExpirationFilter extends Filter { @Override public boolean accept(Key k, Value v) { long expiration = new GlobalIndexValue(v).getExpiration(); return !MetadataExpirationFilter.shouldExpire(expiration, k.getTimestamp()); } @Override boolean accept(Key k, Value v); }### Answer: @Test public void testExpiration() { GlobalIndexExpirationFilter expirationFilter = new GlobalIndexExpirationFilter(); Key key = new Key(); key.setTimestamp(System.currentTimeMillis() - 1000); assertTrue(expirationFilter.accept(key, new GlobalIndexValue(1, 100000).toValue())); assertFalse(expirationFilter.accept(key, new GlobalIndexValue(1, 1).toValue())); assertTrue(expirationFilter.accept(key, new GlobalIndexValue(1, -1).toValue())); assertTrue(expirationFilter.accept(key, new Value("1".getBytes()))); }
### Question: NodeToJexl { public String transform(Set<String> types, Node node) { StringBuilder builder = new StringBuilder(); Iterator<String> typesItr = types.iterator(); while(typesItr.hasNext()) { builder.append(runTransform(typesItr.next(), node)); if(typesItr.hasNext()) builder.append(" or "); } return builder.toString(); } NodeToJexl(TypeRegistry<String> registry); static String removeInvalidChars(String key); static String revertToOriginalkey(String fixedString); String transform(Set<String> types, Node node); static char[] badChars; static String[] strings; static String[] chars; static final String JEXL_NORM_PREFIX; }### Answer: @Test public void testHas() { String jexl = nodeToJexl.transform(singleton(""), create().has("hello").build()); assertEquals("((hello >= '\u0000'))", jexl); } @Test public void testHasNot() { String jexl = nodeToJexl.transform(singleton(""), create().hasNot("hello").build()); assertEquals("(!(hello >= '\u0000'))", jexl); } @Test public void testIn() { String jexl = nodeToJexl.transform(singleton(""), create().in("key", "hello", "goodbye").build()); assertEquals("((key == 'string\u0001hello' or key == 'string\u0001goodbye'))", jexl); } @Test public void testNotIn() { String jexl = nodeToJexl.transform(singleton(""), create().notIn("key", "hello", "goodbye").build()); assertEquals("((key != 'string\u0001hello' and key != 'string\u0001goodbye'))", jexl); } @Test public void testSimpleEquals_AndNode() { String jexl = nodeToJexl.transform(singleton(""), create().and().eq("hello", "goodbye").eq("key1", true).end().build()); assertEquals("((hello == 'string\u0001goodbye') and (key1 == 'boolean\u00011'))", jexl); } @Test public void testSimpleEquals_OrNode() { String jexl = nodeToJexl.transform(singleton(""), create().or().eq("hello", "goodbye").eq("key1", true).end().build()); assertEquals("((hello == 'string\u0001goodbye') or (key1 == 'boolean\u00011'))", jexl); } @Test public void testGreaterThan() { String jexl = nodeToJexl.transform(singleton(""), create().greaterThan("hello", "goodbye").build()); assertEquals("((hello > 'string\u0001goodbye'))", jexl); } @Test public void testLessThan() { String jexl = nodeToJexl.transform(singleton(""), create().lessThan("hello", "goodbye").build()); assertEquals("((hello < 'string\u0001goodbye'))", jexl); } @Test public void testGreaterThanEquals() { String jexl = nodeToJexl.transform(singleton(""), create().greaterThanEq("hello", "goodbye").build()); assertEquals("((hello >= 'string\u0001goodbye'))", jexl); } @Test public void testLessThanEquals() { String jexl = nodeToJexl.transform(singleton(""), create().lessThanEq("hello", "goodbye").build()); assertEquals("((hello <= 'string\u0001goodbye'))", jexl); } @Test public void testNotEquals() { String jexl = nodeToJexl.transform(singleton(""), create().notEq("hello", "goodbye").build()); assertEquals("((hello != 'string\u0001goodbye'))", jexl); }
### Question: EventWritable implements Writable, Settable<Event>, Gettable<Event> { public Event get() { return entry; } EventWritable(); EventWritable(Event entry); void setAttributeWritable(AttributeWritable sharedAttributeWritable); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); void set(Event entry); Event get(); }### Answer: @Test public void testSerializesAndDeserializes() throws IOException { Event event = EventBuilder.create("", "id", System.currentTimeMillis()) .attr(new Attribute("key", "val", ImmutableMap.of("metaKey", "metaVal"))).build(); byte[] serialized = serialize(new EventWritable(event)); Event actual = asWritable(serialized, EventWritable.class).get(); assertEquals(event, actual); }
### Question: AttributeWritable implements Writable, Gettable<Attribute>, Settable<Attribute> { @Override public Attribute get() { return attribute; } AttributeWritable(); AttributeWritable(Attribute attribute); void setTypeRegistry(TypeRegistry<String> registry); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); @Override Attribute get(); @Override void set(Attribute item); }### Answer: @Test public void testSerializesAndDeserializes() throws IOException { Attribute attribute = new Attribute("key", "val", ImmutableMap.of("metaKey", "metaVal")); byte[] serialized = serialize(new AttributeWritable(attribute)); Attribute actual = asWritable(serialized, AttributeWritable.class).get(); assertEquals(attribute, actual); }
### Question: GlobalIndexCombiner extends Combiner { @Override public Value reduce(Key key, Iterator<Value> valueIterator) { long cardinality = 0; long expiration = 0; while(valueIterator.hasNext()) { GlobalIndexValue value = new GlobalIndexValue(valueIterator.next()); cardinality += value.getCardinatlity(); if(value.getExpiration() == -1) expiration = -1; if(expiration != -1) expiration = Math.max(expiration, value.getExpiration()); } return new GlobalIndexValue(cardinality, expiration).toValue(); } @Override Value reduce(Key key, Iterator<Value> valueIterator); }### Answer: @Test public void testWithExpiration() { GlobalIndexCombiner combiner = new GlobalIndexCombiner(); Collection<Value> values = new ArrayList<Value>(); GlobalIndexValue value = new GlobalIndexValue(1, 2); GlobalIndexValue value2 = new GlobalIndexValue(1, 2); GlobalIndexValue value3 = new GlobalIndexValue(1, 50); GlobalIndexValue value4 = new GlobalIndexValue(1, 2); GlobalIndexValue value5 = new GlobalIndexValue(1, 2); values.add(value.toValue()); values.add(value2.toValue()); values.add(value3.toValue()); values.add(value4.toValue()); values.add(value5.toValue()); Value actualVal = combiner.reduce(new Key(), values.iterator()); GlobalIndexValue actualGiv = new GlobalIndexValue(actualVal); assertEquals(5, actualGiv.getCardinatlity()); assertEquals(50, actualGiv.getExpiration()); } @Test public void testWithNoExpiration() { GlobalIndexCombiner combiner = new GlobalIndexCombiner(); Collection<Value> values = new ArrayList<Value>(); GlobalIndexValue value = new GlobalIndexValue(1, 2); GlobalIndexValue value2 = new GlobalIndexValue(1, 2); GlobalIndexValue value3 = new GlobalIndexValue(1, -1); GlobalIndexValue value4 = new GlobalIndexValue(1, 2); GlobalIndexValue value5 = new GlobalIndexValue(1, 2); values.add(value.toValue()); values.add(value2.toValue()); values.add(value3.toValue()); values.add(value4.toValue()); values.add(value5.toValue()); Value actualVal = combiner.reduce(new Key(), values.iterator()); GlobalIndexValue actualGiv = new GlobalIndexValue(actualVal); assertEquals(5, actualGiv.getCardinatlity()); assertEquals(-1, actualGiv.getExpiration()); }
### Question: RangeSplitterVisitor implements NodeVisitor { @Override public void end(ParentNode parentNode) { } @Override void begin(ParentNode parentNode); @Override void end(ParentNode parentNode); @Override void visit(Leaf leaf); }### Answer: @Test public void test() { Node query = QueryBuilder.create().and().eq("key1", "val1").range("key2", 0, 5).end().build(); query.accept(new RangeSplitterVisitor()); assertTrue(query instanceof AndNode); assertEquals(3, query.children().size()); assertTrue(query.children().get(0) instanceof EqualsLeaf); assertTrue(query.children().get(1) instanceof GreaterThanEqualsLeaf); assertTrue(query.children().get(2) instanceof LessThanEqualsLeaf); query = QueryBuilder.create().or().eq("key1", "val1").range("key2", 0, 5).end().build(); query.accept(new RangeSplitterVisitor()); assertTrue(query instanceof OrNode); assertEquals(2, query.children().size()); assertTrue(query.children().get(0) instanceof EqualsLeaf); assertTrue(query.children().get(1) instanceof AndNode); assertTrue(query.children().get(1).children().get(0) instanceof GreaterThanEqualsLeaf); assertTrue(query.children().get(1).children().get(1) instanceof LessThanEqualsLeaf); }
### Question: ExtractInNotInVisitor implements NodeVisitor { @Override public void end(ParentNode parentNode) { } @Override void begin(ParentNode parentNode); @Override void end(ParentNode parentNode); @Override void visit(Leaf leaf); }### Answer: @Test public void testIn() { Node query = QueryBuilder.create().in("key", "hello", "goodbye").build(); Node expected = QueryBuilder.create().and().or().eq("key", "hello").eq("key", "goodbye").end().end().build(); query.accept(new ExtractInNotInVisitor()); assertEquals(expected, query); }
### Question: EntityWritable implements WritableComparable, Settable<Entity>, Gettable<Entity> { public Entity get() { return entity; } EntityWritable(); EntityWritable(Entity entity); void setAttributeWritable(AttributeWritable sharedAttributeWritable); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); void set(Entity entity); Entity get(); @Override int compareTo(Object o); }### Answer: @Test public void testSerializesAndDeserializes() throws IOException { Entity entity = EntityBuilder.create("type", "id") .attr(new Attribute("key", "val", ImmutableMap.of("metaKey", "metaVal"))) .build(); byte[] serialized = serialize(new EntityWritable(entity)); Entity actual = asWritable(serialized, EntityWritable.class).get(); assertEquals(entity, actual); }
### Question: Metric implements Writable { public double getVariance() { BigDecimal sumSquare = new BigDecimal(this.sumSquare); if(count < 2) return 0; BigDecimal sumSquareDivideByCount = sumSquare.divide(valueOf(count), 15, FLOOR); return (sumSquareDivideByCount.subtract(new BigDecimal(getMean() * getMean()))).doubleValue(); } Metric(); Metric(long value); Metric(long min, long max, long sum, long count, BigInteger sumSquare); long getMin(); long getMax(); long getSum(); long getCount(); BigInteger getSumSquare(); double getMean(); double getVariance(); double getStdDev(); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testVariance() { Metric metric = new Metric(1); assertEquals(0.0, metric.getVariance()); metric = new Metric(1, 1, 1, 5, BigInteger.valueOf(1)); assertEquals(0.16, metric.getVariance()); metric = new Metric(1, 1, 5, 5, BigInteger.valueOf(5)); assertEquals(0.0, metric.getVariance()); }
### Question: FeatureRegistry { public AccumuloFeatureConfig transformForClass(Class<? extends Feature> clazz) { AccumuloFeatureConfig featureConfig = classToTransform.get(clazz); if(featureConfig == null) { for(Map.Entry<Class, AccumuloFeatureConfig> clazzes : classToTransform.entrySet()) { if(clazzes.getKey().isAssignableFrom(clazz)) { featureConfig = clazzes.getValue(); classToTransform.put(clazz, featureConfig); } } } return featureConfig; } FeatureRegistry(AccumuloFeatureConfig... transforms); AccumuloFeatureConfig transformForClass(Class<? extends Feature> clazz); Iterable<AccumuloFeatureConfig> getConfigs(); static final FeatureRegistry BASE_FEATURES; }### Answer: @Test public void testMyTestFeatureReturns() { FeatureRegistry registry = new FeatureRegistry(new MetricFeatureConfig()); assertNotNull(registry.transformForClass(MyTestFeature.class)); }
### Question: MetricFeatureConfig implements AccumuloFeatureConfig<MetricFeature> { @Override public MetricFeature buildFeatureFromValue(long timestamp, String group, String type, String name, String visibility, Value value) { Metric metricFeatureVector = valueToVector.apply(value); return new MetricFeature(timestamp, group, type, name, visibility, metricFeatureVector); } @Override Class<MetricFeature> transforms(); @Override Value buildValue(MetricFeature feature); @Override MetricFeature buildFeatureFromValue(long timestamp, String group, String type, String name, String visibility, Value value); @Override String featureName(); @Override List<IteratorSetting> buildIterators(int priority); static final Function<Value, Metric> valueToVector; static final Function<Metric, Value> vectorToValue; }### Answer: @Test public void testBuildFeatureFromValue() { Value value = new Value("1,2,3,4,5".getBytes()); long timestamp = currentTimeMillis(); String group = "group"; String type = "type"; String name = "name"; String vis = "vis"; MetricFeature feature = new MetricFeatureConfig().buildFeatureFromValue( timestamp, group, type, name, vis, value ); assertEquals(group, feature.getGroup()); assertEquals(timestamp, feature.getTimestamp()); assertEquals(type, feature.getType()); assertEquals(name, feature.getName()); assertEquals(vis, feature.getVisibility()); assertEquals(1, feature.getVector().getMin()); assertEquals(2, feature.getVector().getMax()); assertEquals(3, feature.getVector().getSum()); assertEquals(4, feature.getVector().getCount()); assertEquals(BigInteger.valueOf(5), feature.getVector().getSumSquare()); }
### Question: MetricFeatureConfig implements AccumuloFeatureConfig<MetricFeature> { @Override public Value buildValue(MetricFeature feature) { return vectorToValue.apply(feature.getVector()); } @Override Class<MetricFeature> transforms(); @Override Value buildValue(MetricFeature feature); @Override MetricFeature buildFeatureFromValue(long timestamp, String group, String type, String name, String visibility, Value value); @Override String featureName(); @Override List<IteratorSetting> buildIterators(int priority); static final Function<Value, Metric> valueToVector; static final Function<Metric, Value> vectorToValue; }### Answer: @Test public void testBuildValueFromFeature() { long currentTime = currentTimeMillis(); MetricFeature feature = new MetricFeature(currentTimeMillis(), "group", "type", "name", "vis", new Metric(1)); Value value = new MetricFeatureConfig().buildValue(feature); assertEquals("1,1,1,1,1", new String(value.get())); }
### Question: AccumuloChangelogStore implements ChangelogStore { @Override public void put(Iterable<Event> changes) { EventWritable shared = new EventWritable(); checkNotNull(changes); try { for (Event change : changes) { shared.set(change); Mutation m = new Mutation(Long.toString(truncatedReverseTimestamp(change.getTimestamp(), bucketSize))); try { Text reverseTimestamp = new Text(Long.toString(reverseTimestamp(change.getTimestamp()))); m.put(reverseTimestamp, new Text(change.getType() + NULL_BYTE + change.getId()), change.getTimestamp(), new Value(serialize(shared))); writer.addMutation(m); } catch (Exception e) { throw new RuntimeException(e); } } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } AccumuloChangelogStore(Connector connector); AccumuloChangelogStore(Connector connector, String tableName, StoreConfig config); AccumuloChangelogStore(Connector connector, BucketSize bucketSize); AccumuloChangelogStore(Connector connector, String tableName, StoreConfig config, BucketSize bucketSize); @Override void put(Iterable<Event> changes); @Override void flush(); @Override MerkleTree getChangeTree(Date start, Date stop, Auths auths); @Override MerkleTree getChangeTree(Date start, Date stop, int dimensions, Auths auths); @Override CloseableIterable<Event> getChanges(Iterable<Date> buckets, Auths auths); }### Answer: @Test public void singleChange() throws Exception { long currentTime = currentTimeMillis(); MerkleTree sourceTree = buildTree(); Event entry = createStoreEntry("1", currentTime); store.put(asList(entry)); MerkleTree targetTree = buildTree(); assertEquals(sourceTree.getNumLeaves(), targetTree.getNumLeaves()); assertEquals(sourceTree.getDimensions(), targetTree.getDimensions()); List<BucketHashLeaf> diffLeaves = targetTree.diff(sourceTree); assertEquals(1, diffLeaves.size()); long expectedBucket = currentTime - (currentTime % BucketSize.FIVE_MINS.getMs()); assertEquals(expectedBucket, diffLeaves.get(0).getTimestamp()); } @Test public void multipleChanges() throws Exception { long currentTime = currentTimeMillis(); MerkleTree sourceTree = buildTree(); Event entry = createStoreEntry("1", currentTime); Event entry2 = createStoreEntry("2", currentTime - 900000); Event entry3 = createStoreEntry("3", currentTime - 50000000); Event entry4 = createStoreEntry("4", currentTime); Event entry5 = createStoreEntry("5", currentTime + 5000000); store.put(asList(entry, entry2, entry3, entry4, entry5)); MerkleTree targetTree = buildTree(); assertEquals(sourceTree.getNumLeaves(), targetTree.getNumLeaves()); assertEquals(sourceTree.getDimensions(), targetTree.getDimensions()); List<BucketHashLeaf> diffLeaves = targetTree.diff(sourceTree); assertEquals(4, diffLeaves.size()); long expectedTime1 = (currentTime + 5000000) - ((currentTime + 5000000) % BucketSize.FIVE_MINS.getMs()); assertEquals(expectedTime1, diffLeaves.get(0).getTimestamp()); long expectedTime2 = (currentTime) - ((currentTime) % BucketSize.FIVE_MINS.getMs()); assertEquals(expectedTime2, diffLeaves.get(1).getTimestamp()); long expectedTime3 = (currentTime - 900000) - ((currentTime - 900000) % BucketSize.FIVE_MINS.getMs()); assertEquals(expectedTime3, diffLeaves.get(2).getTimestamp()); long expectedTime4 = (currentTime - 50000000) - ((currentTime - 50000000) % BucketSize.FIVE_MINS.getMs()); assertEquals(expectedTime4, diffLeaves.get(3).getTimestamp()); }
### Question: MerkleTree implements Serializable { public Node getTopHash() { return topHash; } MerkleTree(List<T> leaves); MerkleTree(List<T> leaves, int dimensions); Node getTopHash(); Integer getDimensions(); Integer getNumLeaves(); @SuppressWarnings("rawtypes") List<T> diff(MerkleTree other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testTreeBuilds() throws NoSuchAlgorithmException, IOException, ClassNotFoundException { List<MockLeaf> leaves = asList(leaf1, leaf2, leaf8, leaf7, leaf4); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); assertEquals("17a19db32d969668fb08f9a5491eb4fe", tree.getTopHash().getHash()); assertEquals(2, tree.getTopHash().getChildren().size()); }
### Question: MerkleTree implements Serializable { @SuppressWarnings("rawtypes") public List<T> diff(MerkleTree other) { if (dimensions != other.dimensions || numLeaves != other.numLeaves) { throw new IllegalStateException("Trees need to have the same size & dimension to diff."); } List<T> differences = new ArrayList<>(); if (!other.getTopHash().getHash().equals(getTopHash().getHash())) { List<Node> nodes1 = topHash.getChildren(); List<Node> nodes2 = other.getTopHash().getChildren(); if (nodes1 == null) { return differences; } else if (nodes2 == null) { differences.addAll(getLeaves(nodes1)); } else { for (int i = 0; i < nodes1.size(); i++) { if (i < nodes1.size() && nodes2.size() == i) { differences.addAll(getLeaves(nodes1.get(i).getChildren())); } else { differences.addAll(diff(nodes1.get(i), nodes2.get(i))); } } } } return differences; } MerkleTree(List<T> leaves); MerkleTree(List<T> leaves, int dimensions); Node getTopHash(); Integer getDimensions(); Integer getNumLeaves(); @SuppressWarnings("rawtypes") List<T> diff(MerkleTree other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testDiff_differentDimensionsFails() { List<MockLeaf> leaves = asList(leaf1, leaf2); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves, 4); try { tree.diff(tree2); fail("Should have thrown exception"); } catch (IllegalStateException ignored) { } } @Test public void testDiff_differentSizesFails() { List<MockLeaf> leaves = asList(leaf1, leaf2); List<MockLeaf> leaves2 = asList(leaf1, leaf2, leaf3); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves2, 2); try { tree.diff(tree2); fail("Should have thrown exception"); } catch (IllegalStateException ignored) { } } @Test public void testDiff() { List<MockLeaf> leaves = asList(leaf1, leaf2); List<MockLeaf> leaves2 = asList(leaf1, leaf3); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves2, 2); List<MockLeaf> diffs = tree.diff(tree2); assertEquals(leaf2, diffs.get(0)); assertEquals(1, diffs.size()); diffs = tree2.diff(tree); assertEquals(leaf3, diffs.get(0)); assertEquals(1, diffs.size()); }
### Question: MerkleTree implements Serializable { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MerkleTree<?> that = (MerkleTree<?>) o; return dimensions == that.dimensions && numLeaves == that.numLeaves && Objects.equals(topHash, that.topHash); } MerkleTree(List<T> leaves); MerkleTree(List<T> leaves, int dimensions); Node getTopHash(); Integer getDimensions(); Integer getNumLeaves(); @SuppressWarnings("rawtypes") List<T> diff(MerkleTree other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testEquals_false() { List<MockLeaf> leaves = asList(leaf1, leaf2); List<MockLeaf> leaves2 = asList(leaf1, leaf3); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves2, 2); assertFalse(tree.equals(tree2)); assertFalse(tree2.equals(tree)); } @Test public void testEquals_true() { List<MockLeaf> leaves = asList(leaf1, leaf2); List<MockLeaf> leaves2 = asList(leaf1, leaf2); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves2, 2); assertTrue(tree.equals(tree2)); assertTrue(tree2.equals(tree)); }
### Question: CollectionSizeAdjuster { public void adjustSizeIfNeed(int requiredNumber) { if (requiredNumber < 0) { throw new ArrayIndexOutOfBoundsException("index out of bounds"); } if (requiredNumber > collection.size() - 1) { addUnits(requiredNumber); } } CollectionSizeAdjuster(Collection<T> collection, UnitFactory<T> unitFactory); void adjustSizeIfNeed(int requiredNumber); }### Answer: @Test public void adjustSizeIfNeed() throws Exception { for (int i = 0; i < 100; i++) { useAdjuster(i); } }
### Question: OffsetAnimator { protected float computeValueByOffset(float positionOffset) { positionOffset = computeByTimeShift(positionOffset); positionOffset = computeByInterpolator(positionOffset); return computeExactPosition(x1, x2, positionOffset); } protected OffsetAnimator(float x1, float x2); void animate(float positionOffset); void setParams(AnimatorParams params); OffsetAnimator setStartThreshold(float startThreshold); OffsetAnimator setDuration(float duration); OffsetAnimator setInterpolator(Interpolator interpolator); OffsetAnimator setListener(ValueListener valueListener); }### Answer: @Test public void getCurrentValue() throws Exception { OffsetAnimator offsetAnimator = new OffsetAnimator(0, 100); float[] positionOffsets = PositionGenerator.generatePositionOffsets(); final float[] expectedValues = new float[100]; for (int i = 1; i < 100; i++) { expectedValues[i] = i; } final float[] actualValues = new float[100]; for (int i = 0; i < positionOffsets.length; i++) { actualValues[i] = offsetAnimator.computeValueByOffset(positionOffsets[i]); } assertArrayEquals(expectedValues, actualValues, 0.00001f); }
### Question: ImagesPresenter implements ImagesContract.Presenter { @Override public void openImage(String path) { mView.showImage(path); } ImagesPresenter(ImagesRepository imagesRepository, ImagesContract.View imagesView); @Override void start(); @Override void openTakePhoto(); @Override void openImportPhoto(); @Override void openImage(String path); @Override void onImportImage(Bitmap image); @Override void onPhotoTaken(Bitmap image); @Override void setPictureTaker(PictureTaker pictureTaker); @Override void clearPictureTaker(); @Override void setImageImporter(ImageImporter imageImporter); @Override void clearImageImporter(); @Override void onPermissionRequestResult(boolean isGranted); }### Answer: @Test public void openImage() throws Exception { final String image = "1.png"; mPresenter.openImage(image); verify(mView).showImage(image); }
### Question: ImageViewerPresenter implements ImageViewerContract.Presenter { @Override public void showImage() { Bitmap bitmap = mImagesRepository.getImage(mImage); mView.displayImage(bitmap); } ImageViewerPresenter(@NonNull ImageViewerContract.View view, @NonNull ImagesRepository repository, @NonNull ImageSharer imageSharer, @NonNull String image); @Override void start(); @Override void showImage(); @Override void deleteImage(); @Override void shareImage(); }### Answer: @Test public void openImage() throws Exception { final String image = "1.png"; mPresenter.showImage(); verify(mView).displayImage(any(Bitmap.class)); }
### Question: ImageViewerPresenter implements ImageViewerContract.Presenter { @Override public void deleteImage() { mImagesRepository.deleteImage(mImage); mView.displayImageDeleted(); } ImageViewerPresenter(@NonNull ImageViewerContract.View view, @NonNull ImagesRepository repository, @NonNull ImageSharer imageSharer, @NonNull String image); @Override void start(); @Override void showImage(); @Override void deleteImage(); @Override void shareImage(); }### Answer: @Test public void deleteImage() throws Exception { mPresenter.deleteImage(); verify(mRepository).deleteImage(anyString()); }
### Question: ImageViewerPresenter implements ImageViewerContract.Presenter { @Override public void shareImage() { mImageSharer.shareImage(mImage); } ImageViewerPresenter(@NonNull ImageViewerContract.View view, @NonNull ImagesRepository repository, @NonNull ImageSharer imageSharer, @NonNull String image); @Override void start(); @Override void showImage(); @Override void deleteImage(); @Override void shareImage(); }### Answer: @Test public void shareImage() throws Exception { mPresenter.shareImage(); verify(mSharer).shareImage(anyString()); }
### Question: MainPresenter implements MainContract.Presenter { @Override public void loadPosts() { mView.setLoadingPosts(true); mData.getPosts(new DataSource.GetPostsCallback() { @Override public void onPostsLoaded(Post[] posts) { mView.setLoadingPosts(false); mView.hideError(); if (posts != null && posts.length > 0) { mView.showNoPostsMessage(false); mView.setPosts(posts); } else { mView.showNoPostsMessage(true); } } @Override public void onPostsNotAvailable(String error, Throwable cause) { String fullError = error; if (cause != null) { StringBuilder buffer = new StringBuilder(); buffer.append(error); buffer.append('\n'); buffer.append(cause.toString()); fullError = buffer.toString(); } mView.showError(error, fullError); mView.setLoadingPosts(false); mView.showNoPostsMessage(true); mView.setPosts(null); } }); } MainPresenter(DataSource mData, MainContract.View mView); @Override void start(); @Override void loadPosts(); @Override void onLoadPostImageError(String title, Exception e); }### Answer: @Test public void loadPostsSuccess() throws Exception { Post[] posts = new Post[]{ new Post("Annie", "Hello", null), new Post("Ann", "World", null), new Post("Droid", "Test", null) }; mPresenter.loadPosts(); verify(mData).getPosts(mGetPostsCallbackbackCaptor.capture()); verify(mView).setLoadingPosts(true); mGetPostsCallbackbackCaptor.getValue().onPostsLoaded(posts); verify(mView).setLoadingPosts(false); verify(mView).setPosts(posts); verify(mView).showNoPostsMessage(false); verify(mView).hideError(); } @Test public void loadPostsError() throws Exception { String errorText = "Error!"; mPresenter.loadPosts(); verify(mData).getPosts(mGetPostsCallbackbackCaptor.capture()); verify(mView).setLoadingPosts(true); mGetPostsCallbackbackCaptor.getValue().onPostsNotAvailable(errorText, null); verify(mView).setLoadingPosts(false); verify(mView).showError(anyString(), anyString()); verify(mView).showNoPostsMessage(true); verify(mView).setPosts(null); }
### Question: CardTemplate { private String updateImagesPath(String template) { return template.replaceAll(IMAGE_PATH_REGEX, IMAGE_PATH_REPLACEMENT); } CardTemplate(String frontTemplate, String rearTemplate, int ord); String getFrontTemplate(); String getRearTemplate(); int getOrd(); }### Answer: @Test public void updateImagesPathTest() throws Exception { String sampleText = "Che cos'è un latch SR?\n<hr id=answer>\n<div>Un circuito elettronico capace di memorizzare informazioni</div><img src=\"paste-9921374453761.jpg\" /> oppure <img src=\"paste-9921374453761.jpg\" />"; String expectedText = "Che cos'è un latch SR?\n<hr id=answer>\n<div>Un circuito elettronico capace di memorizzare informazioni</div><img src=\"anki-images/paste-9921374453761.jpg\" /> oppure <img src=\"anki-images/paste-9921374453761.jpg\" />"; String result = sampleText.replaceAll("(<img.+?src=\")([^\"]+)\"", "$1anki-images/$2\""); Assert.assertEquals(null, expectedText, result); String sample2 = "<img class=\"latex\" src=\"latex-6a3ac365210c170e4573d6f669410f5812e87aff.png\">"; String expected2 = "<img class=\"latex\" src=\"anki-images/latex-6a3ac365210c170e4573d6f669410f5812e87aff.png\">"; String result2 = sample2.replaceAll("(<img.+?src=\")([^\"]+)\"", "$1anki-images/$2\""); Assert.assertEquals(null, expected2, result2); }
### Question: DialogsDataSource extends SlingSafeMethodsServlet { @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { try { Resource resource = request.getResource(); ResourceResolver resolver = request.getResourceResolver(); ValueMap properties = resource.getValueMap(); String itemResourceType = properties.get("itemResourceType", String.class); String path = properties.get("path", String.class); if (StringUtils.isEmpty(path)) { log.warn("Path unavailable"); return; } path = expressionResolver.resolve(path, request.getLocale(), String.class, request); setDataSource(resource, path, resolver, request, itemResourceType); } catch (RepositoryException e) { log.warn("Unable to list classic dialogs", e.getMessage()); } } }### Answer: @Test public void testDoGet() throws Exception { List<String> expectedDialogPaths = new ArrayList<String>(); expectedDialogPaths.addAll(Arrays.asList( DIALOGS_ROOT + "/classic/dialog", DIALOGS_ROOT + "/classic/design_dialog", DIALOGS_ROOT + "/coral2/cq:dialog", DIALOGS_ROOT + "/coral2/cq:design_dialog", DIALOGS_ROOT + "/level1/classicandcoral2/cq:dialog", DIALOGS_ROOT + "/level1/classicandcoral2/cq:design_dialog", DIALOGS_ROOT + "/level1/converted/dialog", DIALOGS_ROOT + "/level1/converted/cq:design_dialog.coral2", DIALOGS_ROOT + "/level1/coral2andbackup/cq:dialog")); dialogsDataSource.doGet(request, response); ArgumentCaptor<DataSource> dataSourceArgumentCaptor = ArgumentCaptor.forClass(DataSource.class); Mockito.verify(request).setAttribute(Mockito.anyString(), dataSourceArgumentCaptor.capture()); DataSource dialogsDataSource = dataSourceArgumentCaptor.getValue(); @SuppressWarnings("unchecked") List<Resource> dialogsList = IteratorUtils.toList(dialogsDataSource.iterator()); assertEquals(expectedDialogPaths.size(), dialogsList.size()); for (Resource dialogResource : dialogsList) { ValueMap valueMap = dialogResource.getValueMap(); assertNotNull(valueMap.get("dialogPath")); assertNotNull(valueMap.get("type")); assertNotNull(valueMap.get("href")); assertNotNull(valueMap.get("converted")); assertNotNull(valueMap.get("crxHref")); expectedDialogPaths.remove(valueMap.get("dialogPath")); } assertEquals(0, expectedDialogPaths.size()); }
### Question: NodeBasedRewriteRule implements DialogRewriteRule { @Override public String toString() { String path = null; try { path = ruleNode.getPath(); } catch (RepositoryException e) { } return "NodeBasedRewriteRule[" + (path == null ? "" : "path=" +path + ",") + "ranking=" + getRanking() + "]"; } NodeBasedRewriteRule(Node ruleNode); boolean matches(Node root); Node applyTo(Node root, Set<Node> finalNodes); @Override String toString(); int getRanking(); }### Answer: @Test public void testToString() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/simple").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); String expected = "NodeBasedRewriteRule[path=" + RULES_PATH + "/simple,ranking=" + Integer.MAX_VALUE + "]"; assertEquals(expected, rule.toString()); }
### Question: DialogRewriteUtils { public static DialogType getDialogType(Node node) throws RepositoryException { DialogType type = DialogType.UNKNOWN; if (node == null) { return type; } String name = node.getName(); if (Arrays.asList(CLASSIC_DIALOG_NAMES).contains(name) && NT_DIALOG.equals(node.getPrimaryNodeType().getName())) { type = DialogType.CLASSIC; } else if (Arrays.asList(DIALOG_NAMES).contains(name) && node.hasNode("content")) { Node contentNode = node.getNode("content"); type = DialogType.CORAL_2; if (contentNode != null) { if (contentNode.hasProperty(ResourceResolver.PROPERTY_RESOURCE_TYPE)) { String resourceType = contentNode.getProperty(ResourceResolver.PROPERTY_RESOURCE_TYPE).getString(); type = resourceType.startsWith(DIALOG_CONTENT_RESOURCETYPE_PREFIX_CORAL3) ? DialogType.CORAL_3 : DialogType.CORAL_2; } } } return type; } static boolean hasXtype(Node node, String xtype); static boolean hasType(Node node, String type); static boolean hasPrimaryType(Node node, String typeName); static void rename(Node node); static Property copyProperty(Node source, String relPropertyPath, Node destination, String name); static DialogType getDialogType(Node node); static boolean isDesignDialog(Node node); static final String CORAL_2_BACKUP_SUFFIX; static final String NT_DIALOG; static final String NN_CQ_DIALOG; static final String NN_CQ_DESIGN_DIALOG; static final String DIALOG_CONTENT_RESOURCETYPE_PREFIX_CORAL3; }### Answer: @Test public void testGetDialogTypeClassic() throws Exception { boolean allClassic = false; String[] classicDialogPaths = { DIALOGS_ROOT + "/classic/dialog", DIALOGS_ROOT + "/classic/design_dialog" }; for (String path: classicDialogPaths) { Resource resource = context.resourceResolver().getResource(path); Node node = resource.adaptTo(Node.class); DialogType type = DialogRewriteUtils.getDialogType(node); allClassic = (type == DialogType.CLASSIC); if (!allClassic) { break; } } assertTrue(allClassic); } @Test public void testGetDialogTypeCoral2() throws Exception { boolean allCoral2 = false; String[] coral2DialogPaths = { DIALOGS_ROOT + "/coral2/cq:dialog", DIALOGS_ROOT + "/coral2/cq:design_dialog", DIALOGS_ROOT + "/backupsnoreplacementdiscarded/cq:dialog.coral2", DIALOGS_ROOT + "/backupsnoreplacementdiscarded/cq:design_dialog.coral2", DIALOGS_ROOT + "/level1/classicandcoral2/cq:dialog", DIALOGS_ROOT + "/level1/classicandcoral2/cq:design_dialog" }; for (String path: coral2DialogPaths) { Resource resource = context.resourceResolver().getResource(path); Node node = resource.adaptTo(Node.class); DialogType type = DialogRewriteUtils.getDialogType(node); allCoral2 = (type == DialogType.CORAL_2); if (!allCoral2) { break; } } assertTrue(allCoral2); } @Test public void testGetDialogTypeCoral3() throws Exception { boolean allCoral3 = false; String[] coral3DialogPaths = { DIALOGS_ROOT + "/level1/converted/cq:dialog", DIALOGS_ROOT + "/level1/converted/cq:design_dialog" }; for (String path: coral3DialogPaths) { Resource resource = context.resourceResolver().getResource(path); Node node = resource.adaptTo(Node.class); DialogType type = DialogRewriteUtils.getDialogType(node); allCoral3 = (type == DialogType.CORAL_3); if (!allCoral3) { break; } } assertTrue(allCoral3); }
### Question: NodeBasedRewriteRule implements DialogRewriteRule { public int getRanking() { if (ranking == null) { try { if (ruleNode.hasProperty(PROPERTY_RANKING)) { long ranking = ruleNode.getProperty(PROPERTY_RANKING).getLong(); this.ranking = new Long(ranking).intValue(); } else { this.ranking = Integer.MAX_VALUE; } } catch (RepositoryException e) { logger.warn("Caught exception while reading the " + PROPERTY_RANKING + " property"); } } return this.ranking; } NodeBasedRewriteRule(Node ruleNode); boolean matches(Node root); Node applyTo(Node root, Set<Node> finalNodes); @Override String toString(); int getRanking(); }### Answer: @Test public void testGetRanking() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/simple").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); assertEquals(Integer.MAX_VALUE, rule.getRanking()); }
### Question: DialogRewriteUtils { public static boolean isDesignDialog(Node node) throws RepositoryException { if (node == null) { return false; } String name = node.getName(); return name.equals(NameConstants.NN_DESIGN_DIALOG) || name.equals(NN_CQ_DESIGN_DIALOG) || name.equals(NN_CQ_DESIGN_DIALOG + CORAL_2_BACKUP_SUFFIX); } static boolean hasXtype(Node node, String xtype); static boolean hasType(Node node, String type); static boolean hasPrimaryType(Node node, String typeName); static void rename(Node node); static Property copyProperty(Node source, String relPropertyPath, Node destination, String name); static DialogType getDialogType(Node node); static boolean isDesignDialog(Node node); static final String CORAL_2_BACKUP_SUFFIX; static final String NT_DIALOG; static final String NN_CQ_DIALOG; static final String NN_CQ_DESIGN_DIALOG; static final String DIALOG_CONTENT_RESOURCETYPE_PREFIX_CORAL3; }### Answer: @Test public void testIsDesignDialog() throws Exception { boolean allDesignDialogs = false; String[] designDialogPaths = { DIALOGS_ROOT + "/classic/design_dialog", DIALOGS_ROOT + "/coral2/cq:design_dialog", DIALOGS_ROOT + "/backupsnoreplacementdiscarded/cq:design_dialog.coral2", DIALOGS_ROOT + "/level1/classicandcoral2/design_dialog", DIALOGS_ROOT + "/level1/classicandcoral2/cq:design_dialog" }; for (String path: designDialogPaths) { Resource resource = context.resourceResolver().getResource(path); Node node = resource.adaptTo(Node.class); allDesignDialogs = DialogRewriteUtils.isDesignDialog(node); if (!allDesignDialogs) { break; } } assertTrue(allDesignDialogs); }
### Question: DialogConversionServlet extends SlingAllMethodsServlet { private List<DialogRewriteRule> getRules(ResourceResolver resolver) throws ServletException { final List<DialogRewriteRule> rules = new LinkedList<DialogRewriteRule>(); synchronized (this.rules) { rules.addAll(this.rules); } int nb = rules.size(); Resource resource = resolver.getResource(RULES_SEARCH_PATH); if (resource != null) { try { Node rulesContainer = resource.adaptTo(Node.class); NodeIterator iterator = rulesContainer.getNodes(); while (iterator.hasNext()) { Node nextNode = iterator.nextNode(); if (isFolder(nextNode)) { NodeIterator nodeIterator = nextNode.getNodes(); while (nodeIterator.hasNext()) { Node nestedNode = nodeIterator.nextNode(); if (!isFolder(nestedNode)) { rules.add(new NodeBasedRewriteRule(nestedNode)); } } } else { rules.add(new NodeBasedRewriteRule(nextNode)); } } } catch (RepositoryException e) { throw new ServletException("Caught exception while collecting rewrite rules", e); } } Collections.sort(rules, new RuleComparator()); logger.debug("Found {} rules ({} Java-based, {} node-based)", nb, rules.size() - nb); for (DialogRewriteRule rule : rules) { logger.debug(rule.toString()); } return rules; } @SuppressWarnings("unused") void bindRule(DialogRewriteRule rule); @SuppressWarnings("unused") void unbindRule(DialogRewriteRule rule); static final String RULES_SEARCH_PATH; static final String PARAM_PATHS; }### Answer: @Test public void testGetRules() throws Exception { List<String> expectedRulePaths = new ArrayList<String>(); expectedRulePaths.addAll(Arrays.asList( RULES_PATH + "/rewriteRanking", RULES_PATH + "/simple", RULES_PATH + "/rewriteOptional", RULES_PATH + "/rewriteFinal", RULES_PATH + "/rewriteFinalOnReplacement", RULES_PATH + "/rewriteMapChildren", RULES_PATH + "/rewriteCommonAttrs", RULES_PATH + "/rewriteCommonAttrsData", RULES_PATH + "/rewriteRenderCondition", RULES_PATH + "/mapProperties", RULES_PATH + "/rewriteProperties", RULES_PATH + "/nested1/rule1", RULES_PATH + "/nested1/rule2", RULES_PATH + "/nested2/rule1")); Class[] cArgs = new Class[1]; cArgs[0] = ResourceResolver.class; Method method = dialogConversionServlet.getClass().getDeclaredMethod("getRules", cArgs); method.setAccessible(true); Object[] args = new Object[1]; args[0] = context.resourceResolver(); List<DialogRewriteRule> rules = (List<DialogRewriteRule>) method.invoke(dialogConversionServlet, args); assertEquals(expectedRulePaths.size(), rules.size()); int index = 0; for (DialogRewriteRule rule : rules) { String path = expectedRulePaths.get(index); assertTrue(rule.toString().contains("path=" + path + ",")); index++; } }
### Question: NodeBasedRewriteRule implements DialogRewriteRule { public boolean matches(Node root) throws RepositoryException { if (!ruleNode.hasNode("patterns")) { return false; } Node patterns = ruleNode.getNode("patterns"); if (!patterns.hasNodes()) { return false; } NodeIterator iterator = patterns.getNodes(); while (iterator.hasNext()) { Node pattern = iterator.nextNode(); if (matches(root, pattern)) { return true; } } return false; } NodeBasedRewriteRule(Node ruleNode); boolean matches(Node root); Node applyTo(Node root, Set<Node> finalNodes); @Override String toString(); int getRanking(); }### Answer: @Test public void testRewriteOptional() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/rewriteOptional").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); assertTrue(rule.matches(rootNode)); Node itemsNode = ruleNode.getNode("patterns/pattern/items"); itemsNode.getProperty("cq:rewriteOptional").remove(); rule = new NodeBasedRewriteRule(ruleNode); assertFalse(rule.matches(rootNode)); }
### Question: StringUtils { public static int tokenOverlap(String[] tokens1, String[] tokens2) { Set<String> tokenSet2 = new HashSet<String>(Arrays.asList(tokens2)); int score = 0; for (String word : tokens1) if (tokenSet2.contains(word)) score++; return score; } static int tokenOverlap(String[] tokens1, String[] tokens2); static int tokenOverlapExp(String[] tokens1, String[] tokens2); static int findOverlap(String[] tokens1, int i, String[] tokens2, int j); }### Answer: @Test public void testTokenOverlapDouble() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"bag", "dog", "was", "the", "blah", "bag"}; assertEquals(2, StringUtils.tokenOverlap(tokens1, tokens2)); } @Test public void testTokenOverlapSingle() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"chicken", "dog", "was", "the", "blah", "bag"}; assertEquals(2, StringUtils.tokenOverlap(tokens1, tokens2)); } @Test public void testTokenOverlapMixed() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"bag", "dog", "was", "cat", "blah", "bag"}; assertEquals(2, StringUtils.tokenOverlap(tokens1, tokens2)); }
### Question: StringPair implements Comparable, WritableComparable { public int compareTo(Object o) { return compareTo((StringPair) o); } StringPair(); StringPair(String x, String y); int compareTo(Object o); void write(DataOutput out); void readFields(DataInput in); int compareTo(StringPair w); boolean equals(Object o); int hashCode(); static StringPair fromString(String text); String toString(); public String x; public String y; }### Answer: @Test public void testCompareToFirstEqual() { StringPair pair1 = new StringPair("cat", "alpha"); StringPair pair2 = new StringPair("cat", "dog"); assertTrue(pair1.compareTo(pair2) < 0); } @Test public void testCompareToBothEqual() { StringPair pair1 = new StringPair("cat", "dog"); StringPair pair2 = new StringPair("cat", "dog"); assertTrue(pair1.compareTo(pair2) == 0); } @Test public void testCompareToFirstDiffer() { StringPair pair1 = new StringPair("cat", "alpha"); StringPair pair2 = new StringPair("cats", "dog"); assertTrue(pair1.compareTo(pair2) < 0); }
### Question: StringPair implements Comparable, WritableComparable { public boolean equals(Object o) { if (o == null || !(o instanceof StringPair)) return false; StringPair p = (StringPair)o; return (x == p.x || (x != null && x.equals(p.x))) && (y == p.y || (y != null && y.equals(p.y))); } StringPair(); StringPair(String x, String y); int compareTo(Object o); void write(DataOutput out); void readFields(DataInput in); int compareTo(StringPair w); boolean equals(Object o); int hashCode(); static StringPair fromString(String text); String toString(); public String x; public String y; }### Answer: @Test public void testEqualsNull() { StringPair pair1 = new StringPair(); StringPair pair2 = new StringPair(); assertTrue(pair1.equals(pair2)); } @Test public void testEqualsBothMatch() { StringPair pair1 = new StringPair("cat", "dog"); StringPair pair2 = new StringPair("cat", "dog"); assertTrue(pair1.equals(pair2)); } @Test public void testEqualsBothDiffer() { StringPair pair1 = new StringPair("cat", "dog"); StringPair pair2 = new StringPair("dog", "cat"); assertFalse(pair1.equals(pair2)); } @Test public void testEqualsFirstMatchSecondNull() { StringPair pair1 = new StringPair("cat", null); StringPair pair2 = new StringPair("cat", null); assertTrue(pair1.equals(pair2)); } @Test public void testEqualsFirstMatchSecondDiffer() { StringPair pair1 = new StringPair("cat", "cat"); StringPair pair2 = new StringPair("cat", "c"); assertFalse(pair1.equals(pair2)); } @Test public void testEqualsFirstNullSecondMatch() { StringPair pair1 = new StringPair(null, "cat"); StringPair pair2 = new StringPair(null, "cat"); assertTrue(pair1.equals(pair2)); } @Test public void testEqualsFirstNullSecondDiffer() { StringPair pair1 = new StringPair(null, "c"); StringPair pair2 = new StringPair(null, "cat"); assertFalse(pair1.equals(pair2)); }
### Question: StringPair implements Comparable, WritableComparable { public String toString() { return "{" + x.replaceAll(",", "&comma;") + ", " + y.replaceAll(",", "&comma;") + "}"; } StringPair(); StringPair(String x, String y); int compareTo(Object o); void write(DataOutput out); void readFields(DataInput in); int compareTo(StringPair w); boolean equals(Object o); int hashCode(); static StringPair fromString(String text); String toString(); public String x; public String y; }### Answer: @Test public void testToString() { StringPair pair = new StringPair("c,at", "dog,"); assertEquals("{c&comma;at, dog&comma;}", pair.toString()); }
### Question: StringPair implements Comparable, WritableComparable { public static StringPair fromString(String text) { text = text.trim(); text = text.substring(1, text.length() - 1); String[] parts = text.split(", ", 2); return new StringPair(parts[0].replaceAll("&comma;", ","), parts[1].replaceAll("&comma;", ",")); } StringPair(); StringPair(String x, String y); int compareTo(Object o); void write(DataOutput out); void readFields(DataInput in); int compareTo(StringPair w); boolean equals(Object o); int hashCode(); static StringPair fromString(String text); String toString(); public String x; public String y; }### Answer: @Test public void testFromString() { StringPair pair = StringPair.fromString( "{c&comma;at, dog&comma;}"); assertEquals("c,at", pair.x); assertEquals("dog,", pair.y); }
### Question: ExtendedList extends AbstractList<T> { public boolean add(T e) { return extendedItems.add(e); } ExtendedList(List<T> baseItems); boolean add(T e); T get(int index); int size(); }### Answer: @Test public void testAdd() { List<String> extendedList = new ExtendedList<String>(array1); for (String s : array2) assertTrue(extendedList.add(s)); assertEquals(3, array1.size()); } @Test public void testIterator() { List<String> extendedList = new ExtendedList<String>(array1); for (String s : array2) extendedList.add(s); Iterator<String> comboIter = extendedList.iterator(); Iterator<String> iter1 = array1.iterator(); Iterator<String> iter2 = array2.iterator(); while (iter1.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter1.next(), comboIter.next()); } while (iter2.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter2.next(), comboIter.next()); } }
### Question: ExtendedList extends AbstractList<T> { public int size() { return baseItems.size() + extendedItems.size(); } ExtendedList(List<T> baseItems); boolean add(T e); T get(int index); int size(); }### Answer: @Test public void testSize() { List<String> extendedList = new ExtendedList<String>(array1); assertEquals(array1.size(), extendedList.size()); int size = array1.size(); for (String s : array2) { extendedList.add(s); assertEquals(++size, extendedList.size()); } }
### Question: ExtendedList extends AbstractList<T> { public T get(int index) { return (index < baseItems.size()) ? baseItems.get(index) : extendedItems.get(index - baseItems.size()); } ExtendedList(List<T> baseItems); boolean add(T e); T get(int index); int size(); }### Answer: @Test public void testGet() { List<String> extendedList = new ExtendedList<String>(array1); for (int i = 0; i < array1.size(); ++i) assertEquals(array1.get(i), extendedList.get(i)); for (String s : array2) extendedList.add(s); for (int i = 0; i < array1.size(); ++i) assertEquals(array1.get(i), extendedList.get(i)); for (int i = 0; i < array2.size(); ++i) assertEquals(array2.get(i), extendedList.get(i + array1.size())); }
### Question: SenseEval2007DocumentReader implements DocumentReader { public Document readDocument(String doc) { return readDocument(doc, corpusName()); } String corpusName(); Document readDocument(String doc); Document readDocument(String doc, String corpusName); static final String CORPUS_NAME; }### Answer: @Test public void testReadDocument() { DocumentReader reader = new SenseEval2007DocumentReader(); Document doc = reader.readDocument(TEST_SENT); assertEquals("explain.v.4", doc.key()); assertEquals("explain", doc.title()); assertEquals(3, doc.id()); assertEquals(TEST_SENT, doc.originalText()); assertEquals("senseEval2007", doc.sourceCorpus()); assertTrue(doc.rawText().contains("explain ")); assertFalse(doc.rawText().contains("head")); }
### Question: SemEval2010TrainDocumentReader implements DocumentReader { public Document readDocument(String doc) { return readDocument(doc, corpusName()); } SemEval2010TrainDocumentReader(); String corpusName(); Document readDocument(String doc); Document readDocument(String doc, String corpusName); static final String CORPUS_NAME; }### Answer: @Test public void testRead() { DocumentReader reader = new SemEval2010TrainDocumentReader(); Document doc = reader.readDocument(TEST_SENT); assertEquals("class.n.4", doc.key()); assertFalse(doc.rawText().contains("class.n.4")); assertTrue(doc.rawText().contains("Ltd.")); assertEquals("semeval2010_train", doc.sourceCorpus()); }
### Question: UkWacDocumentReader implements DocumentReader { public gov.llnl.ontology.text.Document readDocument(String doc) { return readDocument(doc, corpusName()); } String corpusName(); gov.llnl.ontology.text.Document readDocument(String doc); gov.llnl.ontology.text.Document readDocument(String doc, String corpusName); static final String CORPUS_NAME; }### Answer: @Test public void testReader() { DocumentReader reader = new UkWacDocumentReader(); Document doc = reader.readDocument(INPUT); assertEquals("ukwac:http: assertEquals("ukwac:http: assertEquals(22, doc.rawText().split("\\s+").length); assertEquals(INPUT, doc.originalText()); assertEquals(UkWacDocumentReader.CORPUS_NAME, doc.sourceCorpus()); }
### Question: PubMedDocumentReader extends DefaultHandler implements DocumentReader { public Document readDocument(String originalText, String corpusName) { inAbstract = false; inTitle = false; inPMID = false; inTitle = false; labels.clear(); b.setLength(0); try { saxParser.parse(new InputSource(new StringReader(originalText)), this); } catch (SAXException se) { throw new RuntimeException(se); } catch (IOException ioe) { throw new IOError(ioe); } return new SimpleDocument(corpusName, docText, originalText, key, id, title, labels); } PubMedDocumentReader(); Document readDocument(String originalText, String corpusName); Document readDocument(String originalText); @Override void startElement(String uri, String localName, String name, Attributes atts); @Override void characters(char[] ch, int start, int length); @Override void endElement(String uri, String localName, String name); }### Answer: @Test public void readDocument() { DocumentReader reader = new PubMedDocumentReader(); Document doc = reader.readDocument(DOCUMENT_ONE); assertEquals("pubmed", doc.sourceCorpus()); assertEquals(12345, doc.id()); assertEquals("12345", doc.key()); assertEquals("CHICKEN", doc.title()); assertEquals("And once there was a chicken.", doc.rawText()); assertEquals(DOCUMENT_ONE, doc.originalText()); assertEquals(2, doc.categories().size()); assertTrue(doc.categories().contains("Anit-Chicken Agents")); assertTrue(doc.categories().contains("Non-geese")); doc = reader.readDocument(DOCUMENT_TWO); assertEquals("pubmed", doc.sourceCorpus()); assertEquals(62345, doc.id()); assertEquals("62345", doc.key()); assertEquals("CHICKENS ATTACK", doc.title()); assertEquals("A flock of chickens have attacked new york.", doc.rawText()); assertEquals(DOCUMENT_TWO, doc.originalText()); assertEquals(2, doc.categories().size()); assertTrue(doc.categories().contains("Human-Chicken Resistance")); assertTrue(doc.categories().contains("Pro-Fowl")); }
### Question: TextUtil { public static String cleanTerm(String term) { term = term.toLowerCase().trim(); if (term.matches("[0-9\\-\\.:]+")) return "<NUM>"; if (term.startsWith("http:") || term.startsWith("ftp:")) return "<URL>"; while (term.length() > 0 && term.startsWith("-")) term = term.substring(1, term.length()); while (term.length() > 0 && term.endsWith("-")) term = term.substring(0, term.length()-1); term = term.replaceAll("\"", ""); term = term.replaceAll("\'", ""); term = term.replaceAll("\\[", ""); term = term.replaceAll("\\]", ""); term = term.replaceAll("\\?", ""); term = term.replaceAll("\\*", ""); term = term.replaceAll("\\(", ""); term = term.replaceAll("\\)", ""); term = term.replaceAll("\\^", ""); term = term.replaceAll("\\+", ""); term = term.replaceAll(" term = term.replaceAll(";", ""); term = term.replaceAll("%", ""); term = term.replaceAll(",", ""); term = term.replaceAll("!", ""); return term.trim(); } static String cleanTerm(String term); }### Answer: @Test public void testNumClean() { String[] numbers = { "1900", ":123", "1-2", "1.2", "10000:", "125121", ".123", "123.", }; for (String number : numbers) assertEquals("<NUM>", TextUtil.cleanTerm(number)); }
### Question: Sentence implements Serializable, Iterable<Annotation> { public String sentenceText() { return (text == null) ? null : text.substring(start, end); } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText, String tokenText); static StringPair writeSentences(List<Sentence> sentences); }### Answer: @Test public void testSentenceText() { Sentence sent = new Sentence(2, 10, 8); String text = "abcdefghijlkmop"; sent.setText(text); assertEquals(text.substring(2, 10), sent.sentenceText()); }
### Question: Sentence implements Serializable, Iterable<Annotation> { public Annotation getAnnotation(int index) { return tokenAnnotations[index]; } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText, String tokenText); static StringPair writeSentences(List<Sentence> sentences); }### Answer: @Test public void testEmptyGet() { Sentence sent = new Sentence(0, 100, 1); assertEquals(null, sent.getAnnotation(0)); } @Test (expected=IndexOutOfBoundsException.class) public void testNegativeGet() { Sentence sent = new Sentence(0, 100, 1); sent.getAnnotation(-1); } @Test (expected=IndexOutOfBoundsException.class) public void testTooLargeGet() { Sentence sent = new Sentence(0, 100, 1); sent.getAnnotation(1); }
### Question: Sentence implements Serializable, Iterable<Annotation> { public void addAnnotation(int index, Annotation annotation) { tokenAnnotations[index] = annotation; } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText, String tokenText); static StringPair writeSentences(List<Sentence> sentences); }### Answer: @Test (expected=IndexOutOfBoundsException.class) public void testNegativeSet() { Sentence sent = new Sentence(0, 100, 1); Annotation annot = new SimpleAnnotation("blah"); sent.addAnnotation(-1, annot); } @Test (expected=IndexOutOfBoundsException.class) public void testTooLargeSet() { Sentence sent = new Sentence(0, 100, 1); Annotation annot = new SimpleAnnotation("blah"); sent.addAnnotation(1, annot); }
### Question: Sentence implements Serializable, Iterable<Annotation> { public DependencyTreeNode[] dependencyParseTree() { if (tokenAnnotations.length == 0 || !tokenAnnotations[0].hasDependencyParent()) return new DependencyTreeNode[0]; SimpleDependencyTreeNode[] nodes = new SimpleDependencyTreeNode[tokenAnnotations.length]; for (int i = 0; i < nodes.length; ++i) nodes[i] = new SimpleDependencyTreeNode( tokenAnnotations[i].word(), tokenAnnotations[i].pos(), i); for (int i = 0; i < nodes.length; ++i) { int parent = tokenAnnotations[i].dependencyParent(); String relation = tokenAnnotations[i].dependencyRelation(); if (parent == 0) continue; DependencyRelation r = new SimpleDependencyRelation( nodes[parent-1], relation, nodes[i]); nodes[i].addNeighbor(r); nodes[parent-1].addNeighbor(r); } return nodes; } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText, String tokenText); static StringPair writeSentences(List<Sentence> sentences); }### Answer: @Test public void testDependencyParseTree() { Sentence sentence = new Sentence(0, 100, 7); for (int i = 0; i < TEST_PARSED_SENTENCES.length; ++i) sentence.addAnnotation( i, annotationFromCoNLL(TEST_PARSED_SENTENCES[i])); DependencyTreeNode[] tree = sentence.dependencyParseTree(); assertEquals(TEST_PARSED_SENTENCES.length, tree.length); for (int i = 0; i < TEST_PARSED_SENTENCES.length; ++i) { assertEquals(TEST_PARSED_SENTENCES[i][0], tree[i].word()); assertEquals(TEST_PARSED_SENTENCES[i][1], tree[i].pos()); } assertEquals(1, tree[0].neighbors().size()); DependencyRelation relation = tree[0].neighbors().get(0); assertEquals("When", relation.dependentNode().word()); assertEquals("advmod", relation.relation()); assertEquals("released", relation.headNode().word()); assertEquals(2, tree[1].neighbors().size()); relation = tree[1].neighbors().get(0); assertEquals("When", relation.dependentNode().word()); assertEquals("advmod", relation.relation()); assertEquals("released", relation.headNode().word()); }
### Question: Sentence implements Serializable, Iterable<Annotation> { public StringPair[] taggedTokens() { StringPair[] taggedTokens = new StringPair[tokenAnnotations.length]; for (int i = 0; i < taggedTokens.length; ++i) taggedTokens[i] = new StringPair( tokenAnnotations[i].word(), tokenAnnotations[i].pos()); return taggedTokens; } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText, String tokenText); static StringPair writeSentences(List<Sentence> sentences); }### Answer: @Test public void testTaggedTokens() { Sentence sentence = makeSentence(0, 4, TOKEN_INFO, RANGES); StringPair[] taggedPairs = sentence.taggedTokens(); assertEquals(TOKEN_INFO.length, taggedPairs.length); for (int i = 0; i < TOKEN_INFO.length; ++i) { assertEquals(TOKEN_INFO[i][0], taggedPairs[i].x); assertEquals(TOKEN_INFO[i][1], taggedPairs[i].y); } }
### Question: NetworkConfluency { public double computeInitialAgreement() { return computeKappaScore( info1.edges, info2.edges, numNodes); } NetworkConfluency(String matrixFile1, String matrixFile2, Format format); NetworkConfluency(SparseMatrix matrix1, SparseMatrix matrix2); double computeInitialAgreement(); double computeExtendedAgreement(); static void main(String[] args); static double computeKappaScore(Set<IntPair> edges1, Set<IntPair> edges2, int numNodes); static Matrix multiply(SparseMatrix a, SparseMatrix b); }### Answer: @Test public void testInitialAgreement() { double[][] v1 = new double[][] { {1, 1, 0, 0, 1, 0}, {0, 0, 1, 0, 1, 0}, {0, 1, 0, 0, 0, 1}, {0, 1, 1, 1, 0, 0}, {1, 0, 1, 0, 0, 1}, {1, 1, 0, 0, 1, 1}, }; double[][] v2 = new double[][] { {1, 0, 0, 0, 1, 0}, {0, 0, 0, 0, 1, 0}, {0, 1, 1, 0, 0, 1}, {0, 1, 1, 1, 1, 0}, {1, 0, 1, 1, 0, 1}, {1, 1, 0, 0, 1, 1}, }; int agreeMent = 0; int edges1 = 0; int notEdges1 = 0; int edges2 = 0; int notEdges2 = 0; double numEdges = v1.length * v1.length; for (int r = 0; r < v1.length; ++r) for (int c = 0; c < v1.length; ++c) { if (v1[r][c] == v2[r][c]) agreeMent++; if (v1[r][c] != 0d) edges1++; else notEdges1++; if (v2[r][c] != 0d) edges2++; else notEdges2++; } double p0 = 1/numEdges * agreeMent; double pe = 1/(numEdges*numEdges) * (edges1*edges2 + notEdges1*notEdges2); double expectedKappa = (p0 - pe) / (1 - pe); NetworkConfluency confluency = new NetworkConfluency( makeMatrix(v1), makeMatrix(v2)); assertEquals(expectedKappa, confluency.computeInitialAgreement(), .001); }
### Question: BaseSynset implements Synset { public PartsOfSpeech getPartOfSpeech() { return pos; } BaseSynset(String synsetName); BaseSynset(int offset, PartsOfSpeech pos); BaseSynset(PartsOfSpeech pos); void addMorphyMapping(String original, String lemma); int getSenseNumber(); void setSenseNumber(int senseNumber); String getName(); String getSenseKey(); String getSenseKey(String base); List<String> getSenseKeys(); void addSenseKey(String senseKey); String getDefinition(); PartsOfSpeech getPartOfSpeech(); List<Lemma> getLemmas(); List<String> getExamples(); RelatedForm getDerivationallyRelatedForm(Synset synset); Set<String> getKnownRelationTypes(); Collection<Synset> allRelations(); Set<Synset> getRelations(String relation); Set<Synset> getRelations(Relation relation); int getNumRelations(); List<List<Synset>> getParentPaths(); Set<Synset> getParents(); Set<Synset> getChildren(); int getId(); int[] getFrameIds(); int[] getLemmaIds(); void setFrameInfo(int[] frameIds, int[] lemmaIds); void setId(int newOffset); void setDefinition(String definition); void addLemma(Lemma lemma); void addExample(String example); void addDerivationallyRelatedForm(Synset related, RelatedForm form); boolean addRelation(Relation relation, Synset synset); boolean addRelation(String relation, Synset synset); boolean removeRelation(Relation relation, Synset synset); boolean removeRelation(String relation, Synset synset); String getGloss(); int getMaxDepth(); int getMinDepth(); void setAttribute(String attributeName, Attribute attribute); Attribute getAttribute(String attributeName); Set<String> attributeLabels(); void merge(Synset synset); String toString(); }### Answer: @Test public void testConstructor() { Synset synset = new BaseSynset(PartsOfSpeech.NOUN); assertEquals(PartsOfSpeech.NOUN, synset.getPartOfSpeech()); }
### Question: StringUtils { public static int tokenOverlapExp(String[] tokens1, String[] tokens2) { int index1 = 0; int index2 = 0; int score = 0; for (int i = 0; i < tokens1.length; ++i) for (int j = 0; j < tokens2.length; ++j) if (tokens1[i].equals(tokens2[j])) score += Math.pow(findOverlap(tokens1, i, tokens2, j), 2); return score; } static int tokenOverlap(String[] tokens1, String[] tokens2); static int tokenOverlapExp(String[] tokens1, String[] tokens2); static int findOverlap(String[] tokens1, int i, String[] tokens2, int j); }### Answer: @Test public void testTokenOverlapExpNoSequence() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"bag", "dog", "was", "cat", "blah", "bag"}; assertEquals(3, StringUtils.tokenOverlapExp(tokens1, tokens2)); } @Test public void testTokenOverlapExpBoundedSequence() { String[] tokens1 = {"the", "cat", "has", "chicken", "bag", "the"}; String[] tokens2 = {"the", "dog", "was", "blarg", "chicken", "bag"}; assertEquals(7, StringUtils.tokenOverlapExp(tokens1, tokens2)); }
### Question: BaseSynset implements Synset { public void merge(Synset synset) { if (pos != synset.getPartOfSpeech()) throw new IllegalArgumentException( "Cannot merge synsets with different parts of speech."); Set<Duple<String, Synset>> toRemove = new HashSet<Duple<String, Synset>>(); for (String relation : getKnownRelationTypes()) { Set<Synset> links = relations.get(relation); if (links.contains(synset)) toRemove.add(new Duple<String, Synset>(relation, synset)); } for (Duple<String, Synset> r : toRemove) relations.remove(r.x, r.y); for (String relation : synset.getKnownRelationTypes()) { for (Synset related : synset.getRelations(relation)) { if (related == this) continue; relations.put(relation, related); numRelations++; Relation rel = Relation.fromId(relation); if (rel == null || rel.reflexive() == null) continue; Set<Synset> inwardRelations = related.getRelations( rel.reflexive()); if (inwardRelations.contains(synset)) { inwardRelations.remove(synset); inwardRelations.add(this); } } } for (String example : synset.getExamples()) examples.add(example); this.definition += "; " + synset.getDefinition(); for (Lemma otherLemma : synset.getLemmas()) lemmas.add(otherLemma); for (String attributeLabel : synset.attributeLabels()) { Attribute attribute = attributes.get(attributeLabel); Attribute other = synset.getAttribute(attributeLabel); if (attribute == null) attributes.put(attributeLabel, other); else if (attribute != other) attribute.merge(other); } this.minDepth = -1; this.maxDepth = -1; } BaseSynset(String synsetName); BaseSynset(int offset, PartsOfSpeech pos); BaseSynset(PartsOfSpeech pos); void addMorphyMapping(String original, String lemma); int getSenseNumber(); void setSenseNumber(int senseNumber); String getName(); String getSenseKey(); String getSenseKey(String base); List<String> getSenseKeys(); void addSenseKey(String senseKey); String getDefinition(); PartsOfSpeech getPartOfSpeech(); List<Lemma> getLemmas(); List<String> getExamples(); RelatedForm getDerivationallyRelatedForm(Synset synset); Set<String> getKnownRelationTypes(); Collection<Synset> allRelations(); Set<Synset> getRelations(String relation); Set<Synset> getRelations(Relation relation); int getNumRelations(); List<List<Synset>> getParentPaths(); Set<Synset> getParents(); Set<Synset> getChildren(); int getId(); int[] getFrameIds(); int[] getLemmaIds(); void setFrameInfo(int[] frameIds, int[] lemmaIds); void setId(int newOffset); void setDefinition(String definition); void addLemma(Lemma lemma); void addExample(String example); void addDerivationallyRelatedForm(Synset related, RelatedForm form); boolean addRelation(Relation relation, Synset synset); boolean addRelation(String relation, Synset synset); boolean removeRelation(Relation relation, Synset synset); boolean removeRelation(String relation, Synset synset); String getGloss(); int getMaxDepth(); int getMinDepth(); void setAttribute(String attributeName, Attribute attribute); Attribute getAttribute(String attributeName); Set<String> attributeLabels(); void merge(Synset synset); String toString(); }### Answer: @Test (expected=IllegalArgumentException.class) public void testMergeBadPos() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.VERB); s1.merge(s2); }
### Question: ResnickSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { List<Synset> subsumers = SynsetRelations.lowestCommonHypernyms( synset1, synset2); if (subsumers.size() == 0) return 0; double bestIC = 0; for (Synset subsumer : subsumers) bestIC = Math.max(bestIC, ic.informationContent(subsumer)); return bestIC; } ResnickSimilarity(InformationContent ic); double similarity(Synset synset1, Synset synset2); }### Answer: @Test public void testNoSubsumer() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); SynsetSimilarity sim = new ResnickSimilarity(null); assertEquals(0, sim.similarity(s1, s2), .00001); } @Test public void testSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); MockIC ic = new MockIC(); Synset worst = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, worst); s2.addRelation(Relation.HYPERNYM, worst); Synset best = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, best); s2.addRelation(Relation.HYPERNYM, best); ic.ic.put(best, 10.0); Synset med = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, med); s2.addRelation(Relation.HYPERNYM, med); ic.ic.put(med, 5.0); SynsetSimilarity sim = new ResnickSimilarity(ic); assertEquals(10, sim.similarity(s1, s2), .0001); assertEquals(3, ic.seen.size()); assertTrue(ic.seen.contains(med)); assertTrue(ic.seen.contains(worst)); assertTrue(ic.seen.contains(best)); }
### Question: LeskSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { String[] gloss1 = synset1.getGloss().split("\\s+"); String[] gloss2 = synset2.getGloss().split("\\s+"); return StringUtils.tokenOverlap(gloss1, gloss2); } double similarity(Synset synset1, Synset synset2); }### Answer: @Test public void testLeskSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); s1.setDefinition("how now brown cow"); s2.setDefinition("how now sad meow"); SynsetSimilarity sim = new LeskSimilarity(); assertEquals(2, sim.similarity(s1, s2), .00001); }
### Question: LinSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { double ic1 = ic.informationContent(synset1); double ic2 = ic.informationContent(synset2); if (ic1 == -1 || ic2 == -1) return 0; double icSubsumer = resSim.similarity(synset1, synset2); return (2d * icSubsumer) / (ic1 + ic2); } LinSimilarity(InformationContent ic); double similarity(Synset synset1, Synset synset2); }### Answer: @Test public void testNoSubsumer() { MockIC ic = new MockIC(); Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); SynsetSimilarity sim = new LinSimilarity(ic); assertEquals(0, sim.similarity(s1, s2), .00001); } @Test public void testSimilarity() { MockIC ic = new MockIC(); Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); ic.ic.put(s1, 2.0); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); ic.ic.put(s2, 3.0); Synset worst = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, worst); s2.addRelation(Relation.HYPERNYM, worst); Synset best = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, best); s2.addRelation(Relation.HYPERNYM, best); ic.ic.put(best, 10.0); Synset med = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, med); s2.addRelation(Relation.HYPERNYM, med); ic.ic.put(med, 5.0); SynsetSimilarity sim = new LinSimilarity(ic); assertEquals(2*10/(5), sim.similarity(s1, s2), .0001); assertEquals(5, ic.seen.size()); assertTrue(ic.seen.contains(med)); assertTrue(ic.seen.contains(worst)); assertTrue(ic.seen.contains(best)); assertTrue(ic.seen.contains(s1)); assertTrue(ic.seen.contains(s2)); }
### Question: WuPalmerSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { Synset subsumer = SynsetRelations.lowestCommonHypernym( synset1, synset2); if (subsumer == null) return 0; double depth = subsumer.getMaxDepth() + 1; if (subsumer.getPartOfSpeech() == PartsOfSpeech.NOUN) depth++; double distance1 = SynsetRelations.shortestPathDistance( synset1, subsumer); double distance2 = SynsetRelations.shortestPathDistance( synset2, subsumer); distance1 += depth; distance2 += depth; return (2.0 * depth) / (distance1 + distance2); } double similarity(Synset synset1, Synset synset2); }### Answer: @Test public void testNoSubsumer() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); SynsetSimilarity sim = new WuPalmerSimilarity(); assertEquals(0, sim.similarity(s1, s2), .00001); } @Test public void testNounSimilarity() { Synset subsumer = new BaseSynset(PartsOfSpeech.NOUN); Synset parent = subsumer; for (int i = 0; i < 4; ++i) { Synset child = new BaseSynset(PartsOfSpeech.NOUN); child.addRelation(Relation.HYPERNYM, parent); parent = child; } Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, parent); parent = subsumer; for (int i = 0; i < 2; ++i) { Synset child = new BaseSynset(PartsOfSpeech.NOUN); child.addRelation(Relation.HYPERNYM, parent); parent = child; } Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); s2.addRelation(Relation.HYPERNYM, parent); SynsetSimilarity sim = new WuPalmerSimilarity(); double expected = (2.0 * 2) / (7 + 5); assertEquals(expected, sim.similarity(s1, s2), .00001); } @Test public void testVerbSimilarity() { Synset subsumer = new BaseSynset(PartsOfSpeech.VERB); Synset parent = subsumer; for (int i = 0; i < 4; ++i) { Synset child = new BaseSynset(PartsOfSpeech.NOUN); child.addRelation(Relation.HYPERNYM, parent); parent = child; } Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, parent); parent = subsumer; for (int i = 0; i < 2; ++i) { Synset child = new BaseSynset(PartsOfSpeech.NOUN); child.addRelation(Relation.HYPERNYM, parent); parent = child; } Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); s2.addRelation(Relation.HYPERNYM, parent); SynsetSimilarity sim = new WuPalmerSimilarity(); double expected = (2.0 * 1) / (6 + 4); assertEquals(expected, sim.similarity(s1, s2), .00001); }
### Question: JiangConrathSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { if (synset1.equals(synset2)) return Double.MAX_VALUE; double ic1 = ic.informationContent(synset1); double ic2 = ic.informationContent(synset2); if (ic1 == -1 || ic2 == -1) return 0; double icSubsumer = resSim.similarity(synset1, synset2); double difference = ic1 + ic2 - 2 * icSubsumer; return (difference == 0) ? Double.MAX_VALUE : 1d / difference; } JiangConrathSimilarity(InformationContent ic); double similarity(Synset synset1, Synset synset2); }### Answer: @Test public void testNoSubsumer() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); SynsetSimilarity sim = new JiangConrathSimilarity(null); assertEquals(Double.MAX_VALUE, sim.similarity(s1, s1), .00001); } @Test public void testSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); MockIC ic = new MockIC(); ic.ic.put(s1, 10.0); ic.ic.put(s2, 11.0); Synset worst = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, worst); s2.addRelation(Relation.HYPERNYM, worst); Synset best = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, best); s2.addRelation(Relation.HYPERNYM, best); ic.ic.put(best, 10.0); Synset med = new BaseSynset(PartsOfSpeech.NOUN); s1.addRelation(Relation.HYPERNYM, med); s2.addRelation(Relation.HYPERNYM, med); ic.ic.put(med, 5.0); SynsetSimilarity sim = new JiangConrathSimilarity(ic); assertEquals(1, sim.similarity(s1, s2), .0001); assertEquals(5, ic.seen.size()); assertTrue(ic.seen.contains(med)); assertTrue(ic.seen.contains(worst)); assertTrue(ic.seen.contains(best)); assertTrue(ic.seen.contains(s1)); assertTrue(ic.seen.contains(s2)); }
### Question: LeacockChodorowSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { if (synset1.getPartOfSpeech() != synset2.getPartOfSpeech()) return 0; int maxDepth = wordnet.getMaxDepth(synset1.getPartOfSpeech()); int distance = SynsetRelations.shortestPathDistance(synset1, synset2); return (distance >= 0 && distance <= Integer.MAX_VALUE) ? -1 * Math.log((distance + 1) / (2d * maxDepth)) : 0; } LeacockChodorowSimilarity(OntologyReader reader); double similarity(Synset synset1, Synset synset2); }### Answer: @Test public void testWrongPos() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.VERB); SynsetSimilarity sim = new LeacockChodorowSimilarity(null); assertEquals(0, sim.similarity(s1, s2), .0001); } @Test public void testSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); addParents(s1, s2); MockReader reader = new MockReader(); SynsetSimilarity sim = new LeacockChodorowSimilarity(reader); double expected = -1 * Math.log(7 / (2d * 1)); assertEquals(expected, sim.similarity(s1, s2), .0001); } @Test public void testSimilarityVerb() { Synset s1 = new BaseSynset(PartsOfSpeech.VERB); Synset s2 = new BaseSynset(PartsOfSpeech.VERB); addParents(s1, s2); MockReader reader = new MockReader(); SynsetSimilarity sim = new LeacockChodorowSimilarity(reader); double expected = -1 * Math.log(7 / (2d * 2)); assertEquals(expected, sim.similarity(s1, s2), .0001); }
### Question: LeacockChodorowScaledSimilarity extends LeacockChodorowSimilarity { public double similarity(Synset synset1, Synset synset2) { double lchSim = super.similarity(synset1, synset2); int maxDepth = wordnet.getMaxDepth(synset1.getPartOfSpeech()); double maxSim = -1 * Math.log(1/(2d* maxDepth)); return lchSim / maxSim; } LeacockChodorowScaledSimilarity(OntologyReader reader); double similarity(Synset synset1, Synset synset2); }### Answer: @Test public void testWrongPos() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.VERB); MockReader reader = new MockReader(); SynsetSimilarity sim = new LeacockChodorowScaledSimilarity(reader); assertEquals(0, sim.similarity(s1, s2), .0001); } @Test public void testSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); addParents(s1, s2); MockReader reader = new MockReader(); SynsetSimilarity sim = new LeacockChodorowScaledSimilarity(reader); double max = -1 * Math.log(1/(2d*1)); double expected = -1 * Math.log(7 / (2d * 1)) / max; assertEquals(expected, sim.similarity(s1, s2), .0001); } @Test public void testSimilarityVerb() { Synset s1 = new BaseSynset(PartsOfSpeech.VERB); Synset s2 = new BaseSynset(PartsOfSpeech.VERB); addParents(s1, s2); MockReader reader = new MockReader(); SynsetSimilarity sim = new LeacockChodorowScaledSimilarity(reader); double max = -1 * Math.log(1/(2d*2)); double expected = -1 * Math.log(7 / (2d * 2)) / max; assertEquals(expected, sim.similarity(s1, s2), .0001); }
### Question: ExtendedLeskSimilarity implements SynsetSimilarity { public double similarity(Synset synset1, Synset synset2) { Set<Synset> synsets1 = Sets.newHashSet(synset1.allRelations()); synsets1.add(synset1); Set<Synset> synsets2 = Sets.newHashSet(synset2.allRelations()); synsets2.add(synset2); double score = 0; for (Synset s1 : synsets1) for (Synset s2 : synsets2) score += score(s1.getGloss(), s2.getGloss()); return score; } double similarity(Synset synset1, Synset synset2); }### Answer: @Test public void testLeskSimilarity() { Synset s1 = new BaseSynset(PartsOfSpeech.NOUN); Synset s2 = new BaseSynset(PartsOfSpeech.NOUN); Synset p2 = new BaseSynset(PartsOfSpeech.NOUN); s1.setDefinition("how now brown cow"); s2.setDefinition("how now sad meow"); p2.setDefinition("cow sad sad"); s2.addRelation(Relation.HYPERNYM, p2); SynsetSimilarity sim = new ExtendedLeskSimilarity(); assertEquals(6, sim.similarity(s1, s2), .00001); }
### Question: ExtendedLeskWordSenseDisambiguation extends LeskWordSenseDisambiguation { public void setup(OntologyReader reader) { this.reader = reader; this.sim = new ExtendedLeskSimilarity(); } void setup(OntologyReader reader); String toString(); }### Answer: @Test public void testDisambiguation() { WordSenseDisambiguation wsdAlg = new ExtendedLeskWordSenseDisambiguation(); Sentence sentences = getSentences(TEST_SENTENCE, TEST_POS); wsdAlg.setup(new GenericMockReader(SYNSET_DATA)); Sentence sent = wsdAlg.disambiguate(sentences); Sentence expected = sentences; assertEquals(expected.numTokens(), sent.numTokens()); assertEquals(expected.start(), sent.start()); assertEquals(expected.end(), sent.end()); Annotation word = sent.getAnnotation(1); assertNotNull(word); assertEquals(SYNSET_DATA[2][0], word.sense()); }
### Question: LeskWordSenseDisambiguation extends SlidingWindowDisambiguation { public void setup(OntologyReader reader) { this.reader = reader; this.sim = new LeskSimilarity(); } void setup(OntologyReader reader); String toString(); }### Answer: @Test public void testDisambiguation() { WordSenseDisambiguation wsdAlg = new LeskWordSenseDisambiguation(); Sentence sentences = getSentences(TEST_SENTENCE, TEST_POS); wsdAlg.setup(new GenericMockReader(SYNSET_DATA)); Sentence sent = wsdAlg.disambiguate(sentences); Sentence expected = sentences; assertEquals(expected.numTokens(), sent.numTokens()); assertEquals(expected.start(), sent.start()); assertEquals(expected.end(), sent.end()); Annotation word = sent.getAnnotation(1); assertNotNull(word); assertEquals(SYNSET_DATA[0][0], word.sense()); }
### Question: CombinedSet extends AbstractSet<T> { public int size() { int size = 0; for (Set<T> set : sets) size += set.size(); return size; } CombinedSet(Set<T>...sets); CombinedSet(Collection<Set<T>> setCollection); Iterator<T> iterator(); int size(); }### Answer: @Test public void testCombinedSize() { Set<String> set1 = new HashSet<String>(); for (String s : array1) set1.add(s); Set<String> set2 = new HashSet<String>(); for (String s : array2) set2.add(s); Set<String> combined = new CombinedSet<String>(set1, set2); assertEquals(6, combined.size()); }
### Question: PersonalizedPageRankWSD extends SlidingWindowDisambiguation { public void setup(OntologyReader wordnet) { this.wordnet = wordnet; synsetMap = Maps.newHashMap(); synsetList = Lists.newArrayList(); for (String lemma : wordnet.wordnetTerms()) { for (Synset synset : wordnet.getSynsets(lemma)) if (!synsetMap.containsKey(synset)) { synsetMap.put(synset, synsetMap.size()); synsetList.add(synset); } } SynsetPagerank.setupTransitionAttributes(synsetList, synsetMap); } void setup(OntologyReader wordnet); String toString(); static final String LINK; }### Answer: @Test public void testDisambiguation() { WordSenseDisambiguation wsdAlg = new PersonalizedPageRankWSD(); Sentence sentences = getSentences(TEST_SENTENCE, TEST_POS); LinkedMockReader reader = new LinkedMockReader(SYNSET_DATA); for (String[] synsetLink : SYNSET_LINKS) reader.connectSynsets(synsetLink[0], synsetLink[1], "r"); wsdAlg.setup(reader); Sentence sent = wsdAlg.disambiguate(sentences); Sentence expected = sentences; assertEquals(expected.numTokens(), sent.numTokens()); assertEquals(expected.start(), sent.start()); assertEquals(expected.end(), sent.end()); Annotation word = sent.getAnnotation(1); assertNotNull(word); assertEquals(SYNSET_DATA[2][0], word.sense()); }
### Question: CombinedSet extends AbstractSet<T> { public Iterator<T> iterator() { List<Iterator<T>> iters = new ArrayList<Iterator<T>>(); for (Set<T> set : sets) iters.add(set.iterator()); return new CombinedIterator<T>(iters); } CombinedSet(Set<T>...sets); CombinedSet(Collection<Set<T>> setCollection); Iterator<T> iterator(); int size(); }### Answer: @Test public void testIterator() { Set<String> set1 = new HashSet<String>(); for (String s : array1) set1.add(s); Set<String> set2 = new HashSet<String>(); for (String s : array2) set2.add(s); Set<String> combined = new CombinedSet<String>(set1, set2); Iterator<String> comboIter = combined.iterator(); Iterator<String> iter1 = set1.iterator(); Iterator<String> iter2 = set2.iterator(); while (iter1.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter1.next(), comboIter.next()); } while (iter2.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter2.next(), comboIter.next()); } }
### Question: ExtendedMap extends AbstractMap<K, V> { public V put(K key, V value) { if (baseMap.containsKey(key)) throw new IllegalArgumentException("Should not reinsert keys"); return extendedMap.put(key, value); } ExtendedMap(Map<K, V> baseMap); Set<Map.Entry<K, V>> entrySet(); V get(Object key); V put(K key, V value); }### Answer: @Test public void testPut() { Map<String,String> extendedMap = new ExtendedMap<String, String>(map1); for (Map.Entry<String, String> s : map2.entrySet()) assertNull(extendedMap.put(s.getKey(), s.getValue())); assertEquals(3, map1.size()); }
### Question: ExtendedMap extends AbstractMap<K, V> { public V get(Object key) { V value = baseMap.get(key); return (value != null) ? value : extendedMap.get(key); } ExtendedMap(Map<K, V> baseMap); Set<Map.Entry<K, V>> entrySet(); V get(Object key); V put(K key, V value); }### Answer: @Test public void testGet() { Map<String,String> extendedMap = new ExtendedMap<String, String>(map1); for (String key : map1.keySet()) assertEquals(map1.get(key), extendedMap.get(key)); for (Map.Entry<String, String> s : map2.entrySet()) extendedMap.put(s.getKey(), s.getValue()); for (String key : map1.keySet()) assertEquals(map1.get(key), extendedMap.get(key)); for (String key : map2.keySet()) if (!map1.containsKey(key)) assertEquals(map2.get(key), extendedMap.get(key)); }
### Question: VideoIndexUtils { public static VideoIndex resolve(VideoIndex videoIndex, Media media) { VideoIndex vi = videoIndex; if (videoIndex.getElapsedTime().isEmpty() && videoIndex.getTimestamp().isPresent()) { Instant endTimestamp = media.getStartTimestamp().plus(media.getDuration()); Instant timestamp = videoIndex.getTimestamp().get(); if (timestamp.isBefore(endTimestamp)) { long millis = timestamp.toEpochMilli() - media.getStartTimestamp().toEpochMilli(); if (millis >= 0) { Optional<Duration> elapsedTime = Optional.of(Duration.ofMillis(millis)); vi = new VideoIndex(videoIndex.getTimestamp(), elapsedTime, vi.getTimecode()); } } } else if (videoIndex.getTimestamp().isEmpty() && videoIndex.getElapsedTime().isPresent()) { Instant timestamp = media.getStartTimestamp().plus(videoIndex.getElapsedTime().get()); vi = new VideoIndex(Optional.of(timestamp), videoIndex.getElapsedTime(), videoIndex.getTimecode()); } return vi; } static Optional<Duration> diff(VideoIndex a, VideoIndex b); static VideoIndex resolve(VideoIndex videoIndex, Media media); static VideoIndex resolve(VideoIndex videoIndex, Media source, Media target); }### Answer: @Test public void resolveAddElapsedTimeTest() { var et = Duration.ofMinutes(2); var ts = now.plus(et); var vi = new VideoIndex(ts); var rvi = VideoIndexUtils.resolve(vi, media1); assertTrue(rvi.getTimestamp().isPresent()); assertEquals(ts, rvi.getTimestamp().get()); assertTrue(rvi.getElapsedTime().isPresent()); assertEquals(et, rvi.getElapsedTime().get()); } @Test public void resolveAddTimestampTest() { var et = Duration.ofMinutes(2); var ts = now.plus(et); var vi = new VideoIndex(et); var rvi = VideoIndexUtils.resolve(vi, media1); assertTrue(rvi.getTimestamp().isPresent()); assertEquals(ts, rvi.getTimestamp().get()); assertTrue(rvi.getElapsedTime().isPresent()); assertEquals(et, rvi.getElapsedTime().get()); }
### Question: Pager implements Runnable { public Pager(BiFunction<Long, Long, T> fetchFn, Long limit, Long pageSize) { Function<RequestPager.Page, T> fn = (page) -> { try { return fetchFn.apply(page.getLimit(), page.getOffset()); } catch (Exception e) { Long start = page.getOffset(); Long end = start + page.getLimit(); throw new RuntimeException("Page request from " + start + " + to " + end + " failed"); } }; RequestPager<T> pager = new RequestPager<>(fn, 2, 2); runner = pager.build(limit.intValue(), pageSize.intValue()); } Pager(BiFunction<Long, Long, T> fetchFn, Long limit, Long pageSize); void run(); Observable<T> getObservable(); }### Answer: @Test public void testPager() { var data = new ArrayList<Integer>(); for (var i = 0; i < 1000; i++) { data.add(i); } var pager = new Pager<>((limit, offset) -> { var start = offset; Long end = limit + offset; if (start > data.size()) { start = (long) data.size() - 1; } if (end >= data.size()) { end = (long) data.size(); } return data.subList(start.intValue(), end.intValue()); }, (long) data.size(), 10L); var n = new AtomicInteger(0); pager.getObservable() .subscribe(xs -> n.addAndGet(xs.size()), ex -> Assert.fail(), () -> Assert.assertEquals(data.size(), n.get())); pager.run(); }
### Question: AVFImageCaptureService implements SelectableImageCaptureService { @Override public Framegrab capture(File file) { Framegrab framegrab = new Framegrab(); start(); Optional<Image> imageOpt = imageCapture.capture(file, Duration.ofSeconds(10)); if (imageOpt.isPresent()) { framegrab.setImage(imageOpt.get()); MediaPlayer<? extends VideoState, ? extends VideoError> mediaPlayer = Initializer.getToolBox().getMediaPlayer(); if (mediaPlayer != null) { try { mediaPlayer.requestVideoIndex() .thenAccept(framegrab::setVideoIndex) .get(3000, TimeUnit.MILLISECONDS); } catch (Exception e) { log.warn("Problem with requesting videoIndex while capturing a framegrab", e); framegrab.setVideoIndex(new VideoIndex(Instant.now())); } } if (!framegrab.getVideoIndex().isPresent()) { log.warn("Failed to get video index. Using current timestamp for video index"); framegrab.setVideoIndex(new VideoIndex(Instant.now())); } } else { log.warn("Failed to capture image from device named '" + currentDevice + "'"); } return framegrab; } protected AVFImageCaptureService(); Collection<String> listDevices(); void setDevice(String device); @Override Framegrab capture(File file); @Override void dispose(); static synchronized AVFImageCaptureService getInstance(); AVFImageCapture getImageCapture(); static AVFImageCaptureService imageCaptureService; }### Answer: @Ignore @Test public void testImageCapture() throws Exception { AVFImageCapture ic = new AVFImageCapture(); String[] devices = ic.videoDevicesAsStrings(); if (devices.length > 0) { ic.startSessionWithNamedDevice(devices[0]); Path path = Paths.get("target", getClass().getSimpleName() + "-0-" + Instant.now() + ".png"); Optional<Image> png = ic.capture(path.toFile()); Assert.assertTrue(png.isPresent()); ic.stopSession(); } else { System.err.println("No frame capture devices were found"); } }
### Question: Initializer { public static Path getSettingsDirectory() { if (settingsDirectory == null) { String home = System.getProperty("user.home"); Path path = Paths.get(home, ".vars"); settingsDirectory = createDirectory(path); if (settingsDirectory == null) { log.warn("Failed to create settings directory at " + path); } } return settingsDirectory; } static Config getConfig(); static UIToolBox getToolBox(); static Path getSettingsDirectory(); static Path getImageDirectory(); static Path createDirectory(Path path); }### Answer: @Test public void getSettingsDirectoryTest() { Path path = Initializer.getSettingsDirectory(); assertNotNull("The Settings directory was null", path); assertTrue("The settings directory does not exist", Files.exists(path)); }
### Question: Initializer { public static UIToolBox getToolBox() { if (toolBox == null) { Services services = ServicesBuilder.build(Initializer.getConfig()); ResourceBundle bundle = ResourceBundle.getBundle("i18n", Locale.getDefault()); LessCSSLoader lessLoader = new LessCSSLoader(); String stylesheet = lessLoader.loadLess(Initializer.class.getResource("/less/annotation.less")) .toExternalForm(); Data data = new Data(); Integer timeJump = SharktopodaSettingsPaneController.getTimeJump(); log.info("Setting Time Jump to {} millis", timeJump); data.setTimeJump(timeJump); toolBox = new UIToolBox(data, services, new EventBus(), bundle, getConfig(), Collections.singletonList(stylesheet), new ForkJoinPool()); } return toolBox; } static Config getConfig(); static UIToolBox getToolBox(); static Path getSettingsDirectory(); static Path getImageDirectory(); static Path createDirectory(Path path); }### Answer: @Ignore @Test public void getToolBoxTest() throws Exception { UIToolBox toolBox = Initializer.getToolBox(); assertNotNull("UIToolBox was null", toolBox); Data data = toolBox.getData(); assertNotNull("Data in toolbox was null", data); Services services = toolBox.getServices(); assertNotNull("Services in toolbox was null", data); }
### Question: GraywaterAdapter extends RecyclerView.Adapter<VH> { public void add(@NonNull final T item) { add(mItems.size(), item, true); } @Override int getItemViewType(final int position); @Override VH onCreateViewHolder(final ViewGroup parent, final int viewType); @Override @SuppressLint("RecyclerView") void onBindViewHolder(final VH holder, final int viewHolderPosition); @VisibleForTesting int getViewHolderCount(final int itemPosition); @Override int getItemCount(); void add(@NonNull final T item); void add(@NonNull final T item, final boolean notify); int getItemPosition(final int viewHolderPosition); int getBinderPosition(final int itemIndex, final int viewHolderPosition); void add(final int position, @NonNull final T item, final boolean notify); @Nullable T remove(final int itemPosition); @Nullable T remove(final int itemPosition, final boolean notify); int getFirstViewHolderPosition(final int itemPosition, @NonNull final Class<? extends VH> viewHolderClass); void clear(); static View inflate(final ViewGroup parent, @LayoutRes final int layoutRes); @Override void onViewRecycled(final VH holder); @NonNull List<T> getItems(); @Nullable List<Provider<Binder<? super T, VH, ? extends VH>>> getBindersForPosition(final int itemPosition); @Nullable Pair<Integer, Integer> getViewHolderRange(final int itemPosition); }### Answer: @Test public void testAdd() throws Exception { final TestAdapter adapter = new TestAdapter(); adapter.add("one"); assertEquals(2, adapter.getItemCount()); adapter.add("two"); assertEquals(4, adapter.getItemCount()); adapter.add("three"); assertEquals(6, adapter.getItemCount()); }
### Question: GraywaterAdapter extends RecyclerView.Adapter<VH> { @Nullable public T remove(final int itemPosition) { return remove(itemPosition, true); } @Override int getItemViewType(final int position); @Override VH onCreateViewHolder(final ViewGroup parent, final int viewType); @Override @SuppressLint("RecyclerView") void onBindViewHolder(final VH holder, final int viewHolderPosition); @VisibleForTesting int getViewHolderCount(final int itemPosition); @Override int getItemCount(); void add(@NonNull final T item); void add(@NonNull final T item, final boolean notify); int getItemPosition(final int viewHolderPosition); int getBinderPosition(final int itemIndex, final int viewHolderPosition); void add(final int position, @NonNull final T item, final boolean notify); @Nullable T remove(final int itemPosition); @Nullable T remove(final int itemPosition, final boolean notify); int getFirstViewHolderPosition(final int itemPosition, @NonNull final Class<? extends VH> viewHolderClass); void clear(); static View inflate(final ViewGroup parent, @LayoutRes final int layoutRes); @Override void onViewRecycled(final VH holder); @NonNull List<T> getItems(); @Nullable List<Provider<Binder<? super T, VH, ? extends VH>>> getBindersForPosition(final int itemPosition); @Nullable Pair<Integer, Integer> getViewHolderRange(final int itemPosition); }### Answer: @Test public void testRemove() throws Exception { final TestAdapter adapter = new TestAdapter(); adapter.add("zero"); adapter.add("one"); adapter.add("two"); adapter.add("three"); adapter.add("four"); adapter.add("five"); adapter.remove(0); assertEquals(2 * 5, adapter.getItemCount()); adapter.remove(4); assertEquals(2 * 4, adapter.getItemCount()); adapter.remove(2); assertEquals(2 * 3, adapter.getItemCount()); final List<Object> items = adapter.getItems(); assertEquals(3, items.size()); assertEquals("one", items.get(0)); assertEquals("two", items.get(1)); assertEquals("four", items.get(2)); }
### Question: GraywaterAdapter extends RecyclerView.Adapter<VH> { @Override public int getItemViewType(final int position) { return internalGetItemViewType(position); } @Override int getItemViewType(final int position); @Override VH onCreateViewHolder(final ViewGroup parent, final int viewType); @Override @SuppressLint("RecyclerView") void onBindViewHolder(final VH holder, final int viewHolderPosition); @VisibleForTesting int getViewHolderCount(final int itemPosition); @Override int getItemCount(); void add(@NonNull final T item); void add(@NonNull final T item, final boolean notify); int getItemPosition(final int viewHolderPosition); int getBinderPosition(final int itemIndex, final int viewHolderPosition); void add(final int position, @NonNull final T item, final boolean notify); @Nullable T remove(final int itemPosition); @Nullable T remove(final int itemPosition, final boolean notify); int getFirstViewHolderPosition(final int itemPosition, @NonNull final Class<? extends VH> viewHolderClass); void clear(); static View inflate(final ViewGroup parent, @LayoutRes final int layoutRes); @Override void onViewRecycled(final VH holder); @NonNull List<T> getItems(); @Nullable List<Provider<Binder<? super T, VH, ? extends VH>>> getBindersForPosition(final int itemPosition); @Nullable Pair<Integer, Integer> getViewHolderRange(final int itemPosition); }### Answer: @Test public void testGetItemViewType() throws Exception { final TestAdapter adapter = new TestAdapter(); adapter.add(Uri.parse("https: assertEquals(3, adapter.getItemCount()); adapter.add("one"); assertEquals(5, adapter.getItemCount()); adapter.add(Uri.parse("http: assertEquals(8, adapter.getItemCount()); adapter.add("three"); assertEquals(10, adapter.getItemCount()); adapter.add(Uri.parse("https: assertEquals(13, adapter.getItemCount()); adapter.add("five"); assertEquals(15, adapter.getItemCount()); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(0)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(1)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(2)); assertEquals(TestAdapter.TextViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(3)); assertEquals(TestAdapter.TextViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(4)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(5)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(6)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(10)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(11)); assertEquals(TestAdapter.ImageViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(12)); assertEquals(TestAdapter.TextViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(13)); assertEquals(TestAdapter.TextViewHolderCreator.VIEW_TYPE, adapter.getItemViewType(14)); }
### Question: GraywaterAdapter extends RecyclerView.Adapter<VH> { public void clear() { mItems.clear(); mBinderListCache.clear(); mViewHolderToItemPositionCache.clear(); mItemPositionToFirstViewHolderPositionCache.clear(); mViewHolderPreparedCache.clear(); mPreviousBoundViewHolderPosition = NO_PREVIOUS_BOUND_VIEWHOLDER; } @Override int getItemViewType(final int position); @Override VH onCreateViewHolder(final ViewGroup parent, final int viewType); @Override @SuppressLint("RecyclerView") void onBindViewHolder(final VH holder, final int viewHolderPosition); @VisibleForTesting int getViewHolderCount(final int itemPosition); @Override int getItemCount(); void add(@NonNull final T item); void add(@NonNull final T item, final boolean notify); int getItemPosition(final int viewHolderPosition); int getBinderPosition(final int itemIndex, final int viewHolderPosition); void add(final int position, @NonNull final T item, final boolean notify); @Nullable T remove(final int itemPosition); @Nullable T remove(final int itemPosition, final boolean notify); int getFirstViewHolderPosition(final int itemPosition, @NonNull final Class<? extends VH> viewHolderClass); void clear(); static View inflate(final ViewGroup parent, @LayoutRes final int layoutRes); @Override void onViewRecycled(final VH holder); @NonNull List<T> getItems(); @Nullable List<Provider<Binder<? super T, VH, ? extends VH>>> getBindersForPosition(final int itemPosition); @Nullable Pair<Integer, Integer> getViewHolderRange(final int itemPosition); }### Answer: @Test public void testClear() throws Exception { final TestAdapter adapter = new TestAdapter(); final Uri tumblrUri = Uri.parse("https: adapter.add(tumblrUri); assertEquals(3, adapter.getItemCount()); adapter.add("one"); assertEquals(5, adapter.getItemCount()); adapter.add(Uri.parse("http: assertEquals(8, adapter.getItemCount()); adapter.add("three"); assertEquals(10, adapter.getItemCount()); final Uri googleUri = Uri.parse("https: adapter.add(googleUri); assertEquals(13, adapter.getItemCount()); adapter.add("five"); assertEquals(15, adapter.getItemCount()); adapter.clear(); assertEquals(0, adapter.getItemCount()); }
### Question: ZNodePath extends ZNodeLabelVector { public static String canonicalize(final String path) { final int length = path.length(); int lastSlash = -1; StringBuilder builder = null; for (int i=0; i<length; ++i) { char c = path.charAt(i); if ((c == SLASH) || (i == length - 1)) { if (i > 0) { if ((c == SLASH) && (lastSlash == i-1)) { if (builder == null) { builder = new StringBuilder(length) .append(path, 0, lastSlash+1); } } else { ZNodeLabel label = ZNodeLabel.validated(path, lastSlash+1, (c == SLASH) ? i : i+1); if (ZNodeLabel.self().equals(label)) { if (builder == null) { builder = new StringBuilder(length) .append(path, 0, lastSlash+1); } } else if (ZNodeLabel.parent().equals(label)) { if (builder == null) { builder = new StringBuilder(length) .append(path, 0, lastSlash+1); } int buildLength = builder.length(); assert (builder.charAt(buildLength -1) == SLASH); int parentSlash = -1; for (int j = buildLength-2; j >= 0; j--) { if (builder.charAt(j) == SLASH) { parentSlash = j; break; } } if (parentSlash < 0) { throw new IllegalArgumentException(String.format("missing parent at index %d of %s", i, path)); } builder.delete(parentSlash + 1, buildLength); } else { if (builder != null) { builder.append(path, lastSlash+1, i+1); } } } } if (c == SLASH) { lastSlash = i; } } } String canonicalized; if (builder == null) { canonicalized = ((length > 1) && (path.charAt(length - 1) == SLASH)) ? path.substring(0, length - 1) : path; } else { int buildLength = builder.length(); if ((buildLength > 1) && (builder.charAt(buildLength - 1) == SLASH)) { builder.deleteCharAt(buildLength - 1); } canonicalized = builder.toString(); } if (canonicalized.isEmpty()) { throw new IllegalArgumentException(String.format("empty canonicalized path for %s", path)); } if (canonicalized.charAt(0) != SLASH) { throw new IllegalArgumentException(String.format("not absolute path for %s", path)); } return canonicalized; } protected ZNodePath(String label); static RootZNodePath root(); static String validate(String path); @SuppressWarnings("unchecked") static T validate(T path, int start, int end); static ZNodePath validated(String path); static ZNodePath validated(String path, int start, int end); static String canonicalize(final String path); static ZNodePath canonicalized(String path); @Serializes(from=String.class, to=ZNodePath.class) static ZNodePath fromString(String path); @Override final boolean isAbsolute(); RelativeZNodePath relative(ZNodePath other); @Override abstract ZNodePath join(ZNodeName other); abstract boolean isRoot(); abstract AbstractZNodeLabel label(); }### Answer: @Test public void testCanonicalize() { assertEquals("/", ZNodePath.canonicalize("/")); assertEquals("/", ZNodePath.canonicalize(" assertEquals("/", ZNodePath.canonicalize(" assertEquals("/a", ZNodePath.canonicalize("/a")); assertEquals("/a", ZNodePath.canonicalize("/a/")); assertEquals("/", ZNodePath.canonicalize("/.")); assertEquals("/a", ZNodePath.canonicalize("/a/.")); assertEquals("/", ZNodePath.canonicalize("/a/..")); }
### Question: IterableNullChecker { public static <T> Iterable<T> checkNotContainsNull(final Iterable<T> iterable, final String errorMessage) { checkNotNull(iterable, "Argument \'iterable\' cannot be null."); checkNotNull(errorMessage, "Argument \'errorMessage\' cannot be null."); for (final Object o : iterable) { checkNotNull(o, errorMessage); } return iterable; } static Iterable<T> checkNotContainsNull(final Iterable<T> iterable, final String errorMessage); }### Answer: @Test(expected = IllegalArgumentException.class) public void testCheckNotContainsNull_nullIterable() { IterableNullChecker.checkNotContainsNull(null, ""); } @Test public void testCheckNotContainsNull_emptyIterable() { IterableNullChecker.checkNotContainsNull(new ArrayList<>(), ""); } @Test(expected = IllegalArgumentException.class) public void testCheckNotContainsNull_iterableContainingOnlyNull() { final List<Object> list = new ArrayList<>(); list.add(null); IterableNullChecker.checkNotContainsNull(list, ""); } @Test(expected = IllegalArgumentException.class) public void testCheckNotContainsNull_iterableContainingNullAndOtherValues() { final List<Object> list = new ArrayList<>(); list.add(null); list.add("hello"); IterableNullChecker.checkNotContainsNull(list, ""); } @Test public void testCheckNotContainsNull_iterableContainingOnlyNonNullValues() { final List<Object> list = new ArrayList<>(); list.add("hello"); list.add("world"); IterableNullChecker.checkNotContainsNull(list, ""); } @Test(expected = IllegalArgumentException.class) public void testCheckNotContainsNull_nullErrorMessage() { IterableNullChecker.checkNotContainsNull(new ArrayList<>(), null); }
### Question: CommonFunctions extends AbstractCommonFunctions implements SelfReference { @Deprecated public boolean takeItem(Player player, int id, int amount) { ItemStack IS = new ItemStack(id, amount); if (!player.getInventory().containsAtLeast(IS, amount)) return false; player.getInventory().removeItem(IS); return true; } CommonFunctions(TriggerReactorCore plugin); @Deprecated boolean takeItem(Player player, int id, int amount); boolean takeItem(Player player, String id, int amount); @Deprecated boolean takeItem(Player player, int id, int amount, int data); boolean takeItem(Player player, String id, int amount, int data); Collection<? extends Player> getPlayers(); @Override PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); @Deprecated ItemStack item(int type, int amount, int data); ItemStack item(String type, int amount, int data); @Deprecated ItemStack item(int type, int amount); ItemStack item(String type, int amount); ItemStack headForName(String targetName, int amount); ItemStack headForValue(String textureValue); }### Answer: @SuppressWarnings("deprecation") @Test public void testTakeItem() { ItemStack IS = new ItemStack(Material.STONE, 64); ItemStack IS2 = new ItemStack(Material.STONE, 64, (short) 1); FakeInventory inv = fInventory(this, IS, IS2); Player mockPlayer = Mockito.mock(Player.class); PlayerInventory mockInventory = preparePlayerInventory(mockPlayer, inv); Mockito.when(mockPlayer.getInventory()).thenReturn(mockInventory); fn.takeItem(mockPlayer, "STONE", 1); Assert.assertEquals(63, IS.getAmount()); fn.takeItem(mockPlayer, "STONE", 2, 1); Assert.assertEquals(62, IS2.getAmount()); fn.takeItem(mockPlayer, 1, 5); Assert.assertEquals(58, IS.getAmount()); fn.takeItem(mockPlayer, 1, 6, 1); Assert.assertEquals(56, IS2.getAmount()); }
### Question: AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String currentAreaAt(Location location) { String[] areaNames = currentAreasAt(location); return areaNames.length > 0 ? areaNames[0] : null; } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); }### Answer: @Test public void testCurrentAreaAt() { }
### Question: AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String[] currentAreas(Entity entity) { return currentAreasAt(entity.getLocation()); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); }### Answer: @Test public void testCurrentAreas() { }
### Question: AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String[] currentAreasAt(Location location) { AbstractAreaTriggerManager areaManager = plugin.getAreaManager(); String[] names = areaManager.getAreas(LocationUtil.convertToSimpleLocation(location)).stream() .map(Map.Entry::getValue) .map(Trigger::getTriggerName) .toArray(String[]::new); return names; } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); }### Answer: @Test public void testCurrentAreasAt() { }
### Question: AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public List<Entity> getEntitiesInArea(String areaTriggerName) { AbstractAreaTriggerManager areaManager = plugin.getAreaManager(); AreaTrigger trigger = areaManager.getArea(areaTriggerName); if (trigger == null) return null; List<Entity> entities = new ArrayList<>(); for (IEntity ie : trigger.getEntities()) entities.add(ie.get()); return entities; } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); }### Answer: @Test public void testGetEntitiesInArea() { }
### Question: AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String color(String str) { return ChatColor.translateAlternateColorCodes('&', str); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); }### Answer: @Test public void testColor() { Assert.assertEquals(ChatColor.RED + "My message", fn.color("&cMy message")); }
### Question: AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public Color bukkitColor(int red, int green, int blue) { return Color.fromRGB(red, green, blue); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); }### Answer: @Test public void testBukkitColor() { Color expect = Color.fromRGB(3, 6, 8); Color result = fn.bukkitColor(3, 6, 8); Assert.assertEquals(expect.asBGR(), result.asBGR()); }
### Question: AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { @Deprecated public abstract ItemStack item(int type, int amount, int data); AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); }### Answer: @Test public abstract void testItem();
### Question: AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String getItemTitle(ItemStack IS) { ItemMeta IM = IS.getItemMeta(); if (IM == null) return ""; String dispName = IM.getDisplayName(); return dispName == null ? "" : dispName; } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); }### Answer: @Test public void testGetItemTitle() { ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> "abc").when(mockItemMeta).getDisplayName(); Assert.assertEquals("abc", fn.getItemTitle(IS)); }
### Question: AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public void setItemTitle(ItemStack IS, String title) { ItemMeta IM = IS.getItemMeta(); if (IM == null) IM = Bukkit.getItemFactory().getItemMeta(IS.getType()); if (IM == null) return; IM.setDisplayName(color(title)); IS.setItemMeta(IM); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); }### Answer: @Test public void testSetItemTitle() { ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> { title = invocation.getArgument(0); return null; }).when(mockItemMeta).setDisplayName(Mockito.anyString()); fn.setItemTitle(IS, "xyz"); Assert.assertEquals("xyz", title); }
### Question: AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public boolean hasLore(ItemStack IS, String lore) { ItemMeta IM = IS.getItemMeta(); if (IM == null) return false; List<String> lores = IM.getLore(); if (lores == null) return false; return lores.contains(lore); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); }### Answer: @Test public void testHasLore() { List<String> lores = new ArrayList<>(); lores.add("abab"); lores.add("cdcd"); ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> lores).when(mockItemMeta).getLore(); Assert.assertTrue(fn.hasLore(IS, "abab")); Assert.assertFalse(fn.hasLore(IS, "hoho")); }
### Question: CommonFunctions extends AbstractCommonFunctions implements SelfReference { @Deprecated public ItemStack item(int type, int amount, int data) { return new ItemStack(type, amount, (short) data); } CommonFunctions(TriggerReactorCore plugin); @Deprecated boolean takeItem(Player player, int id, int amount); boolean takeItem(Player player, String id, int amount); @Deprecated boolean takeItem(Player player, int id, int amount, int data); boolean takeItem(Player player, String id, int amount, int data); Collection<? extends Player> getPlayers(); @Override PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); @Deprecated ItemStack item(int type, int amount, int data); ItemStack item(String type, int amount, int data); @Deprecated ItemStack item(int type, int amount); ItemStack item(String type, int amount); ItemStack headForName(String targetName, int amount); ItemStack headForValue(String textureValue); }### Answer: @SuppressWarnings("deprecation") @Test public void testItem() { ItemStack IS = new ItemStack(Material.STONE, 64); ItemStack IS2 = new ItemStack(Material.STONE, 63, (short) 1); Assert.assertTrue(isEqual(IS, fn.item("STONE", 64))); Assert.assertTrue(isEqual(IS2, fn.item("STONE", 63, 1))); Assert.assertTrue(isEqual(IS, fn.item(1, 64))); Assert.assertTrue(isEqual(IS2, fn.item(1, 63, 1))); }
### Question: AbstractCommonFunctions extends io.github.wysohn.triggerreactor.core.manager.trigger.share.CommonFunctions implements SelfReference { public String getLore(ItemStack IS, int index) { ItemMeta IM = IS.getItemMeta(); if (IM == null) return null; List<String> lores = IM.getLore(); if (lores == null) return null; if (index < 0 || index >= lores.size()) return null; return lores.get(index); } AbstractCommonFunctions(TriggerReactorCore plugin); Plugin plugin(String name); @Deprecated abstract boolean takeItem(Player player, int id, int amount); abstract boolean takeItem(Player player, String id, int amount); @Deprecated abstract boolean takeItem(Player player, int id, int amount, int data); abstract boolean takeItem(Player player, String id, int amount, int data); boolean takeItem(Player player, ItemStack IS, int amount); Location location(String world, double x, double y, double z); Location location(String world, double x, double y, double z, double yaw, double pitch); Block block(String world, int x, int y, int z); boolean locationEqual(Location loc1, Location loc2); abstract PotionEffect makePotionEffect(String EffectType, int duration, int amplifier, boolean ambient, boolean particles, Color color); Player player(String name); OfflinePlayer oplayer(String name); abstract Collection<? extends Player> getPlayers(); String currentArea(Entity entity); String currentAreaAt(Location location); String[] currentAreas(Entity entity); String[] currentAreasAt(Location location); List<Entity> getEntitiesInArea(String areaTriggerName); String color(String str); Color bukkitColor(int red, int green, int blue); @Deprecated abstract ItemStack item(int type, int amount, int data); abstract ItemStack item(String type, int amount, int data); @Deprecated abstract ItemStack item(int type, int amount); abstract ItemStack item(String type, int amount); String getItemTitle(ItemStack IS); void setItemTitle(ItemStack IS, String title); boolean hasLore(ItemStack IS, String lore); String getLore(ItemStack IS, int index); void addLore(ItemStack IS, String lore); void setLore(ItemStack IS, int index, String lore); void removeLore(ItemStack IS, int index); void clearLore(ItemStack IS); int loreSize(ItemStack IS); @Override String formatCurrency(double money, String locale1, String locale2); @Override String formatCurrency(double money); Block getTargetBlock(Player player, int maxDistance); ItemStack headForName(String targetName); abstract ItemStack headForName(String targetName, int amount); abstract ItemStack headForValue(String textureValue); }### Answer: @Test public void testGetLore() { List<String> lores = new ArrayList<>(); lores.add("abab"); lores.add("cdcd"); ItemStack IS = new ItemStack(Material.STONE); Mockito.doAnswer(invocation -> lores).when(mockItemMeta).getLore(); Assert.assertEquals("abab", fn.getLore(IS, 0)); Assert.assertEquals("cdcd", fn.getLore(IS, 1)); Assert.assertNull(fn.getLore(IS, 2)); Assert.assertNull(fn.getLore(IS, -1)); }