Fix the Hibernate4 issues (#1106)

* Binary genetic algorithm

* Fix the junit tests conflict
This commit is contained in:
maibin 2017-02-04 18:47:30 +01:00 committed by GitHub
parent ad104bfe8c
commit ffd17c1b21
7 changed files with 308 additions and 82 deletions

View File

@ -3,28 +3,34 @@ package com.baeldung.algorithms;
import java.util.Scanner;
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One");
int decision = in.nextInt();
switch (decision) {
case 1:
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
break;
case 2:
SlopeOne.slopeOne(3);
break;
default:
System.out.println("Unknown option");
break;
}
in.close();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One");
System.out.println("3 - Simple Genetic Algorithm");
int decision = in.nextInt();
switch (decision) {
case 1:
System.out.println(
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
break;
case 2:
SlopeOne.slopeOne(3);
break;
case 3:
SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
break;
default:
System.out.println("Unknown option");
break;
}
in.close();
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.algorithms.ga.binary;
import lombok.Data;
@Data
public class Individual {
protected int defaultGeneLength = 64;
private byte[] genes = new byte[defaultGeneLength];
private int fitness = 0;
public Individual() {
for (int i = 0; i < genes.length; i++) {
byte gene = (byte) Math.round(Math.random());
genes[i] = gene;
}
}
protected byte getSingleGene(int index) {
return genes[index];
}
protected void setSingleGene(int index, byte value) {
genes[index] = value;
fitness = 0;
}
public int getFitness() {
if (fitness == 0) {
fitness = SimpleGeneticAlgorithm.getFitness(this);
}
return fitness;
}
@Override
public String toString() {
String geneString = "";
for (int i = 0; i < genes.length; i++) {
geneString += getSingleGene(i);
}
return geneString;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.algorithms.ga.binary;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
@Data
public class Population {
private List<Individual> individuals;
public Population(int size, boolean createNew) {
individuals = new ArrayList<>();
if (createNew) {
createNewPopulation(size);
}
}
protected Individual getIndividual(int index) {
return individuals.get(index);
}
protected Individual getFittest() {
Individual fittest = individuals.get(0);
for (int i = 0; i < individuals.size(); i++) {
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
fittest = getIndividual(i);
}
}
return fittest;
}
private void createNewPopulation(int size) {
for (int i = 0; i < size; i++) {
Individual newIndividual = new Individual();
individuals.add(i, newIndividual);
}
}
}

View File

@ -0,0 +1,119 @@
package com.baeldung.algorithms.ga.binary;
import lombok.Data;
@Data
public class SimpleGeneticAlgorithm {
private static final double uniformRate = 0.5;
private static final double mutationRate = 0.025;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
private static byte[] solution = new byte[64];
public static boolean runAlgorithm(int populationSize, String solution) {
if (solution.length() != SimpleGeneticAlgorithm.solution.length) {
throw new RuntimeException(
"The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes");
}
SimpleGeneticAlgorithm.setSolution(solution);
Population myPop = new Population(populationSize, true);
int generationCount = 1;
while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) {
System.out.println(
"Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness());
myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop);
generationCount++;
}
System.out.println("Solution found!");
System.out.println("Generation: " + generationCount);
System.out.println("Genes: ");
System.out.println(myPop.getFittest());
return true;
}
public static Population evolvePopulation(Population pop) {
int elitismOffset;
Population newPopulation = new Population(pop.getIndividuals().size(), false);
if (elitism) {
newPopulation.getIndividuals().add(0, pop.getFittest());
elitismOffset = 1;
} else {
elitismOffset = 0;
}
for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) {
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.getIndividuals().add(i, newIndiv);
}
for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) {
mutate(newPopulation.getIndividual(i));
}
return newPopulation;
}
private static Individual crossover(Individual indiv1, Individual indiv2) {
Individual newSol = new Individual();
for (int i = 0; i < newSol.getDefaultGeneLength(); i++) {
if (Math.random() <= uniformRate) {
newSol.setSingleGene(i, indiv1.getSingleGene(i));
} else {
newSol.setSingleGene(i, indiv2.getSingleGene(i));
}
}
return newSol;
}
private static void mutate(Individual indiv) {
for (int i = 0; i < indiv.getDefaultGeneLength(); i++) {
if (Math.random() <= mutationRate) {
byte gene = (byte) Math.round(Math.random());
indiv.setSingleGene(i, gene);
}
}
}
private static Individual tournamentSelection(Population pop) {
Population tournament = new Population(tournamentSize, false);
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.getIndividuals().size());
tournament.getIndividuals().add(i, pop.getIndividual(randomId));
}
Individual fittest = tournament.getFittest();
return fittest;
}
protected static int getFitness(Individual individual) {
int fitness = 0;
for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) {
if (individual.getSingleGene(i) == solution[i]) {
fitness++;
}
}
return fitness;
}
protected static int getMaxFitness() {
int maxFitness = solution.length;
return maxFitness;
}
protected static void setSolution(String newSolution) {
solution = new byte[newSolution.length()];
for (int i = 0; i < newSolution.length(); i++) {
String character = newSolution.substring(i, i + 1);
if (character.contains("0") || character.contains("1")) {
solution[i] = Byte.parseByte(character);
} else {
solution[i] = 0;
}
}
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
public class BinaryGeneticAlgorithmTest {
@Test
public void testGA() {
Assert.assertTrue(SimpleGeneticAlgorithm.runAlgorithm(50,
"1011000100000100010000100000100111001000000100000100000000001111"));
}
}

View File

@ -10,4 +10,5 @@
# Packaged files #
*.jar
*.war
*.ear
*.ear
/target/

View File

@ -1,4 +1,3 @@
package com.baeldung.hibernate.oneToMany.main;
import static org.junit.Assert.assertNotNull;
@ -13,85 +12,86 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.hibernate.oneToMany.model.Cart;
import com.baeldung.hibernate.oneToMany.model.Items;
//@RunWith(SpringJUnit4ClassRunner.class)
public class HibernateOneToManyAnnotationMainTest {
private static SessionFactory sessionFactory;
private static SessionFactory sessionFactory;
private Session session;
private Session session;
public HibernateOneToManyAnnotationMainTest() {
}
public HibernateOneToManyAnnotationMainTest() {
}
@BeforeClass
public static void beforeTests() {
Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class).setProperty("hibernate.dialect", HSQLDialect.class.getName())
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()).setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa")
.setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
@BeforeClass
public static void beforeTests() {
Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class)
.setProperty("hibernate.dialect", HSQLDialect.class.getName())
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test")
.setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "")
.setProperty("hibernate.hbm2ddl.auto", "update");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
}
@Test
public void givenSession_checkIfDatabaseIsEmpty() {
Cart cart = (Cart) session.get(Cart.class, new Long(1));
assertNull(cart);
@Test
public void givenSession_checkIfDatabaseIsEmpty() {
Cart cart = (Cart) session.get(Cart.class, new Long(1));
assertNull(cart);
}
}
@Test
public void givenSession_checkIfDatabaseIsPopulated_afterCommit() {
Cart cart = new Cart();
Set<Items> cartItems = new HashSet<>();
cartItems = cart.getItems();
Assert.assertNull(cartItems);
Items item1 = new Items();
item1.setItemId("I10");
item1.setItemTotal(10);
item1.setQuantity(1);
item1.setCart(cart);
assertNotNull(item1);
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1);
assertNotNull(itemsSet);
cart.setItems(itemsSet);
assertNotNull(cart);
session.persist(cart);
session.getTransaction().commit();
session.close();
@Test
public void testAddItemsToCart() {
Cart cart = new Cart();
Set<Items> cartItems = new HashSet<>();
cartItems = cart.getItems();
Assert.assertNull(cartItems);
Items item1 = new Items("I10", 10, 1, cart);
assertNotNull(item1);
Set<Items> itemsSet = new HashSet<Items>();
cart.setItems(itemsSet);
assertNotNull(cart);
System.out.println("Items added to cart");
session = sessionFactory.openSession();
session.beginTransaction();
cart = (Cart) session.get(Cart.class, new Long(1));
assertNotNull(cart);
}
}
@After
public void tearDown() {
session.getTransaction().commit();
session.close();
}
@Test
public void givenSession_checkIfDatabaseIsPopulated_afterCommit() {
Cart cart = new Cart();
Set<Items> cartItems = new HashSet<>();
cartItems = cart.getItems();
Assert.assertNull(cartItems);
Items item1 = new Items();
item1.setItemId("I10");
item1.setItemTotal(10);
item1.setQuantity(1);
item1.setCart(cart);
assertNotNull(item1);
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1);
assertNotNull(itemsSet);
cart.setItems(itemsSet);
assertNotNull(cart);
session.persist(cart);
session.getTransaction().commit();
cart = (Cart) session.get(Cart.class, new Long(1));
assertNotNull(cart);
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}