method2testcases
stringlengths 118
3.08k
|
---|
### Question:
MemoryReactiveStore implements ReactiveStore<Key, Value> { public void replaceAll(@NonNull final List<Value> modelList) { cache.clear(); storeAll(modelList); } MemoryReactiveStore(@NonNull final Func1<Value, Key> extractKeyFromModel,
@NonNull final Store.MemoryStore<Key, Value> cache); void storeSingular(@NonNull final Value model); void storeAll(@NonNull final List<Value> modelList); void replaceAll(@NonNull final List<Value> modelList); @NonNull Observable<Option<Value>> getSingular(@NonNull final Key key); @NonNull Observable<Option<List<Value>>> getAll(); }### Answer:
@Test public void cacheIsClearedInReplaceAll() { List<TestObject> list = createTestObjectList(); reactiveStore.replaceAll(list); Mockito.verify(cache).clear(); } |
### Question:
Cache implements MemoryStore<Key, Value> { @Override @NonNull public Maybe<Value> getSingular(@NonNull final Key key) { return Maybe.fromCallable(() -> cache.containsKey(key)) .filter(isPresent -> isPresent) .map(__ -> cache.get(key)) .filter(this::notExpired) .map(CacheEntry::cachedObject) .subscribeOn(Schedulers.computation()); } Cache(@NonNull final Function<Value, Key> extractKeyFromModel,
@NonNull final TimestampProvider timestampProvider); Cache(@NonNull final Function<Value, Key> extractKeyFromModel,
@NonNull final TimestampProvider timestampProvider,
final long timeoutMs); private Cache(@NonNull final Function<Value, Key> extractKeyFromModel,
@NonNull final TimestampProvider timestampProvider,
@NonNull final Option<Long> timeoutMs); @Override void putSingular(@NonNull Value value); @Override void putAll(@NonNull List<Value> values); @Override @NonNull Maybe<Value> getSingular(@NonNull final Key key); @Override @NonNull Maybe<List<Value>> getAll(); @Override void clear(); }### Answer:
@Test public void getSingularCompletesWithNoEmissionsWhenCacheIsEmpty() { cache.getSingular("KEY").test().assertNoValues(); } |
### Question:
Cache implements MemoryStore<Key, Value> { @Override @NonNull public Maybe<List<Value>> getAll() { return Observable.fromIterable(cache.values()) .filter(this::notExpired) .map(CacheEntry::cachedObject) .toList() .filter(ListUtils::isNotEmpty) .subscribeOn(Schedulers.computation()); } Cache(@NonNull final Function<Value, Key> extractKeyFromModel,
@NonNull final TimestampProvider timestampProvider); Cache(@NonNull final Function<Value, Key> extractKeyFromModel,
@NonNull final TimestampProvider timestampProvider,
final long timeoutMs); private Cache(@NonNull final Function<Value, Key> extractKeyFromModel,
@NonNull final TimestampProvider timestampProvider,
@NonNull final Option<Long> timeoutMs); @Override void putSingular(@NonNull Value value); @Override void putAll(@NonNull List<Value> values); @Override @NonNull Maybe<Value> getSingular(@NonNull final Key key); @Override @NonNull Maybe<List<Value>> getAll(); @Override void clear(); }### Answer:
@Test public void getAllCompletesWithNoEmissionsWhenCacheIsEmpty() { cache.getAll().test().assertNoValues(); } |
### Question:
UnwrapOptionTransformer implements ObservableTransformer<Option<T>, T> { @Override public ObservableSource<T> apply(final Observable<Option<T>> upstream) { return upstream.filter(Option::isSome) .map(OptionUnsafe::getUnsafe); } @Override ObservableSource<T> apply(final Observable<Option<T>> upstream); static UnwrapOptionTransformer<T> create(); }### Answer:
@Test public void transformerFiltersOutNone() { Observable<Option<Object>> source = Observable.just(Option.none()); TestObserver<Object> ts = new TestObserver<>(); transformer.apply(source).subscribe(ts); ts.assertNoValues(); }
@Test public void transformerUnwrapsSome() { Object object = new Object(); Observable<Option<Object>> source = Observable.just(Option.ofObj(object)); TestObserver<Object> ts = new TestObserver<>(); transformer.apply(source).subscribe(ts); ts.assertValue(object); } |
### Question:
Preconditions { public static <T> T checkNotNull(final T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } private Preconditions(); @NonNull static T get(@Nullable final T reference); static T checkNotNull(final T reference); static T checkNotNull(final T reference, @NonNull final String errorMessage); }### Answer:
@Test public void checkNotNull_doesNotThrowException_whenNonNull() { Preconditions.checkNotNull(new Object()); }
@Test public void checkNotNull_throwsNullPointerException_whenNull() { thrown.expect(NullPointerException.class); Preconditions.checkNotNull(null); }
@Test public void checkNotNullWithMessage_doesNotThrowException_whenNonNull() { Preconditions.checkNotNull(new Object(), "Unused message"); }
@Test public void checkNotNullWithMessage_throwsNullPointerExceptionWithMessage_whenNull() { final String message = "message"; thrown.expect(NullPointerException.class); thrown.expectMessage(message); Preconditions.checkNotNull(null, message); } |
### Question:
Preconditions { @NonNull public static <T> T get(@Nullable final T reference) { if (reference == null) { throw new NullPointerException("Assertion for a nonnull object failed."); } return reference; } private Preconditions(); @NonNull static T get(@Nullable final T reference); static T checkNotNull(final T reference); static T checkNotNull(final T reference, @NonNull final String errorMessage); }### Answer:
@Test public void get_returnsParameter_whenNonNull() { Object obj = new Object(); assertThat(Preconditions.get(obj)).isEqualTo(obj); }
@Test public void get_throwsNullPointerException_whenNull() { thrown.expect(NullPointerException.class); Preconditions.get(null); } |
### Question:
StringUtils { @SuppressWarnings("unchecked") @NonNull public String applySubstitutionsToString(@NonNull final String string, @NonNull final Pair<String, String>... substitutions) { String primaryString = string; for (final Pair<String, String> substitution : substitutions) { primaryString = primaryString.replace("{{" + substitution.first + "}}", substitution.second); } return primaryString; } @Inject StringUtils(); @SuppressWarnings("unchecked") @NonNull String applySubstitutionsToString(@NonNull final String string, @NonNull final Pair<String, String>... substitutions); }### Answer:
@Test public void parametersAreReplacedCorrectly() { String param1Name = "firstName"; String param1Value = "Georgy"; String param2Name = "lastName"; String param2Value = "Georgiev"; String string = "He is {{firstName}} {{lastName}}"; String formattedString = stringUtils.applySubstitutionsToString(string, Pair.create(param1Name, param1Value), Pair.create(param2Name, param2Value)); assertThat(formattedString).isEqualTo("He is Georgy Georgiev"); }
@Test public void notFoundParametersAreIgnored() { String param1Name = "wrongParamName"; String param1Value = "Somebody"; String string = "He is {{firstName}}"; String formattedString = stringUtils.applySubstitutionsToString(string, Pair.create(param1Name, param1Value)); assertThat(formattedString).isEqualTo(string); } |
### Question:
ListUtils { @NonNull public static <T> List<T> union(@NonNull final List<T> list1, @NonNull final List<T> list2) { return new ArrayList<T>() {{ addAll(list1); addAll(list2); }}; } @NonNull static List<T> union(@NonNull final List<T> list1, @NonNull final List<T> list2); static boolean isNotEmpty(@NonNull final List<T> list); }### Answer:
@Test public void unionResultsInSecondListAppendedToFirstListRespectingTheOrder() { final List<Object> list1 = new ArrayList<Object>() {{ add(mockObject1); add(mockObject2); add(mockObject3); add(mockObject4); }}; final List<Object> list2 = new ArrayList<Object>() {{ add(mockObject5); add(mockObject6); }}; final List<Object> result = ListUtils.union(list1, list2); Assertions.assertThat(result).containsExactly(mockObject1, mockObject2, mockObject3, mockObject4, mockObject5, mockObject6); }
@Test public void unionDoesNotRemoveDuplicates() { final List<Object> list1 = new ArrayList<Object>() {{ add(mockObject5); add(mockObject6); }}; final List<Object> list2 = new ArrayList<Object>() {{ add(mockObject5); add(mockObject6); }}; final List<Object> result = ListUtils.union(list1, list2); Assertions.assertThat(result).containsExactly(mockObject5, mockObject6, mockObject5, mockObject6); } |
### Question:
ODFValidatorService implements Validate { public ServiceDescription describe() { ServiceDescription.Builder mds = new ServiceDescription.Builder(NAME, Validate.class.getCanonicalName()); mds.description("A validator for ODF file, based on the ODF Toolkit project ODF Validator."); mds.author("Andrew Jackson <[email protected]>"); try { mds.furtherInfo(new URI("http: } catch (URISyntaxException e) { } mds.classname(this.getClass().getCanonicalName()); return mds.build(); } ServiceDescription describe(); ValidateResult validate(DigitalObject dob, URI format, List<Parameter> parameters); static final String NAME; }### Answer:
@Test public void testDescribe() { ServiceDescription desc = ids.describe(); System.out.println("Recieved service description: " + desc.toXmlFormatted() ); assertTrue("The ServiceDescription should not be NULL.", desc != null ); } |
### Question:
ODFValidatorService implements Validate { public ValidateResult validate(DigitalObject dob, URI format, List<Parameter> parameters) { return ODFValidatorWrapper.validateODF(dob,format); } ServiceDescription describe(); ValidateResult validate(DigitalObject dob, URI format, List<Parameter> parameters); static final String NAME; }### Answer:
@Test public void testValidate() throws MalformedURLException, URISyntaxException { testValidateThis(new DigitalObject.Builder( Content.byValue(new File("tests/test-files/documents/test_odt/v11/test_file_v11.odt") ) ).build() , new URI("planets:fmt/ext/odf"), true); testValidateThis(new DigitalObject.Builder( Content.byReference(new File("PC/odf-toolkit/src/test/resources/HelloWorld.doc") ) ).build() , new URI("planets:fmt/ext/odf"), true); testValidateThis(new DigitalObject.Builder( Content.byReference(new File("PC/odf-toolkit/src/test/resources/HelloWorld.sxw") ) ).build() , new URI("planets:fmt/ext/odf"), false); testValidateThis(null, new URI("http: testValidateThis(new DigitalObject.Builder( Content.byReference(new URL("http: true); } |
### Question:
ToolSpec { String toXMlFormatted() throws JAXBException, UnsupportedEncodingException { Marshaller m = jc.createMarshaller(); m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); ByteArrayOutputStream bos = new ByteArrayOutputStream(); m.marshal(this, bos); return bos.toString("UTF-8"); } String getTool(); void setTool(String tool); Version getVersion(); void setVersion(Version version); Install getInstall(); void setInstall(Install install); List<Var> getEnv(); void setEnv(List<Var> env); List<Var> getVar(); void setVar(List<Var> var); List<Convert> getConvert(); void setConvert(List<Convert> convert); List<Validate> getValidate(); void setValidate(List<Validate> validate); static ToolSpec fromInputStream( InputStream input ); }### Answer:
@Test public void testToXMlFormatted() { fail("Not yet implemented"); } |
### Question:
ToolSpec { public static ToolSpec fromInputStream( InputStream input ) throws FileNotFoundException, JAXBException { Unmarshaller u = jc.createUnmarshaller(); return (ToolSpec) u.unmarshal(new StreamSource(input)); } String getTool(); void setTool(String tool); Version getVersion(); void setVersion(Version version); Install getInstall(); void setInstall(Install install); List<Var> getEnv(); void setEnv(List<Var> env); List<Var> getVar(); void setVar(List<Var> var); List<Convert> getConvert(); void setConvert(List<Convert> convert); List<Validate> getValidate(); void setValidate(List<Validate> validate); static ToolSpec fromInputStream( InputStream input ); }### Answer:
@Test public void testFromInputstream() throws FileNotFoundException, JAXBException { ToolSpec kakadu = ToolSpec.fromInputStream( ToolSpec.class.getResourceAsStream("/toolspecs/kakadu.ptspec")); System.out.println("Tools "+kakadu.getTool()); ToolSpec jhove2 = ToolSpec.fromInputStream( ToolSpec.class.getResourceAsStream("/toolspecs/jhove2.ptspec")); System.out.println("Tools "+jhove2.getTool()); ToolSpec isobuster = ToolSpec.fromInputStream( ToolSpec.class.getResourceAsStream("/toolspecs/isobuster.ptspec")); System.out.println("Tools "+isobuster.getTool()); } |
### Question:
PivotalTrackerUtil { public String pivotalTrackerAdd( String url, String projectId, String token, String name, String storyType, String description) { PivotalTrackerAPI pivotalTrackerTarget = webAPIResolver.getWebAPI(url, PivotalTrackerAPI.class); PivotalTrackerResponse bugData = pivotalTrackerTarget.addBug( token, projectId, MapBuilder.<String, String>newHashMap() .with("name", name) .with("story_type", storyType) .with("description", description) .build()); log.info("Bug Report url = " + bugData.url); return bugData.url; } PivotalTrackerUtil(WebAPIResolver resolver); String pivotalTrackerAdd(
String url,
String projectId,
String token,
String name,
String storyType,
String description); }### Answer:
@Test public void testPivotalTracker() { PivotalTrackerUtil pivotalTrackerUtil = new PivotalTrackerUtil(new MyWebAPIResolver()); final String pivotalTrackerData = pivotalTrackerUtil.pivotalTrackerAdd( "https: "2016043", "ff33d6e6e138d66834a52be6bf19f6f1", "Best Awesome Bug", "bug", "The most awesome ever test of adding bug"); Assert.assertEquals("https: } |
### Question:
Pair implements Serializable { public K getObject1() { return key; } Pair(K key, V value); K getKey(); void setKey(K key); V getValue(); void setValue(V value); K getObject1(); V getObject2(); @Override int hashCode(); @SuppressWarnings("rawtypes") @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testObject1() throws Exception { final Pair<String, String> pair1 = new Pair("A", "D"); assertTrue(pair1.getObject1() instanceof String); assertTrue("A".equalsIgnoreCase(pair1.getObject1())); } |
### Question:
Pair implements Serializable { public V getObject2() { return value; } Pair(K key, V value); K getKey(); void setKey(K key); V getValue(); void setValue(V value); K getObject1(); V getObject2(); @Override int hashCode(); @SuppressWarnings("rawtypes") @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testObject2() throws Exception { final Pair<String, String> pair1 = new Pair("A", "D"); assertTrue(pair1.getObject2() instanceof String); assertTrue("D".equalsIgnoreCase(pair1.getObject2())); } |
### Question:
Pair implements Serializable { @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(key); builder.append(':'); builder.append(value); return builder.toString(); } Pair(K key, V value); K getKey(); void setKey(K key); V getValue(); void setValue(V value); K getObject1(); V getObject2(); @Override int hashCode(); @SuppressWarnings("rawtypes") @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testToString() throws Exception { final Pair<String, String> pair = new Pair("Key", "Value"); assertEquals("Key:Value", pair.toString()); } |
### Question:
VariableTime implements IVariableTime { public VariableTime( Integer minute, Integer hour, Integer dayOfWeek, Integer dayOfMonth, Integer month, Integer year) { this.minute = minute; this.hour = hour; this.dayOfWeek = dayOfWeek; this.dayOfMonth = dayOfMonth; this.month = month; this.year = year; } VariableTime(
Integer minute,
Integer hour,
Integer dayOfWeek,
Integer dayOfMonth,
Integer month,
Integer year); Integer getDayOfMonth(); Integer getDayOfWeek(); Integer getYear(); Integer getMonth(); Integer getHour(); Integer getMinute(); }### Answer:
@Test public void testVariableTime() { final VariableTime vt = new VariableTime(20, 4, 3, 4, 12, 1972); assertTrue(vt.getMinute() == 20); assertTrue(vt.getHour() == 4); assertTrue(vt.getDayOfWeek() == 3); assertTrue(vt.getDayOfMonth() == 4); assertTrue(vt.getMonth() == 12); assertTrue(vt.getYear() == 1972); } |
### Question:
PrettyDuration { public static String prettyDuration(long milliseconds) { long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds); milliseconds -= TimeUnit.MINUTES.toMillis(minutes); long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds); milliseconds -= TimeUnit.SECONDS.toMillis(seconds); StringBuilder sb = new StringBuilder(); sb.append(minutes); sb.append("m "); sb.append(seconds); sb.append("s "); sb.append(milliseconds); sb.append("ms"); return (sb.toString()); } static String prettyDuration(long milliseconds); }### Answer:
@Test public void testPrettyDuration() throws Exception { assertEquals("0m 1s 0ms", PrettyDuration.prettyDuration(1000)); } |
### Question:
SqlBuilder { public String getSqlString() { return command + (command.equals(DELETE) ? "" : selection) + FROM + tableName + getWhereClauseString() + getQuerySuffixString(); } SqlBuilder(String tableName); SqlBuilder(String tableName, String command); static String getSortOrderString(SqlQueryOrder.SortOrder sortOrder); SqlBuilder addCaseInsensitiveLikeCondition(String fieldName, String fieldValue); SqlBuilder addInCondition(String fieldName, Collection<String> values); SqlBuilder addMultipleOrConditionOfKeyValuePairs(
String keyColumnName,
String valueColumnName,
Map<String, String> keyValuePairs); SqlBuilder addCondition(String condition); SqlBuilder addQueryParam(Object param); SqlBuilder addQueryParams(Collection<Object> params); String getSqlString(); SqlBuilder setSelection(String selection); SqlBuilder addQuerySuffix(String querySuffix); SqlBuilder addQuerySuffixWithParam(String suffix, Object param); @NoJavadoc // TODO add JavaDoc SqlBuilder addOrderByClause(SqlQueryOrder sqlQueryOrder); List<Object> getQueryParams(); @Override String toString(); String build(); static final int MAX_ITEMS_FOR_IN_CLAUSE; static final String SELECT; static final String DELETE; }### Answer:
@Test public void testSimpleQuery() { SqlBuilder builder = new SqlBuilder("table"); Assert.assertEquals("wrong query", "select * from table", builder.getSqlString()); } |
### Question:
PersistentMessagingServer implements Connection { @Override public void pause() { queues.values().forEach(Queue::pause); } PersistentMessagingServer(MessagePersister persister); @Override void createQueue(
String queueName,
int memoryBufferMaxMessages,
int secondsToSleepBetweenMessageRetries,
int maxRetries); @Override void sendMessage(String queueName, InputStream messageBody, Map<String, String> headers); @Override void sendMessage(String queueName, Consumer<OutputStream> writer, Map<String, String> headers); @Override void subscribe(String queueName, String consumerName, Consumer<Message> messageConsumer); @Override void unsubscribe(String queueName, String consumerName); @Override void pause(); @Override void pause(String queueName); @Override void start(); @Override void start(String queueName); }### Answer:
@Test public void testPause() throws InterruptedException { Connection connection = createConnectionWithQueue(1000, 2, 1); AtomicInteger count = createSomeMessyQueues(connection); Thread.sleep(55L); connection.pause(); int countRightAfterPause = count.get(); System.out.println(countRightAfterPause); Thread.sleep(100L); System.out.println(count.get()); int countNow = count.get(); Assert.assertTrue("Messages should be drained from the queue", countNow > countRightAfterPause); Thread.sleep(100L); Assert.assertEquals("Messages should stopped being consumed as the queue is paused now", countNow, count.get()); Assert.assertTrue(countNow > 0 && countNow < 10000); } |
### Question:
PersistentMessagingServer implements Connection { @Override public void unsubscribe(String queueName, String consumerName) { getQueue(queueName).removeConsumer(consumerName); } PersistentMessagingServer(MessagePersister persister); @Override void createQueue(
String queueName,
int memoryBufferMaxMessages,
int secondsToSleepBetweenMessageRetries,
int maxRetries); @Override void sendMessage(String queueName, InputStream messageBody, Map<String, String> headers); @Override void sendMessage(String queueName, Consumer<OutputStream> writer, Map<String, String> headers); @Override void subscribe(String queueName, String consumerName, Consumer<Message> messageConsumer); @Override void unsubscribe(String queueName, String consumerName); @Override void pause(); @Override void pause(String queueName); @Override void start(); @Override void start(String queueName); }### Answer:
@Test public void testUnsubscribe() throws InterruptedException { Connection connection = createConnectionWithQueue(1000, 2, 1); AtomicInteger count = createSomeMessyQueues(connection); Thread.sleep(55L); IntStream.range(0,30).forEach((i) -> connection.unsubscribe("q1", "Saruman" + i)); int countRightAfterPause = count.get(); System.out.println(countRightAfterPause); Thread.sleep(100L); System.out.println(count.get()); int countNow = count.get(); Assert.assertTrue("Messages should be drained from the queue until finished un-subscribing", countNow > countRightAfterPause); Thread.sleep(100L); Assert.assertEquals("Messages should stopped being consumed as the queue is has no subscribersnow", countNow, count.get()); Assert.assertTrue(countNow > 0 && countNow < 10000); } |
### Question:
Task { @Override public String toString() { return "Task{" + "id=" + id + ", name='" + name + '\'' + ", executionTime=" + executionTime + ", payload='" + payload + '\'' + '}'; } Task(
String id,
String name,
long executionTime,
String payload); private Task(); final String getId(); final String getName(); final long getExecutionTime(); void setExecutionTime(long executionTime); final String getPayload(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void serializeDeserializeTaskTest() throws Exception { Task task = new Task(UUID.randomUUID().toString(), "task", System.currentTimeMillis(), "payload"); Object serializedTask = PostgresUtil.objectToJsonBParameter(task, null); Task deserializedTask = PostgresUtil.fromJsonB(((PGobject) serializedTask).getValue(), Task.class); Assert.assertEquals(task, deserializedTask); }
@Test public void serializeDeserializeOneOffTaskTest() throws Exception { String id = UUID.randomUUID().toString(); OneOffTask task = new OneOffTask(id, "task", System.currentTimeMillis(), "payload", "consumer"); Object serializedTask = PostgresUtil.objectToJsonBParameter(task, null); Task deserializedTask = PostgresUtil.fromJsonB(((PGobject) serializedTask).getValue(), Task.class); Assert.assertEquals(task, deserializedTask); }
@Test public void serializeDeserializeRecurringTaskTest() throws Exception { String id = UUID.randomUUID().toString(); Task task = new RecurringTask(id, "task", System.currentTimeMillis(), "payload", "function", 5); Object serializedTask = PostgresUtil.objectToJsonBParameter(task, null); Task deserializedTask = PostgresUtil.fromJsonB(((PGobject) serializedTask).getValue(), Task.class); Assert.assertEquals(task, deserializedTask); } |
### Question:
DockerArtifactRegistryImpl implements ArtifactRegistryApi { @Override public Collection<String> listVersions(String artifactId) { try { if (!artifactId.contains("/")) { artifactId = "library/" + artifactId; } final String registryUrl = this.url + "/v2/repositories/" + artifactId + "/tags/"; log.info("fetching tags from {}", registryUrl); final Map res = webAPIResolver .getWebTarget(registryUrl) .request(MediaType.APPLICATION_JSON_TYPE) .buildGet() .invoke(Map.class); return ((List<Map>) res.get("results")) .stream() .map(o -> (String) o.get("name")) .collect(Collectors.toList()); } catch (Exception ex) { log.warn("oh well.. couldn't fetch from registry" + ex.getMessage(), ex); return Collections.singleton("latest"); } } DockerArtifactRegistryImpl(WebAPIResolver webAPIResolver, String url, String username, String password); @Override Collection<String> listVersions(String artifactId); }### Answer:
@Test public void testMe() { new ResteasyJackson2Provider(); final DockerArtifactRegistryImpl dockerArtifactRegistry = new DockerArtifactRegistryImpl(new TestResolver(), "https: final Collection<String> mysql = dockerArtifactRegistry.listVersions("mysql"); mysql.forEach(System.out::println); Assert.assertTrue(mysql.contains("latest")); } |
### Question:
ApplicationCopyEventRepositoryImpl implements ApplicationCopyEventRepository, ServiceLifecycle { @Override public List<ApplicationCopyEvent> listOrderedEvents(UUID copyId) { return nqs.getList(SQL_SELECT_EVENTS_BY_APP_COPY_ID, this::convertRow, Collections.singletonList(copyId)); } ApplicationCopyEventRepositoryImpl(DataSource dataSource); ApplicationCopyEventRepositoryImpl(); @Override UUID subscribe(Consumer<ApplicationCopyEvent> consumer); @Override void unSubscribe(UUID subscriberId); @Override List<ApplicationCopyEvent> listOrderedEvents(UUID copyId); @Override Map<UUID, List<ApplicationCopyEvent>> listByAppInstanceId(UUID appInstanceId); @Override ApplicationCopyEvent store(ApplicationCopyEvent appCopyEvent); @Override Collection<ApplicationCopyEvent> store(Collection<ApplicationCopyEvent> appCopyEvents); @Override void init(Context context); @Override void shutDown(); }### Answer:
@Test public void testNonExistentCopyId() { UUID copyId = UUID.randomUUID(); Collection<ApplicationCopyEvent> events = appCopyEventRepo.listOrderedEvents(copyId); Assert.assertEquals(0, events.size()); } |
### Question:
ApplicationCopyEventRepositoryImpl implements ApplicationCopyEventRepository, ServiceLifecycle { @Override public Map<UUID, List<ApplicationCopyEvent>> listByAppInstanceId(UUID appInstanceId) { return nqs.getMapOfList( SQL_SELECT_EVENTS_BY_APP_INSTANCE_ID, new UuidNativeQueryConverter("appCopyId"), this::convertRow, Collections.singletonList(appInstanceId) ); } ApplicationCopyEventRepositoryImpl(DataSource dataSource); ApplicationCopyEventRepositoryImpl(); @Override UUID subscribe(Consumer<ApplicationCopyEvent> consumer); @Override void unSubscribe(UUID subscriberId); @Override List<ApplicationCopyEvent> listOrderedEvents(UUID copyId); @Override Map<UUID, List<ApplicationCopyEvent>> listByAppInstanceId(UUID appInstanceId); @Override ApplicationCopyEvent store(ApplicationCopyEvent appCopyEvent); @Override Collection<ApplicationCopyEvent> store(Collection<ApplicationCopyEvent> appCopyEvents); @Override void init(Context context); @Override void shutDown(); }### Answer:
@Test public void testNonExistentInstanceId() { UUID instId = UUID.randomUUID(); Map<UUID, List<ApplicationCopyEvent>> events = appCopyEventRepo.listByAppInstanceId(instId); Assert.assertEquals(0, events.keySet().size()); } |
### Question:
SiteRepositoryImpl implements SiteRepository, ServiceLifecycle { @Override public Site load() { final Site site = new Site(siteName); populateSite(site); return site; } SiteRepositoryImpl(); SiteRepositoryImpl(
String siteName,
DataSource dataSource,
SerializationWriter<DbSite> writer,
SerializationReader<DbSite> reader,
ArtifactRegistryFactory artifactRegistryFactory,
WebAPIResolver resolver); @Override void init(Context context); @Override void shutDown(); @Override Site load(); @Override void persist(Site site); }### Answer:
@Test public void testEmptyCreated() { final Site empty = siteRepository.load(); Assert.assertTrue(empty.getCopyRepositories().isEmpty()); Assert.assertTrue(empty.getDsbList().isEmpty()); Assert.assertTrue(empty.getPsbs().isEmpty()); Assert.assertEquals("my-site", empty.getName()); }
@Test public void testAdd() { persistSite(); Site newSite = siteRepository.load(); assertSiteEquals(newSite); } |
### Question:
ErrorMessageHeaderWriter implements SerializationWriter<ErrorMessageHeader> { @Override public void writeObject(ErrorMessageHeader errorMessageHeader, OutputStream outputStream) throws ErrorMessageHeaderSerializationException { ObjectMapper mapper = new ObjectMapper(); try { mapper.writeValue(outputStream, errorMessageHeader); } catch (Exception e) { String message = "Could not serialize a " + ErrorMessageHeader.class.getName() + " object. Cause: " + e.getMessage(); throw new ErrorMessageHeaderSerializationException(message, e); } } @Override void writeObject(ErrorMessageHeader errorMessageHeader, OutputStream outputStream); }### Answer:
@Test public void testWriteErrorMessageHeader() { ErrorMessageHeader errorMessageHeader = new ErrorMessageHeader("microservice-1-uri", 1456485443905L, 404, "Service unavailable"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new ErrorMessageHeaderWriter().writeObject(errorMessageHeader, outputStream); String jsonResult = outputStream.toString(); JsonFluentAssert actualJson = JsonFluentAssert.assertThatJson(jsonResult); InputStream expectedJson = getClass().getClassLoader().getResourceAsStream("errors/serialization/errormessageheader.json"); String expectedJSON = null; try { expectedJSON = ReadFile.getFileContents(expectedJson).toString(); } catch (IOException e) { e.printStackTrace(); } actualJson.hasSameStructureAs(expectedJSON); actualJson.isEqualTo(expectedJSON); }
@Test public void testException() { ErrorMessageHeaderWriter writer = new ErrorMessageHeaderWriter(); try { writer.writeObject(null, null); } catch (ErrorMessageHeaderSerializationException e) { String message = e.getMessage(); Assert.assertTrue(message.startsWith("Could not serialize ")); } } |
### Question:
JiraQueryUtil { public UIJiraLoginResponse queryJira(String url, String userName, String password) { JiraAPI jiraTarget = webAPIResolver.getWebAPI(url, JiraAPI.class); JiraSession session = jiraTarget.autenticate( MapBuilder.<String, String>newHashMap() .with("username", userName) .with("password", password) .build()) .session; if (!"JSESSIONID".equals(session.name)) { throw new InternalServerErrorException("jira session not identified by JSESSIONID but by " + session.name); } return new UIJiraLoginResponse( jiraTarget.listProjects(session.value).stream() .map(o -> new UIJiraLoginResponseProjects(o.id, o.name)) .collect(Collectors.toList()), jiraTarget.listIssueTypes(session.value).stream() .map(o -> new UIJiraLoginResponseProjects(o.id, o.name)) .collect(Collectors.toList()) ); } JiraQueryUtil(WebAPIResolver resolver); UIJiraLoginResponse queryJira(String url, String userName, String password); }### Answer:
@Test public void testJiraQuery() { JiraQueryUtil jiraQueryUtil = new JiraQueryUtil(new MyWebAPIResolver()); final UIJiraLoginResponse jiraData = jiraQueryUtil.queryJira("http: Assert.assertEquals(1, jiraData.getIssueTypes().size()); Assert.assertEquals("iId", jiraData.getIssueTypes().iterator().next().getId()); Assert.assertEquals("iName", jiraData.getIssueTypes().iterator().next().getName()); Assert.assertEquals(1, jiraData.getProjects().size()); Assert.assertEquals("pId", jiraData.getProjects().iterator().next().getId()); Assert.assertEquals("pName", jiraData.getProjects().iterator().next().getName()); }
@Test public void testInvalidSession() { JiraQueryUtil jiraQueryUtil = new JiraQueryUtil(new MyWebAPIResolver(false)); try { jiraQueryUtil.queryJira("http: Assert.fail("Should have failed"); } catch (InternalServerErrorException ex) { } } |
### Question:
PathUtilities { static boolean isValid(String path) { Objects.requireNonNull(path, "Path can't be null"); if ("/".equals(path)) { return true; } if (path.startsWith("/")) { path = path.substring(1); } for (String part : split(path)) { if (!isPathNameValid(part)) { return false; } } return true; } }### Answer:
@Test public void testPathsWithValidCharacters() { assertTrue(PathUtilities.isValid("level1")); assertTrue(PathUtilities.isValid("level-1")); assertTrue(PathUtilities.isValid("level-1/level-2/level3")); assertTrue(PathUtilities.isValid("1/2/a")); }
@Test public void testThatPathWithOnlyHyphenIsInvalid() { assertFalse(PathUtilities.isValid("level1/-/level3")); assertFalse(PathUtilities.isValid("-")); }
@Test public void testThatPathWithSpaceIsInvalid() { assertFalse(PathUtilities.isValid("level 1")); }
@Test public void testThatPathWithNoneAlphaNumericOrHyphenIsInvalid() { assertFalse(PathUtilities.isValid("apple_level")); assertFalse(PathUtilities.isValid("category%23/apple")); }
@Test public void testThatPathStartingWithSeparatorIsValid() { assertTrue(PathUtilities.isValid("/apple/ball")); }
@Test public void testRootPathIsValid() { assertTrue(PathUtilities.isValid("/")); } |
### Question:
SavedImageRepositoryImpl extends AbstractHubRepositoryImpl implements SavedImageRepository, ServiceLifecycle { @Override public Collection<DBSavedImage> list() { return nqs.getList(SQL_SELECT, this::convertRow); } SavedImageRepositoryImpl(); SavedImageRepositoryImpl(DataSource dataSource); @Override void init(Context context); @Override void pause(); @Override void resume(); @Override void shutDown(); @Override DBSavedImage get(UUID savedImageId); @Override Collection<DBSavedImage> findByAppTemplateId(UUID appTemplateId); @Override void add(DBSavedImage savedImage); @Override Collection<DBSavedImage> list(); @Override void updateImageState(UUID savedImageId, DBSavedImage.DBSavedImageState state); }### Answer:
@Test public void testCreate() throws DuplicateResourceException { UUID id = UUID.randomUUID(); final DBSavedImage newImage = createAndVerify(id, "my Image"); final Collection<DBSavedImage> list = savedImageRepository.list(); Assert.assertEquals("Must be exactly one template", 1, list.size()); final DBSavedImage fromList = list.iterator().next(); Assert.assertNotNull(fromList); assertEquals(newImage, fromList); } |
### Question:
SchemaBootstrapScript { @NoJavadoc public Reader getScriptReader() throws IOException { StringReader reader; if (scriptContent != null) { reader = new StringReader(scriptContent.toString()); } else { InputStream resourceAsStream = Objects.requireNonNull( this.getClass().getClassLoader().getResourceAsStream(resourceLocation), "Invalid resource path provided for sql file, resource could not be located: " + resourceLocation); reader = new StringReader(IOUtils.toString(resourceAsStream)); } return reader; } SchemaBootstrapScript(String resourceLocation, String description, int schemaVersion); SchemaBootstrapScript(StringBuilder scriptContent, String description, int schemaVersion); String getDescription(); int getSchemaVersion(); @NoJavadoc Reader getScriptReader(); }### Answer:
@Test public void testGetScriptReaderFromFile() throws Exception { schemaBootstrapScript = new SchemaBootstrapScript("test.sql", "test", 1); final Reader reader = schemaBootstrapScript.getScriptReader(); final List<String> lines = IOUtils.readLines(reader); assertTrue(reader instanceof StringReader); assertTrue(lines.equals(Arrays.asList(EXPECTED.split("\n")))); }
@Test public void testGetScriptReaderFromStringBuilder() throws Exception { final StringBuilder stringBuilder = new StringBuilder(EXPECTED); schemaBootstrapScript = new SchemaBootstrapScript(stringBuilder, "test", 1); final Reader reader = schemaBootstrapScript.getScriptReader(); assertTrue(reader instanceof StringReader); assertEquals(EXPECTED, IOUtils.toString(reader)); } |
### Question:
Timer { public Collection<String> list() { return jobs.keySet(); } Timer(String name, MetricsRegistry registry); void add(String name, Runnable runnable, int seconds, Date nextRun); void add(String name, Runnable runnable, int seconds); void remove(String name); Collection<String> list(); void pause(); void resume(); void stop(); void start(); }### Answer:
@Test public void testThatTimerSupportsAddingTasks() { Assert.assertTrue(timer.list().contains(TASK1)); Assert.assertTrue(timer.list().contains(TASK2)); } |
### Question:
Timer { public void start() { executor.execute(this::process); } Timer(String name, MetricsRegistry registry); void add(String name, Runnable runnable, int seconds, Date nextRun); void add(String name, Runnable runnable, int seconds); void remove(String name); Collection<String> list(); void pause(); void resume(); void stop(); void start(); }### Answer:
@Test public void testThatTasksRunCorrectNumberOfTimes() throws Exception { timer.start(); Thread.sleep(5 * 1000); Assert.assertEquals(3, sensing.get(TASK1).size()); Assert.assertEquals(2, sensing.get(TASK2).size()); }
@Test public void testThatMetricsIsUpdated() throws Exception { timer.start(); Thread.sleep(5 * 1000); Assert.assertEquals(2, registry.getRegistry().getTimers().size()); } |
### Question:
TempFileSystemBlobStore implements BlobStore { @Override public void update(String namespace, String key, Map<String, String> headers, InputStream blob) throws ObjectKeyFormatException, IllegalStoreStateException { try { delete(namespace, key); create(namespace, key, headers, blob); } catch (DuplicateObjectKeyException e) { log.error( "Duplicate keys happened. most likely something wrong with implementation. " + "This should never happens.", e); } } TempFileSystemBlobStore(); void create(String namespace, String key, Map<String, String> headers, final InputStream blob); @Override void create(String namespace, String key, Map<String, String> headers, BlobWriter blobWriter); @Override void update(String namespace, String key, Map<String, String> headers, InputStream blob); @Override void update(String namespace, String key, Map<String, String> headers, BlobWriter blobWriter); @Override void moveNameSpace(final String oldNamespace, final String key, final String newNamespace); void ren(File[] files, String target, String replacement); @Override void readBlob(final String namespace, final String key, BlobReader reader); @Override void readBlob(final String namespace, final String key, final OutputStream out); @Override Map<String, String> readHeaders(final String namespace, final String key); @Override void delete(int expirySeconds); @Override void delete(final String namespace, final String key); FilenameFilter getHeadersFilenameFilter(String namespace, String key); FilenameFilter getFilenameFilter(String namespace, String key); @Override boolean isExists(final String namespace, final String key); @Override Collection<BlobStoreLink> list(); }### Answer:
@Test public void testIllegalKey() { BlobStore bs = new TempFileSystemBlobStore(); InputStream inputStream = null; try { bs.update(".", "!", null, inputStream); assertTrue("illegal key passed as valid", false); } catch (ObjectKeyFormatException e) { assertTrue(true); } catch (IllegalStoreStateException e) { assertTrue("IllegalStoreStateException should not be thrown", false); } } |
### Question:
ReadFile { public static String getFileContentsFromResource(String resourceLocation) throws IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); return getFileContentsFromResource(resourceLocation, classLoader); } static String getFileContentsFromResource(String resourceLocation); static String getFileContentsFromResource(String resourceLocation, ClassLoader classLoader); static StringBuilder getFileContentsFromResourceAsStringBuilder(
String resourceLocation,
ClassLoader classLoader); static String getFileContents(File file); static StringBuilder getFileContents(InputStream inputStream); static StringBuilder getFileContents(Reader reader); }### Answer:
@Test(expected = FileNotFoundException.class) public void getFileContentsFromResourceTest() throws IOException { final String result = ReadFile.getFileContentsFromResource(TESTFILE); assertNotNull(result); assertTrue(result.contains("wheezles")); ReadFile.getFileContentsFromResource(BADFILE); assertFalse(true); }
@Test(expected = FileNotFoundException.class) public void getFileContentsFromResourceWithClassloaderTest() throws IOException { final String result = ReadFile.getFileContentsFromResource(TESTFILE, Thread.currentThread().getContextClassLoader()); assertNotNull(result); assertTrue(result.contains("wheezles")); ReadFile.getFileContentsFromResource(BADFILE, Thread.currentThread().getContextClassLoader()); assertFalse(true); } |
### Question:
MicroServiceMetricsResource extends MicroServiceResource implements MicroServiceMetricsAPI { @Override public Response getMetricsOutput() { StreamingOutput stream = outputStream -> mapper .writerWithDefaultPrettyPrinter() .writeValue(outputStream, getMicroServiceApplication().getMicroServiceContext().getMetricsRegistry()); return Response .ok(stream, MediaType.APPLICATION_JSON_TYPE) .header("Cache-Control", "must-revalidate,no-cache,no-store") .build(); } MicroServiceMetricsResource(); @Override Response getMetricsOutput(); @Override Map<String, List> getDsMetrics(@PathParam("ds") String ds); }### Answer:
@Test @SuppressWarnings("unchecked") public void getMetricsOutput() throws URISyntaxException, IOException { final MockHttpResponse response = get(MicroServiceMetricsAPI.BASE_URI, MediaType.APPLICATION_JSON_TYPE); assertEquals(HttpStatus.SC_OK, response.getStatus()); final Map<String, ?> json = json(response); System.out.println(json); assertEquals("mock-api", json.get("name")); final Map<String, ?> metrics = (Map<String, ?>) json.get("metrics"); assertEquals("3.0.0", metrics.get("version")); } |
### Question:
ReadFile { public static StringBuilder getFileContentsFromResourceAsStringBuilder( String resourceLocation, ClassLoader classLoader) throws IOException { InputStream inputStream = classLoader.getResourceAsStream(resourceLocation); if (inputStream == null) { throw new FileNotFoundException("Could not find resource file at path '" + resourceLocation + "'"); } return getFileContents(inputStream); } static String getFileContentsFromResource(String resourceLocation); static String getFileContentsFromResource(String resourceLocation, ClassLoader classLoader); static StringBuilder getFileContentsFromResourceAsStringBuilder(
String resourceLocation,
ClassLoader classLoader); static String getFileContents(File file); static StringBuilder getFileContents(InputStream inputStream); static StringBuilder getFileContents(Reader reader); }### Answer:
@Test public void getFileContentsFromResourceAsStringBuilderTest() throws IOException { final StringBuilder sb = ReadFile.getFileContentsFromResourceAsStringBuilder( TESTFILE, Thread.currentThread().getContextClassLoader()); assertFalse(sb.length() == 0); } |
### Question:
CountingReader extends Reader { @Override public boolean ready() throws IOException { return delegate.ready(); } CountingReader(Reader delegate); @Override int read(CharBuffer target); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); int getCharCount(); }### Answer:
@Test public void ready() throws IOException { when(delegate.ready()).thenReturn(true); assertTrue(cut.ready()); verify(delegate).ready(); } |
### Question:
CountingReader extends Reader { @Override public boolean markSupported() { return false; } CountingReader(Reader delegate); @Override int read(CharBuffer target); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); int getCharCount(); }### Answer:
@Test public void markSupported() { assertFalse(cut.markSupported()); } |
### Question:
CountingReader extends Reader { @Override public void mark(int readAheadLimit) throws IOException { throw new IOException("mark() not supported"); } CountingReader(Reader delegate); @Override int read(CharBuffer target); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); int getCharCount(); }### Answer:
@Test(expected = IOException.class) public void mark() throws IOException { cut.mark(1000); } |
### Question:
CountingReader extends Reader { @Override public void reset() throws IOException { throw new IOException("reset() not supported"); } CountingReader(Reader delegate); @Override int read(CharBuffer target); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); int getCharCount(); }### Answer:
@Test(expected = IOException.class) public void reset() throws IOException { cut.reset(); } |
### Question:
CountingReader extends Reader { @Override public void close() throws IOException { delegate.close(); } CountingReader(Reader delegate); @Override int read(CharBuffer target); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); int getCharCount(); }### Answer:
@Test public void close() throws IOException { cut.close(); verify(delegate).close(); } |
### Question:
CountingReader extends Reader { public int getCharCount() { return charCount; } CountingReader(Reader delegate); @Override int read(CharBuffer target); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); int getCharCount(); }### Answer:
@Test public void getCharCountWithNoCharactersRead() { assertEquals(0, cut.getCharCount()); } |
### Question:
MicroServiceConfigurationResource extends MicroServiceResource implements MicroServiceConfigurationAPI { @Override public ServiceConfiguration getServiceConfiguration() { Context context = getMicroServiceApplication().getMicroServiceContext(); LoggerConfig loggerConfig = getLoggerConfig(context); List<ResourceConfig> inputQueues = getResourceConfigs(context.getQueuesManager().getManagedResources()); List<ResourceConfig> datasources = getResourceConfigs(context.getDatasourceManager().getManagedResources()); List<ResourceConfig> destinations = getResourceConfigs(context.getDestinationManager().getManagedResources()); List<ResourceConfig> blobStores = getResourceConfigs(context.getBlobStoreManager().getManagedResources()); List<ResourceConfig> serviceDependencies = getDependencyConfigs(context.getDependencyManager().getManagedResources()); List<ResourceConfig> externalResources = new ArrayList<>(); for (ResourceManager currExternalResourceManager : context.getExternalResourceManagers()) { externalResources.addAll(getResourceConfigs(currExternalResourceManager.getManagedResources())); } List<ParamConfig> paramsConfig = getParamConfigs(context); return new ServiceConfiguration( context.getMicroServiceName(), context.getServiceDescription(), context.getMicroServiceBaseURI(), loggerConfig, inputQueues, datasources, destinations, blobStores, serviceDependencies, externalResources, paramsConfig ); } @Override ServiceConfiguration getServiceConfiguration(); @Override Response setLogLevel(); }### Answer:
@Test @SuppressWarnings("unchecked") public void getServiceConfiguration() throws URISyntaxException, IOException { final MockHttpResponse response = get(MicroServiceConfigurationAPI.BASE_URI, MediaType.APPLICATION_JSON_TYPE); assertEquals(HttpStatus.SC_OK, response.getStatus()); final Map<String, ?> json = json(response); assertEquals("Mock Micro Service", json.get("name")); assertEquals(VERSION_NOT_AVAILABLE, json.get("version")); final List<Map<String, ?>> parameters = (List<Map<String, ?>>) json.get("parameters"); assertEquals("Expected 2 parameters, boo-timeout and health-check-period-in-seconds", 3, parameters.size()); } |
### Question:
PrefixReader extends Reader { @Override public boolean markSupported() { return false; } PrefixReader(char[] prefix, Reader delegate); PrefixReader(Object lock, char[] prefix, Reader delegate); @Override int read(CharBuffer target); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); }### Answer:
@Test public void markSupported() throws IOException { assertFalse(cut.markSupported()); } |
### Question:
ManagedMessageListenerImpl implements ManagedMessageListener { private void handleMessage(Message message, Context context, boolean isError) { ContextThreadLocal.setContext(context); Thread currentThread = Thread.currentThread(); String origThreadName = currentThread.getName(); MessageLoggingContext messageLoggingContext = buildMessageLoggingContext(message); Map<String, String> messageHeaderValuesForLogging = messageLoggingContext.getMessageHeaderValuesForLogging(); if (logger.isDebugEnabled()) { logger.debug("currentThread {}", currentThread); logger.debug("origThreadName {}", origThreadName); messageHeaderValuesForLogging.values().forEach(logger::debug); } try (CounterMetric autoCounter = activeJobs.inc(); StopWatch stopWatch = messageProcessingTimer.getStopWatch( new MapMetricState(messageHeaderValuesForLogging))) { queueExecutionState.setExecutionState(messageHeaderValuesForLogging); currentThread.setName(messageLoggingContext.getThreadName()); if (logger.isDebugEnabled()) { logger.debug("Executing message listener"); } if (isError) { handleErrorMessage(message, context); } else { messageListener.onMessage(message, context); } if (logger.isDebugEnabled()) { logger.debug("Done executing message listener"); } } catch (Exception ex) { logger.warn("Error while processing message. {}", ex.getMessage()); errorCounter.inc(); throw ex; } finally { try { queueExecutionState.clearExecutionState(); } finally { currentThread.setName(origThreadName); } } } ManagedMessageListenerImpl(
Context context,
MessageListener messageListener,
ManagedInputQueue managedQueue,
int threadOrdinal); @Override void onMessage(Message message, Context context); @Override void onErrorMessage(Message message, Context context); QueueExecutionState getQueueExecutionState(); }### Answer:
@Test public void testHandleMessage() { Message message = mock(Message.class); managedMessageListener.onMessage(message, context); verify(messageListener).onMessage(eq(message), eq(context)); } |
### Question:
PrefixReader extends Reader { @Override public void mark(int readAheadLimit) throws IOException { throw new IOException("mark() not supported"); } PrefixReader(char[] prefix, Reader delegate); PrefixReader(Object lock, char[] prefix, Reader delegate); @Override int read(CharBuffer target); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); }### Answer:
@Test(expected = IOException.class) public void mark() throws Exception { cut.mark(0); } |
### Question:
PrefixReader extends Reader { @Override public void reset() throws IOException { throw new IOException("reset() not supported"); } PrefixReader(char[] prefix, Reader delegate); PrefixReader(Object lock, char[] prefix, Reader delegate); @Override int read(CharBuffer target); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); }### Answer:
@Test(expected = IOException.class) public void reset() throws Exception { cut.reset(); } |
### Question:
PrefixReader extends Reader { @Override public void close() throws IOException { delegate.close(); } PrefixReader(char[] prefix, Reader delegate); PrefixReader(Object lock, char[] prefix, Reader delegate); @Override int read(CharBuffer target); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); }### Answer:
@Test public void close() throws Exception { final Reader mockDelegate = Mockito.mock(Reader.class); final PrefixReader cut = new PrefixReader(prefix, mockDelegate); cut.close(); verify(mockDelegate).close(); } |
### Question:
PrefixReader extends Reader { @Override public boolean ready() throws IOException { return delegate.ready(); } PrefixReader(char[] prefix, Reader delegate); PrefixReader(Object lock, char[] prefix, Reader delegate); @Override int read(CharBuffer target); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); }### Answer:
@Test public void ready() throws Exception { final Reader mockDelegate = Mockito.mock(Reader.class); final PrefixReader cut = new PrefixReader(prefix, mockDelegate); cut.ready(); verify(mockDelegate).ready(); } |
### Question:
EscapingReader extends Reader { @Override public long skip(long n) throws IOException { return delegate.skip(n); } EscapingReader(Reader delegate); EscapingReader(Object lock, Reader delegate); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); }### Answer:
@Test public void skip() throws IOException { cut.skip(999); verify(mockDelegate).skip(Mockito.anyLong()); } |
### Question:
EscapingReader extends Reader { @Override public boolean ready() throws IOException { return delegate.ready(); } EscapingReader(Reader delegate); EscapingReader(Object lock, Reader delegate); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); }### Answer:
@Test public void ready() throws IOException { cut.ready(); verify(mockDelegate).ready(); } |
### Question:
EscapingReader extends Reader { @Override public boolean markSupported() { return false; } EscapingReader(Reader delegate); EscapingReader(Object lock, Reader delegate); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); }### Answer:
@Test public void markSupported() throws IOException { assertFalse(cut.markSupported()); } |
### Question:
EscapingReader extends Reader { @Override public void mark(int readAheadLimit) throws IOException { throw new IOException("mark() not supported"); } EscapingReader(Reader delegate); EscapingReader(Object lock, Reader delegate); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); }### Answer:
@Test(expected = IOException.class) public void mark() throws IOException { cut.mark(0); } |
### Question:
EscapingReader extends Reader { @Override public void reset() throws IOException { throw new IOException("reset() not supported"); } EscapingReader(Reader delegate); EscapingReader(Object lock, Reader delegate); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); }### Answer:
@Test(expected = IOException.class) public void reset() throws IOException { cut.reset(); } |
### Question:
EscapingReader extends Reader { @Override public void close() throws IOException { delegate.close(); } EscapingReader(Reader delegate); EscapingReader(Object lock, Reader delegate); @Override int read(); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override boolean ready(); @Override boolean markSupported(); @Override void mark(int readAheadLimit); @Override void reset(); @Override void close(); }### Answer:
@Test public void close() throws IOException { cut.close(); verify(mockDelegate).close(); } |
### Question:
PortfolioServiceImpl implements PortfolioService { @Override public void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { if (amount <= 0) { resultHandler.handle(Future.failedFuture("Cannot sell " + quote.getString("name") + " - the amount must be " + "greater than 0")); return; } double price = amount * quote.getDouble("bid"); String name = quote.getString("name"); int current = portfolio.getAmount(name); if (current >= amount) { int newAmount = current - amount; if (newAmount == 0) { portfolio.getShares().remove(name); } else { portfolio.getShares().put(name, newAmount); } portfolio.setCash(portfolio.getCash() + price); sendActionOnTheEventBus("SELL", amount, quote, newAmount); resultHandler.handle(Future.succeededFuture(portfolio)); } else { resultHandler.handle(Future.failedFuture("Cannot sell " + amount + " of " + name + " - " + "not enough stocks " + "in portfolio")); } } PortfolioServiceImpl(Vertx vertx, ServiceDiscovery discovery, double initialCash); @Override void getPortfolio(Handler<AsyncResult<Portfolio>> resultHandler); @Override void evaluate(Handler<AsyncResult<Double>> resultHandler); @Override void buy(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler); @Override void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler); }### Answer:
@Test public void testYouCannotSellANegativeAmount(TestContext tc) { Async async = tc.async(); service.sell(-1, quote("A", 10, 20, 100), ar -> { tc.assertTrue(ar.failed()); async.complete(); }); } |
### Question:
MIC implements Serializable { @Nullable public static MIC parse (@Nullable final String sMIC) { if (StringHelper.hasNoText (sMIC)) return null; final StringTokenizer st = new StringTokenizer (sMIC, ", \t\r\n"); final String sMICBytes = st.nextToken (); final byte [] aMICBytes = Base64.safeDecode (sMICBytes); if (aMICBytes == null) throw new IllegalArgumentException ("Failed to base64 decode '" + sMICBytes + "'"); if (!st.hasMoreTokens ()) throw new IllegalArgumentException ("Separator after Base64 bytes is missing"); final String sAlgorithm = st.nextToken (); final ECryptoAlgorithmSign eDigestAlgorithm = ECryptoAlgorithmSign.getFromIDOrNull (sAlgorithm); if (eDigestAlgorithm == null) throw new IllegalArgumentException ("Failed to parse digest algorithm '" + sAlgorithm + "'"); return new MIC (aMICBytes, eDigestAlgorithm); } MIC(@Nonnull final byte [] aMICBytes, @Nonnull final ECryptoAlgorithmSign eDigestAlgorithm); @Nonnull byte [] micBytes(); @Nonnull ECryptoAlgorithmSign getDigestAlgorithm(); @Nonnull @Nonempty String getAsAS2String(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); @Nullable static MIC parse(@Nullable final String sMIC); }### Answer:
@Test public void testParseEmpty () { assertNull (MIC.parse (null)); assertNull (MIC.parse ("")); }
@Test (expected = IllegalArgumentException.class) public void testParseInvalidNoSep () { MIC.parse ("VGVzdA=="); }
@Test (expected = IllegalArgumentException.class) public void testParseInvalidNoAlg () { MIC.parse ("VGVzdA==, "); }
@Test (expected = IllegalArgumentException.class) public void testParseInvalidInvalidAlg () { MIC.parse ("VGVzdA==, blub"); } |
### Question:
TempSharedFileInputStream extends SharedFileInputStream { @Nonnull public static TempSharedFileInputStream getTempSharedFileInputStream (@Nonnull @WillClose final InputStream aIS, @Nonnull final String sName) throws IOException { final File aDest = storeContentToTempFile (aIS, sName); return new TempSharedFileInputStream (aDest); } private TempSharedFileInputStream(@Nonnull final File aFile); @Override void close(); void closeAll(); @Nonnull static TempSharedFileInputStream getTempSharedFileInputStream(@Nonnull @WillClose final InputStream aIS,
@Nonnull final String sName); }### Answer:
@Test public void testGetTempSharedFileInputStream () throws Exception { final String inData = "123456"; try (final InputStream is = new NonBlockingByteArrayInputStream (inData.getBytes ()); final SharedFileInputStream sis = TempSharedFileInputStream.getTempSharedFileInputStream (is, "myName"); final NonBlockingByteArrayOutputStream baos = new NonBlockingByteArrayOutputStream ()) { StreamHelper.copyInputStreamToOutputStream (sis, baos); final String res = baos.getAsString (StandardCharsets.ISO_8859_1); assertEquals ("read the data", inData, res); sis.close (); } } |
### Question:
TempSharedFileInputStream extends SharedFileInputStream { @Nonnull protected static File storeContentToTempFile (@Nonnull @WillClose final InputStream aIS, @Nonnull final String sName) throws IOException { final String sSuffix = FilenameHelper.getAsSecureValidASCIIFilename (StringHelper.hasText (sName) ? sName : "tmp"); final File aDestFile = File.createTempFile ("AS2TempSharedFileIS", sSuffix); try (final FileOutputStream aOS = new FileOutputStream (aDestFile)) { final MutableLong aCount = new MutableLong (0); StreamHelper.copyInputStreamToOutputStream (aIS, aOS, aCount); if (LOGGER.isInfoEnabled ()) { if (aCount.longValue () > 1024) LOGGER.info (aCount.longValue () + " bytes copied to " + aDestFile.getAbsolutePath ()); } } return aDestFile; } private TempSharedFileInputStream(@Nonnull final File aFile); @Override void close(); void closeAll(); @Nonnull static TempSharedFileInputStream getTempSharedFileInputStream(@Nonnull @WillClose final InputStream aIS,
@Nonnull final String sName); }### Answer:
@Test public void testStoreContentToTempFile () throws Exception { final String inData = "123456"; final String name = "xxy"; try (final InputStream is = new NonBlockingByteArrayInputStream (inData.getBytes (StandardCharsets.ISO_8859_1))) { final File file = TempSharedFileInputStream.storeContentToTempFile (is, name); assertTrue ("Temp file exists", file.exists ()); assertTrue ("Temp file name includes given name", file.getName ().indexOf (name) > 0); FileOperations.deleteFileIfExisting (file); } } |
### Question:
TempSharedFileInputStream extends SharedFileInputStream { @Override protected void finalize () throws Throwable { try { closeAll (); } catch (final Exception ex) { LOGGER.error ("Exception in finalize()", ex); } super.finalize (); } private TempSharedFileInputStream(@Nonnull final File aFile); @Override void close(); void closeAll(); @Nonnull static TempSharedFileInputStream getTempSharedFileInputStream(@Nonnull @WillClose final InputStream aIS,
@Nonnull final String sName); }### Answer:
@Test public void testFinalize () throws Exception { for (int i = 0; i < 10000; i++) { final String sSrcData = "123456"; try (final InputStream is = new NonBlockingByteArrayInputStream (sSrcData.getBytes (StandardCharsets.ISO_8859_1)); final TempSharedFileInputStream aSharedIS = TempSharedFileInputStream.getTempSharedFileInputStream (is, "myName")) { final int t = aSharedIS.read (); assertEquals (t, sSrcData.charAt (0)); aSharedIS.closeAll (); } } } |
### Question:
AS2IOHelper { @Nullable public static String getFilenameFromMessageID (@Nonnull final String sMessageID) { String s = StringHelper.removeAll (sMessageID, '<'); s = StringHelper.removeAll (s, '>'); return FilenameHelper.getAsSecureValidASCIIFilename (s); } private AS2IOHelper(); @Nonnull static FileOperationManager getFileOperationManager(); @Nonnull static File getDirectoryFile(@Nonnull final String sDirectory); @Nonnull @Nonempty static String getTransferRate(final long nBytes, @Nonnull final StopWatch aSW); @Nonnull static File getUniqueFile(@Nonnull final File aDir, @Nullable final String sFilename); static void handleError(@Nonnull final File aFile, @Nonnull final String sErrorDirectory); @Nonnull static File moveFile(@Nonnull final File aSrc,
@Nonnull final File aDestFile,
final boolean bOverwrite,
final boolean bRename); @Nullable static String getFilenameFromMessageID(@Nonnull final String sMessageID); @Nullable static String getSafeFileAndFolderName(@Nullable final String s); @Nonnull @ReturnsMutableCopy static byte [] getAllAsciiBytes(@Nonnull final String sString); @Nonnull static OutputStream getContentTransferEncodingAwareOutputStream(@Nonnull final OutputStream aOS,
@Nullable final String sEncoding); @Nonnull static InputStream getContentTransferEncodingAwareInputStream(@Nonnull final InputStream aIS,
@Nullable final String sEncoding); }### Answer:
@Test public void testGetFilenameFromMessageID () { assertNull (AS2IOHelper.getFilenameFromMessageID ("")); assertNull (AS2IOHelper.getFilenameFromMessageID ("<<<<>>>>")); assertEquals ("a", AS2IOHelper.getFilenameFromMessageID ("a")); assertEquals ("a", AS2IOHelper.getFilenameFromMessageID ("<a>")); assertEquals ("a", AS2IOHelper.getFilenameFromMessageID ("<<<<<a>>>>>")); assertEquals ("[email protected]", AS2IOHelper.getFilenameFromMessageID ("<<<<<[email protected]>>>>>")); } |
### Question:
AS2HttpHelper { @Nullable public static ContentType parseContentType (@Nullable final String sContentType) { if (StringHelper.hasText (sContentType)) { final String sRealContentType = RFC2616Codec.isMaybeEncoded (sContentType) ? new RFC2616Codec ().getDecodedAsString (sContentType) : sContentType; try { return new ContentType (sRealContentType); } catch (final ParseException ex) { if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Error parsing Content-Type '" + sContentType + "'", ex); } } return null; } private AS2HttpHelper(); @Nullable static ContentType parseContentType(@Nullable final String sContentType); @Nullable static String getCleanContentType(@Nullable final String sContentType); @Nonnull static InternetHeaders getAsInternetHeaders(@Nonnull final HttpHeaderMap aHeaders); }### Answer:
@Test public void testParseContentType () { assertNull (AS2HttpHelper.parseContentType (null)); assertNull (AS2HttpHelper.parseContentType ("")); assertNull (AS2HttpHelper.parseContentType (" ")); assertNull (AS2HttpHelper.parseContentType ("abc")); assertNull (AS2HttpHelper.parseContentType ("abc/")); assertNotNull (AS2HttpHelper.parseContentType ("abc/def")); assertNotNull (AS2HttpHelper.parseContentType ("abc/def; a=b")); assertNotNull (AS2HttpHelper.parseContentType (" abc/def ; a = b ")); assertNotNull (AS2HttpHelper.parseContentType ("abc/def; a=b; c=d")); assertNotNull (AS2HttpHelper.parseContentType (" abc/def ; a = b ; c = d ")); } |
### Question:
AS2HttpHelper { @Nullable public static String getCleanContentType (@Nullable final String sContentType) { final ContentType aCT = parseContentType (sContentType); return aCT != null ? aCT.toString () : null; } private AS2HttpHelper(); @Nullable static ContentType parseContentType(@Nullable final String sContentType); @Nullable static String getCleanContentType(@Nullable final String sContentType); @Nonnull static InternetHeaders getAsInternetHeaders(@Nonnull final HttpHeaderMap aHeaders); }### Answer:
@Test public void testGetCleanContentType () { assertNull (AS2HttpHelper.getCleanContentType (null)); assertNull (AS2HttpHelper.getCleanContentType ("")); assertNull (AS2HttpHelper.getCleanContentType (" ")); assertNull (AS2HttpHelper.getCleanContentType ("abc")); assertNull (AS2HttpHelper.getCleanContentType ("abc/")); assertEquals ("abc/def", AS2HttpHelper.getCleanContentType ("abc/def")); assertEquals ("abc/def; a=b", AS2HttpHelper.getCleanContentType ("abc/def; a=b")); assertEquals ("abc/def; a=b", AS2HttpHelper.getCleanContentType (" abc/def ; a = b ")); assertEquals ("abc/def; a=b; c=d", AS2HttpHelper.getCleanContentType ("abc/def; a=b; c=d")); assertEquals ("abc/def; a=b; c=d", AS2HttpHelper.getCleanContentType (" abc/def ; a = b ; c = d ")); } |
### Question:
MongoDBPartnershipFactory extends AbstractDynamicComponent implements IPartnershipFactory { @Override public EChange addPartnership (final Partnership aPartnership) throws AS2Exception { m_aPartnerships.insertOne (_toDocument (aPartnership)); return EChange.CHANGED; } MongoDBPartnershipFactory(final MongoCollection <Document> aPartnerships, final Logger aLogger); @Override EChange addPartnership(final Partnership aPartnership); @Override EChange removePartnership(final Partnership aPartnership); @Override void updatePartnership(final IMessage aMsg, final boolean bOverwrite); @Override void updatePartnership(final IMessageMDN aMdn, final boolean bOverwrite); @Override Partnership getPartnership(final Partnership aPartnership); @Override Partnership getPartnershipByName(final String sName); @Override ICommonsSet <String> getAllPartnershipNames(); @Override ICommonsList <Partnership> getAllPartnerships(); }### Answer:
@Test public void testAddPartnership () throws AS2Exception { final Partnership partnership = new Partnership ("Test partnership"); assertTrue (mongoDBPartnershipFactory.addPartnership (partnership).isChanged ()); assertEquals (1, collection.countDocuments ()); assertNotNull (mongoDBPartnershipFactory.getPartnershipByName ("Test partnership")); } |
### Question:
DiscreteAnneal { public String getStatus() { final StringBuilder result = new StringBuilder(); result.append("k="); result.append(this.k); result.append(",kMax="); result.append(this.kMax); result.append(",t="); result.append(this.currentTemperature); result.append(",prob="); result.append(this.lastProbability); return result.toString(); } DiscreteAnneal(final int theKMax, final double theStartingTemperature, final double theEndingTemperature); double coolingSchedule(); void iteration(); abstract void backupState(); abstract void restoreState(); abstract void foundNewBest(); abstract void moveToNeighbor(); abstract double evaluate(); boolean done(); double getBestScore(); double calcProbability(final double ecurrent, final double enew, final double t); int getK(); int getCycles(); void setCycles(final int cycles); String getStatus(); }### Answer:
@Test public void testStatus() { final DiscreteAnnealSubclass anneal = new DiscreteAnnealSubclass(1000, 4000, 1); assertEquals("k=0,kMax=1000,t=0.0,prob=0.0", anneal.getStatus()); } |
### Question:
KMeans { public void initForgy(final List<BasicData> theObservations) { final int dimensions = findDimensions(theObservations); this.clusters.clear(); final Set<Integer> usedObservations = new HashSet<Integer>(); for (int i = 0; i < this.k; i++) { final Cluster cluster = new Cluster(dimensions); this.clusters.add(cluster); int observationIndex = -1; while (observationIndex == -1) { observationIndex = this.randomGeneration.nextInt(theObservations.size()); if (usedObservations.contains(observationIndex)) { observationIndex = -1; } } final double[] observation = theObservations.get(observationIndex).getInput(); System.arraycopy(observation, 0, cluster.getCenter(), 0, dimensions); usedObservations.add(observationIndex); } for (final BasicData observation : theObservations) { final Cluster cluster = findNearestCluster(observation.getInput()); cluster.getObservations().add(observation); } updateStep(); } KMeans(final int theK); void initRandom(final List<BasicData> theObservations); void initForgy(final List<BasicData> theObservations); Cluster findNearestCluster(final double[] observation); boolean iteration(); int iteration(final int maxIterations); GenerateRandom getRandomGeneration(); void setRandomGeneration(final GenerateRandom randomGeneration); CalculateDistance getDistanceMetric(); void setDistanceMetric(final CalculateDistance distanceMetric); int getK(); List<Cluster> getClusters(); }### Answer:
@Test(expected = AIFHError.class) public void testNoObservations() { final List<BasicData> list = new ArrayList<BasicData>(); final KMeans kmeans = new KMeans(3); kmeans.initForgy(list); }
@Test(expected = AIFHError.class) public void testNoDimension() { final List<BasicData> list = new ArrayList<BasicData>(); list.add(new BasicData(0)); final KMeans kmeans = new KMeans(3); kmeans.initForgy(list); } |
### Question:
BasicData { public String toString() { final StringBuilder result = new StringBuilder(); result.append("[BasicData: input:"); result.append(Arrays.toString(this.input)); result.append(", ideal:"); result.append(Arrays.toString(this.ideal)); result.append(", label:"); result.append(this.label); result.append("]"); return result.toString(); } BasicData(final int theInputDimensions); BasicData(final int theInputDimensions, final int theIdealDimensions); BasicData(final int theInputDimensions, final int theIdealDimensions, final String theLabel); BasicData(final double[] theInputData, final double[] theIdealData, final String theLabel); BasicData(final double[] theInputData, final String theLabel); BasicData(final double[] theInputData); double[] getInput(); double[] getIdeal(); String getLabel(); void setLabel(final String label); String toString(); static List<BasicData> convertArrays(final double[][] inputData, final double[][] idealData); }### Answer:
@Test public void testToString() { final BasicData data = new BasicData(2); assertEquals("[BasicData: input:[0.0, 0.0], ideal:[], label:null]", data.toString()); } |
### Question:
VectorUtil { public static int maxIndex(final double[] a) { int result = -1; double max = Double.NEGATIVE_INFINITY; for (int i = 0; i < a.length; i++) { if (a[i] > max) { max = a[i]; result = i; } } return result; } private VectorUtil(); static int maxIndex(final double[] a); }### Answer:
@Test public void testMaxIndex() { final double[] a = {2, 4, 10, 8}; assertEquals(2, VectorUtil.maxIndex(a), AIFH.DEFAULT_PRECISION); } |
### Question:
LogLinkFunction implements Fn { @Override public double evaluate(final double[] x) { if (x.length > 1) { throw new AIFHError("The logistic link function can only accept one parameter."); } return Math.log(x[0]); } @Override double evaluate(final double[] x); }### Answer:
@Test public void testEvaluate() { final LogLinkFunction fn = new LogLinkFunction(); final double[] x = {2}; final double y = fn.evaluate(x); assertEquals(0.6931471805599453, y, AIFH.DEFAULT_PRECISION); }
@Test(expected = AIFHError.class) public void testException() { final LogLinkFunction fn = new LogLinkFunction(); final double[] x = {1, 2}; fn.evaluate(x); } |
### Question:
IdentityLinkFunction implements Fn { @Override public double evaluate(final double[] x) { if (x.length > 1) { throw new AIFHError("The linear link function can only accept one parameter."); } return x[0]; } @Override double evaluate(final double[] x); }### Answer:
@Test public void testEvaluate() { final IdentityLinkFunction fn = new IdentityLinkFunction(); final double[] x = {2}; final double y = fn.evaluate(x); assertEquals(2, y, AIFH.DEFAULT_PRECISION); }
@Test(expected = AIFHError.class) public void testException() { final IdentityLinkFunction fn = new IdentityLinkFunction(); final double[] x = {1, 2}; fn.evaluate(x); } |
### Question:
InverseLinkFunction implements Fn { @Override public double evaluate(final double[] x) { if (x.length > 1) { throw new AIFHError("The inverse link function can only accept one parameter."); } return -Math.pow(x[0], -1); } @Override double evaluate(final double[] x); }### Answer:
@Test public void testEvaluate() { final InverseLinkFunction fn = new InverseLinkFunction(); final double[] x = {2}; final double y = fn.evaluate(x); assertEquals(-0.5, y, AIFH.DEFAULT_PRECISION); }
@Test(expected = AIFHError.class) public void testException() { final InverseLinkFunction fn = new InverseLinkFunction(); final double[] x = {1, 2}; fn.evaluate(x); } |
### Question:
DiscreteAnneal { public double coolingSchedule() { final double ex = (double) k / (double) kMax; return this.startingTemperature * Math.pow(this.endingTemperature / this.startingTemperature, ex); } DiscreteAnneal(final int theKMax, final double theStartingTemperature, final double theEndingTemperature); double coolingSchedule(); void iteration(); abstract void backupState(); abstract void restoreState(); abstract void foundNewBest(); abstract void moveToNeighbor(); abstract double evaluate(); boolean done(); double getBestScore(); double calcProbability(final double ecurrent, final double enew, final double t); int getK(); int getCycles(); void setCycles(final int cycles); String getStatus(); }### Answer:
@Test public void testCoolingSchedule() { final DiscreteAnnealSubclass anneal = new DiscreteAnnealSubclass(1000, 400, 1); assertEquals(400, anneal.coolingSchedule(), AIFH.DEFAULT_PRECISION); anneal.iteration(); assertEquals(397.61057939346017, anneal.coolingSchedule(), AIFH.DEFAULT_PRECISION); } |
### Question:
LogitLinkFunction implements Fn { @Override public double evaluate(final double[] x) { if (x.length > 1) { throw new AIFHError("The logistic link function can only accept one parameter."); } return 1.0 / (1.0 + Math.exp(-x[0])); } @Override double evaluate(final double[] x); }### Answer:
@Test public void testEvaluate() { final LogitLinkFunction fn = new LogitLinkFunction(); final double[] x = {2}; final double y = fn.evaluate(x); assertEquals(0.8807970779778823, y, AIFH.DEFAULT_PRECISION); }
@Test(expected = AIFHError.class) public void testException() { final LogitLinkFunction fn = new LogitLinkFunction(); final double[] x = {1, 2}; fn.evaluate(x); } |
### Question:
InverseSquaredLinkFunction implements Fn { @Override public double evaluate(final double[] x) { if (x.length > 1) { throw new AIFHError("The inverse squared link function can only accept one parameter."); } return -Math.pow(x[0], -2); } @Override double evaluate(final double[] x); }### Answer:
@Test public void testEvaluate() { final InverseSquaredLinkFunction fn = new InverseSquaredLinkFunction(); final double[] x = {2}; final double y = fn.evaluate(x); assertEquals(-0.25, y, AIFH.DEFAULT_PRECISION); }
@Test(expected = AIFHError.class) public void testException() { final InverseSquaredLinkFunction fn = new InverseSquaredLinkFunction(); final double[] x = {1, 2}; fn.evaluate(x); } |
### Question:
GaussianFunction extends AbstractRBF { @Override public double evaluate(final double[] x) { double value = 0; final double width = getWidth(); for (int i = 0; i < getDimensions(); i++) { final double center = this.getCenter(i); value += Math.pow(x[i] - center, 2) / (2.0 * width * width); } return Math.exp(-value); } GaussianFunction(final int theDimensions, final double[] theParams, final int theIndex); @Override double evaluate(final double[] x); }### Answer:
@Test public void testEvaluate() { final double[] params = {5, 0, 0, 0}; final GaussianFunction funct = new GaussianFunction(3, params, 0); final double[] x = {-1, 0, 1}; final double y = funct.evaluate(x); assertEquals(0.9607894391523232, y, AIFH.DEFAULT_PRECISION); }
@Test public void testToString() { final double[] params = {5, 0, 0, 0}; final GaussianFunction funct = new GaussianFunction(3, params, 0); final double[] x = {-1, 0, 1}; funct.evaluate(x); assertEquals("[GaussianFunction:width=5.00,center=0.00,0.00,0.00]", funct.toString()); } |
### Question:
MultiquadricFunction extends AbstractRBF { @Override public double evaluate(final double[] x) { double value = 0; final double width = getWidth(); for (int i = 0; i < getDimensions(); i++) { final double center = getCenter(i); value += Math.pow(x[i] - center, 2) + (width * width); } return Math.sqrt(value); } MultiquadricFunction(final int theDimensions, final double[] theParams, final int theIndex); @Override double evaluate(final double[] x); }### Answer:
@Test public void testEvaluate() { final double[] params = {5, 0, 0, 0}; final MultiquadricFunction funct = new MultiquadricFunction(3, params, 0); final double[] x = {-1, 0, 1}; final double y = funct.evaluate(x); assertEquals(8.774964387392123, y, AIFH.DEFAULT_PRECISION); }
@Test public void testToString() { final double[] params = {5, 0, 0, 0}; final MultiquadricFunction funct = new MultiquadricFunction(3, params, 0); final double[] x = {-1, 0, 1}; funct.evaluate(x); assertEquals("[MultiquadricFunction:width=5.00,center=0.00,0.00,0.00]", funct.toString()); } |
### Question:
InverseMultiquadricFunction extends AbstractRBF { @Override public double evaluate(final double[] x) { double value = 0; final double width = getWidth(); for (int i = 0; i < getDimensions(); i++) { final double center = getCenter(i); value += Math.pow(x[i] - center, 2) + (width * width); } return 1 / Math.sqrt(value); } InverseMultiquadricFunction(final int theDimensions, final double[] theParams, final int theIndex); @Override double evaluate(final double[] x); }### Answer:
@Test public void testEvaluate() { final double[] params = {5, 0, 0, 0}; final InverseMultiquadricFunction funct = new InverseMultiquadricFunction(3, params, 0); final double[] x = {-1, 0, 1}; final double y = funct.evaluate(x); assertEquals(0.11396057645963795, y, AIFH.DEFAULT_PRECISION); }
@Test public void testToString() { final double[] params = {5, 0, 0, 0}; final InverseMultiquadricFunction funct = new InverseMultiquadricFunction(3, params, 0); final double[] x = {-1, 0, 1}; funct.evaluate(x); assertEquals("[InverseMultiquadricFunction:width=5.00,center=0.00,0.00,0.00]", funct.toString()); } |
### Question:
ScoreClassificationData implements ScoreFunction { @Override public double calculateScore(final MachineLearningAlgorithm algo) { int incorrectCount = 0; int totalCount = 0; final ClassificationAlgorithm ralgo = (ClassificationAlgorithm) algo; for (final BasicData aTrainingData : this.trainingData) { totalCount++; final int output = ralgo.computeClassification(aTrainingData.getInput()); if (output != (int) aTrainingData.getIdeal()[0]) { incorrectCount++; } } return (double) incorrectCount / (double) totalCount; } ScoreClassificationData(final List<BasicData> theTrainingData); @Override double calculateScore(final MachineLearningAlgorithm algo); }### Answer:
@Test public void testClassification() { final double[] ACTUAL = {0.0, 1.0, 0.0, 0.0}; final List<BasicData> training = BasicData.convertArrays(TEST_INPUT, TEST_IDEAL); final ScoreClassificationData score = new ScoreClassificationData(training); final SimpleAlgo simple = new SimpleAlgo(ACTUAL); final double s = score.calculateScore(simple); assertEquals(0.25, s, AIFH.DEFAULT_PRECISION); } |
### Question:
MexicanHatFunction extends AbstractRBF { @Override public double evaluate(final double[] x) { double norm = 0; for (int i = 0; i < getDimensions(); i++) { final double center = this.getCenter(i); norm += Math.pow(x[i] - center, 2); } return (1 - norm) * Math.exp(-norm / 2); } MexicanHatFunction(final int theDimensions, final double[] theParams, final int theIndex); @Override double evaluate(final double[] x); }### Answer:
@Test public void testEvaluate() { final double[] params = {5, 0, 0, 0}; final MexicanHatFunction funct = new MexicanHatFunction(3, params, 0); final double[] x = {-1, 0, 1}; final double y = funct.evaluate(x); assertEquals(-0.36787944117144233, y, AIFH.DEFAULT_PRECISION); }
@Test public void testToString() { final double[] params = {5, 0, 0, 0}; final MexicanHatFunction funct = new MexicanHatFunction(3, params, 0); final double[] x = {-1, 0, 1}; funct.evaluate(x); assertEquals("[MexicanHatFunction:width=5.00,center=0.00,0.00,0.00]", funct.toString()); } |
### Question:
DataSet { public Map<String, Integer> encodeOneOfN(final int column) { return encodeOneOfN(column, 0, 1); } DataSet(final String[] theHeaders); static DataSet load(final File filename); static DataSet load(final InputStream is); static void save(final File filename, final DataSet ds); static void save(final OutputStream os, final DataSet ds); int getHeaderCount(); String[] getHeaders(); void add(final Object[] row); List<Object[]> getData(); double getMax(final int column); double getMin(final int column); void normalizeRange(final int column, final double dataLow, final double dataHigh, final double normalizedLow, final double normalizedHigh); void normalizeRange(final int column, final double normalizedLow, final double normalizedHigh); void deNormalizeRange(final int column, final double dataLow, final double dataHigh, final double normalizedLow, final double normalizedHigh); void normalizeReciprocal(final int column); void deNormalizeReciprocal(final int column); Map<String, Integer> enumerateClasses(final int column); Map<String, Integer> encodeNumeric(final int column); Map<String, Integer> encodeOneOfN(final int column); Map<String, Integer> encodeOneOfN(final int column, final double offValue, final double onValue); Map<String, Integer> encodeEquilateral(final int column); Map<String, Integer> encodeEquilateral(final int column, final double offValue, final double onValue); int size(); void appendColumns(final int count); void insertColumns(final int column, final int columnCount); @Override boolean equals(final Object other); List<BasicData> extractUnsupervisedLabeled(final int labelIndex); List<BasicData> extractSupervised(final int inputBegin, final int inputCount, final int idealBegin, final int idealCount); void deleteUnknowns(); void deleteColumn(final int col); void replaceColumn(final int columnIndex, final double searchFor, final double replaceWith, final double others); }### Answer:
@Test public void testEncodeOneOfN() { final DataSet ds1 = generateTestData(); ds1.encodeOneOfN(0); } |
### Question:
Equilateral implements Serializable { public final double[] encode(final int set) { if (set < 0 || set > this.matrix.length) { throw new AIFHError("Class out of range for equilateral: " + set); } return this.matrix[set]; } Equilateral(final int count, final double low, final double high); final int decode(final double[] activations); final double[] encode(final int set); final double getDistance(final double[] data, final int set); static final int MIN_EQ; }### Answer:
@Test public void testEncode() { final Equilateral eq = new Equilateral(3, -1, 1); final double[] d = eq.encode(1); assertEquals(0.8660254037844386, d[0], AIFH.DEFAULT_PRECISION); assertEquals(-0.5, d[1], AIFH.DEFAULT_PRECISION); }
@Test(expected = AIFHError.class) public void testError() { final Equilateral eq = new Equilateral(3, -1, 1); eq.encode(10); }
@Test public void testAllEqual() { final Equilateral eq = new Equilateral(10, -1, 1); final CalculateDistance dc = new EuclideanDistance(); double compareDist = 0; for (int x = 0; x < 10; x++) { double[] baseClass = eq.encode(x); for (int y = 0; y < 10; y++) { if (x != y) { double[] otherClass = eq.encode(y); double dist = dc.calculate(baseClass, otherClass); if (compareDist < AIFH.DEFAULT_PRECISION) { compareDist = dist; } else { assertEquals(compareDist, dist, AIFH.DEFAULT_PRECISION); } } } } } |
### Question:
Equilateral implements Serializable { public final int decode(final double[] activations) { double minValue = Double.POSITIVE_INFINITY; int minSet = -1; for (int i = 0; i < this.matrix.length; i++) { final double dist = getDistance(activations, i); if (dist < minValue) { minValue = dist; minSet = i; } } return minSet; } Equilateral(final int count, final double low, final double high); final int decode(final double[] activations); final double[] encode(final int set); final double getDistance(final double[] data, final int set); static final int MIN_EQ; }### Answer:
@Test public void testDecode() { final Equilateral eq = new Equilateral(3, -1, 1); final double[] d0 = {0.866, 0.5}; final double[] d1 = {-0.866, 0.5}; final double[] d2 = {0, -1}; assertEquals(2, eq.decode(d0)); assertEquals(2, eq.decode(d1)); assertEquals(0, eq.decode(d2)); } |
### Question:
RBFNetwork implements RegressionAlgorithm, ClassificationAlgorithm { @Override public int computeClassification(final double[] input) { final double[] output = computeRegression(input); return VectorUtil.maxIndex(output); } RBFNetwork(final int theInputCount, final int rbfCount, final int theOutputCount); @Override double[] computeRegression(final double[] input); @Override double[] getLongTermMemory(); void reset(final GenerateRandom rnd); @Override int computeClassification(final double[] input); @Override String toString(); }### Answer:
@Test public void testComputeClassification() { final RBFNetwork network = new RBFNetwork(2, 1, 2); final double[] ltm = { 2.0, 2.0, 5.0, 2.0, 4.0, 3.0, 4.0, 5.0, 6.0}; System.arraycopy(ltm, 0, network.getLongTermMemory(), 0, ltm.length); final double[] x = {1, 2}; final double[] y = network.computeRegression(x); assertEquals(7, y[0], AIFH.DEFAULT_PRECISION); assertEquals(11, y[1], AIFH.DEFAULT_PRECISION); final int cls = network.computeClassification(x); assertEquals(1, cls); } |
### Question:
BasicGenerateRandom extends AbstractGenerateRandom { @Override public boolean nextBoolean() { return this.rand.nextBoolean(); } BasicGenerateRandom(final long seed); BasicGenerateRandom(); @Override int nextInt(); @Override double nextDouble(); @Override float nextFloat(); @Override long nextLong(); @Override boolean nextBoolean(); @Override double nextGaussian(); }### Answer:
@Test public void testGenerateBoolean() { final BasicGenerateRandom rnd = new BasicGenerateRandom(1); for (final boolean aBOOLEAN_TEST : BOOLEAN_TEST) { final boolean g = rnd.nextBoolean(); assertEquals(g, aBOOLEAN_TEST); } } |
### Question:
BasicGenerateRandom extends AbstractGenerateRandom { @Override public double nextDouble() { return this.rand.nextDouble(); } BasicGenerateRandom(final long seed); BasicGenerateRandom(); @Override int nextInt(); @Override double nextDouble(); @Override float nextFloat(); @Override long nextLong(); @Override boolean nextBoolean(); @Override double nextGaussian(); }### Answer:
@Test public void testDoubleRange() { final BasicGenerateRandom rnd = new BasicGenerateRandom(1); for (final double aDOUBLE_RANGE_TEST : DOUBLE_RANGE_TEST) { final double g = rnd.nextDouble(-1, 1); assertEquals(g, aDOUBLE_RANGE_TEST, AIFH.DEFAULT_PRECISION); } }
@Test public void testDouble() { final BasicGenerateRandom rnd = new BasicGenerateRandom(1); for (final double aDOUBLE_TEST : DOUBLE_TEST) { final double g = rnd.nextDouble(); assertEquals(g, aDOUBLE_TEST, AIFH.DEFAULT_PRECISION); } } |
### Question:
BasicGenerateRandom extends AbstractGenerateRandom { @Override public long nextLong() { return this.rand.nextLong(); } BasicGenerateRandom(final long seed); BasicGenerateRandom(); @Override int nextInt(); @Override double nextDouble(); @Override float nextFloat(); @Override long nextLong(); @Override boolean nextBoolean(); @Override double nextGaussian(); }### Answer:
@Test public void testLong() { final BasicGenerateRandom rnd = new BasicGenerateRandom(1); for (final long aLONG_TEST : LONG_TEST) { final long l = rnd.nextLong(); assertEquals(l, aLONG_TEST, AIFH.DEFAULT_PRECISION); } } |
### Question:
BasicGenerateRandom extends AbstractGenerateRandom { @Override public float nextFloat() { return this.rand.nextFloat(); } BasicGenerateRandom(final long seed); BasicGenerateRandom(); @Override int nextInt(); @Override double nextDouble(); @Override float nextFloat(); @Override long nextLong(); @Override boolean nextBoolean(); @Override double nextGaussian(); }### Answer:
@Test public void testFloat() { final BasicGenerateRandom rnd = new BasicGenerateRandom(1); for (final float aFLOAT_TEST : FLOAT_TEST) { final float l = (float) rnd.nextFloat(); assertEquals(l, aFLOAT_TEST, AIFH.DEFAULT_PRECISION); } } |
### Question:
BasicGenerateRandom extends AbstractGenerateRandom { @Override public double nextGaussian() { return this.rand.nextGaussian(); } BasicGenerateRandom(final long seed); BasicGenerateRandom(); @Override int nextInt(); @Override double nextDouble(); @Override float nextFloat(); @Override long nextLong(); @Override boolean nextBoolean(); @Override double nextGaussian(); }### Answer:
@Test public void testGaussianFloat() { final BasicGenerateRandom rnd = new BasicGenerateRandom(1); for (final double aGAUSSIAN_TEST : GAUSSIAN_TEST) { final double g = rnd.nextGaussian(); assertEquals(g, aGAUSSIAN_TEST, AIFH.DEFAULT_PRECISION); } } |
### Question:
BasicGenerateRandom extends AbstractGenerateRandom { @Override public int nextInt() { return this.rand.nextInt(); } BasicGenerateRandom(final long seed); BasicGenerateRandom(); @Override int nextInt(); @Override double nextDouble(); @Override float nextFloat(); @Override long nextLong(); @Override boolean nextBoolean(); @Override double nextGaussian(); }### Answer:
@Test public void testInt() { final BasicGenerateRandom rnd = new BasicGenerateRandom(1); for (final int aINT_TEST : INT_TEST) { final int g = rnd.nextInt(); assertEquals(g, aINT_TEST, AIFH.DEFAULT_PRECISION); } }
@Test public void testIntRange() { final BasicGenerateRandom rnd = new BasicGenerateRandom(1); for (final int aINT_RANGE_TEST : INT_RANGE_TEST) { final int g = rnd.nextInt(0, 10); assertEquals(g, aINT_RANGE_TEST); } } |
### Question:
MultiplyWithCarryGenerateRandom extends AbstractBoxMuller { @Override public boolean nextBoolean() { return nextDouble() > 0.5; } MultiplyWithCarryGenerateRandom(final long seed); MultiplyWithCarryGenerateRandom(); MultiplyWithCarryGenerateRandom(long[] seeds, final long carry, final int r, final long multiplier); @Override double nextDouble(); @Override long nextLong(); @Override boolean nextBoolean(); @Override float nextFloat(); @Override int nextInt(); }### Answer:
@Test public void testGenerateBoolean() { final MultiplyWithCarryGenerateRandom rnd = new MultiplyWithCarryGenerateRandom(1); for (final boolean aBOOLEAN_TEST : BOOLEAN_TEST) { final boolean g = rnd.nextBoolean(); assertEquals(g, aBOOLEAN_TEST); } } |
### Question:
ChebyshevDistance extends AbstractDistance { @Override public double calculate(final double[] position1, final int pos1, final double[] position2, final int pos2, final int length) { double result = 0; for (int i = 0; i < length; i++) { final double d = Math.abs(position1[pos1 + i] - position2[pos2 + i]); result = Math.max(d, result); } return result; } @Override double calculate(final double[] position1, final int pos1, final double[] position2, final int pos2, final int length); }### Answer:
@Test public void testDistanceCalc() { final CalculateDistance calc = new ChebyshevDistance(); final double[] pos1 = {0.5, 1.0, 2.5,}; final double[] pos2 = {0.1, 2.0, -2.5,}; assertEquals(5.0, calc.calculate(pos1, pos2), 0.001); } |
### Question:
MultiplyWithCarryGenerateRandom extends AbstractBoxMuller { @Override public double nextDouble() { return (((long) next(26) << 27) + next(27)) / (double) (1L << 53); } MultiplyWithCarryGenerateRandom(final long seed); MultiplyWithCarryGenerateRandom(); MultiplyWithCarryGenerateRandom(long[] seeds, final long carry, final int r, final long multiplier); @Override double nextDouble(); @Override long nextLong(); @Override boolean nextBoolean(); @Override float nextFloat(); @Override int nextInt(); }### Answer:
@Test public void testDoubleRange() { final MultiplyWithCarryGenerateRandom rnd = new MultiplyWithCarryGenerateRandom(1); for (final double aDOUBLE_RANGE_TEST : DOUBLE_RANGE_TEST) { final double g = rnd.nextDouble(-1, 1); assertEquals(g, aDOUBLE_RANGE_TEST, AIFH.DEFAULT_PRECISION); } }
@Test public void testDouble() { final MultiplyWithCarryGenerateRandom rnd = new MultiplyWithCarryGenerateRandom(1); for (final double aDOUBLE_TEST : DOUBLE_TEST) { final double g = rnd.nextDouble(); assertEquals(g, aDOUBLE_TEST, AIFH.DEFAULT_PRECISION); } } |
### Question:
MultiplyWithCarryGenerateRandom extends AbstractBoxMuller { @Override public long nextLong() { return ((long) next(32) << 32) + next(32); } MultiplyWithCarryGenerateRandom(final long seed); MultiplyWithCarryGenerateRandom(); MultiplyWithCarryGenerateRandom(long[] seeds, final long carry, final int r, final long multiplier); @Override double nextDouble(); @Override long nextLong(); @Override boolean nextBoolean(); @Override float nextFloat(); @Override int nextInt(); }### Answer:
@Test public void testLong() { final MultiplyWithCarryGenerateRandom rnd = new MultiplyWithCarryGenerateRandom(1); for (final long aLONG_TEST : LONG_TEST) { final long l = rnd.nextLong(); assertEquals(l, aLONG_TEST); } } |
### Question:
MultiplyWithCarryGenerateRandom extends AbstractBoxMuller { @Override public float nextFloat() { return (float) nextDouble(); } MultiplyWithCarryGenerateRandom(final long seed); MultiplyWithCarryGenerateRandom(); MultiplyWithCarryGenerateRandom(long[] seeds, final long carry, final int r, final long multiplier); @Override double nextDouble(); @Override long nextLong(); @Override boolean nextBoolean(); @Override float nextFloat(); @Override int nextInt(); }### Answer:
@Test public void testFloat() { final MultiplyWithCarryGenerateRandom rnd = new MultiplyWithCarryGenerateRandom(1); for (final float aFLOAT_TEST : FLOAT_TEST) { final float l = (float) rnd.nextFloat(); assertEquals(l, aFLOAT_TEST, AIFH.DEFAULT_PRECISION); } } |
### Question:
MultiplyWithCarryGenerateRandom extends AbstractBoxMuller { @Override public int nextInt() { return (int) nextLong(); } MultiplyWithCarryGenerateRandom(final long seed); MultiplyWithCarryGenerateRandom(); MultiplyWithCarryGenerateRandom(long[] seeds, final long carry, final int r, final long multiplier); @Override double nextDouble(); @Override long nextLong(); @Override boolean nextBoolean(); @Override float nextFloat(); @Override int nextInt(); }### Answer:
@Test public void testInt() { final MultiplyWithCarryGenerateRandom rnd = new MultiplyWithCarryGenerateRandom(1); for (final int aINT_TEST : INT_TEST) { final int g = rnd.nextInt(); assertEquals(g, aINT_TEST); } }
@Test public void testIntRange() { final MultiplyWithCarryGenerateRandom rnd = new MultiplyWithCarryGenerateRandom(1); for (final int aINT_RANGE_TEST : INT_RANGE_TEST) { final int g = rnd.nextInt(0, 10); assertEquals(g, aINT_RANGE_TEST); } } |
### Question:
LinearCongruentialRandom extends AbstractBoxMuller { @Override public boolean nextBoolean() { return nextDouble() > 0.5; } LinearCongruentialRandom(final long theSeed); LinearCongruentialRandom(); LinearCongruentialRandom(final long theModulus,
final long theMultiplier, final long theIncrement,
final long theSeed); final long getIncrement(); final long getModulus(); final long getMultiplier(); final long getSeed(); @Override final double nextDouble(); @Override final long nextLong(); @Override boolean nextBoolean(); @Override float nextFloat(); @Override int nextInt(); static final long DEFAULT_MOD1; static final long DEFAULT_MOD2; static final long DEFAULT_MULT; static final long DEFAULT_INC; static final long MAX_RAND; }### Answer:
@Test public void testGenerateBoolean() { final LinearCongruentialRandom rnd = new LinearCongruentialRandom(1); for (final boolean aBOOLEAN_TEST : BOOLEAN_TEST) { final boolean g = rnd.nextBoolean(); assertEquals(g, aBOOLEAN_TEST); } } |
### Question:
LinearCongruentialRandom extends AbstractBoxMuller { @Override public final double nextDouble() { return (double) nextLong() / LinearCongruentialRandom.MAX_RAND; } LinearCongruentialRandom(final long theSeed); LinearCongruentialRandom(); LinearCongruentialRandom(final long theModulus,
final long theMultiplier, final long theIncrement,
final long theSeed); final long getIncrement(); final long getModulus(); final long getMultiplier(); final long getSeed(); @Override final double nextDouble(); @Override final long nextLong(); @Override boolean nextBoolean(); @Override float nextFloat(); @Override int nextInt(); static final long DEFAULT_MOD1; static final long DEFAULT_MOD2; static final long DEFAULT_MULT; static final long DEFAULT_INC; static final long MAX_RAND; }### Answer:
@Test public void testDoubleRange() { final LinearCongruentialRandom rnd = new LinearCongruentialRandom(1); for (final double aDOUBLE_RANGE_TEST : DOUBLE_RANGE_TEST) { final double g = rnd.nextDouble(-1, 1); assertEquals(g, aDOUBLE_RANGE_TEST, AIFH.DEFAULT_PRECISION); } }
@Test public void testDouble() { final LinearCongruentialRandom rnd = new LinearCongruentialRandom(1); for (final double aDOUBLE_TEST : DOUBLE_TEST) { final double g = rnd.nextDouble(); assertEquals(g, aDOUBLE_TEST, AIFH.DEFAULT_PRECISION); } } |
### Question:
LinearCongruentialRandom extends AbstractBoxMuller { @Override public final long nextLong() { this.seed = (this.multiplier * this.seed + this.increment) % this.modulus; return this.seed; } LinearCongruentialRandom(final long theSeed); LinearCongruentialRandom(); LinearCongruentialRandom(final long theModulus,
final long theMultiplier, final long theIncrement,
final long theSeed); final long getIncrement(); final long getModulus(); final long getMultiplier(); final long getSeed(); @Override final double nextDouble(); @Override final long nextLong(); @Override boolean nextBoolean(); @Override float nextFloat(); @Override int nextInt(); static final long DEFAULT_MOD1; static final long DEFAULT_MOD2; static final long DEFAULT_MULT; static final long DEFAULT_INC; static final long MAX_RAND; }### Answer:
@Test public void testLong() { final LinearCongruentialRandom rnd = new LinearCongruentialRandom(1); for (final long aLONG_TEST : LONG_TEST) { final long l = rnd.nextLong(); assertEquals(l, aLONG_TEST, AIFH.DEFAULT_PRECISION); } } |
### Question:
EuclideanDistance extends AbstractDistance { @Override public double calculate(final double[] position1, final int pos1, final double[] position2, final int pos2, final int length) { double sum = 0; for (int i = 0; i < length; i++) { final double d = position1[i + pos1] - position2[i + pos1]; sum += d * d; } return Math.sqrt(sum); } @Override double calculate(final double[] position1, final int pos1, final double[] position2, final int pos2, final int length); }### Answer:
@Test public void testDistanceCalc() { final CalculateDistance calc = new EuclideanDistance(); final double[] pos1 = {0.5, 1.0, 2.5,}; final double[] pos2 = {0.1, 2.0, -2.5,}; assertEquals(5.1146, calc.calculate(pos1, pos2), 0.001); } |
Subsets and Splits