diff --git a/Calculator/pom.xml b/Calculator/pom.xml new file mode 100644 index 0000000..21d555d --- /dev/null +++ b/Calculator/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + ru.caf82.homework + Calculator + 1.0 + jar + + + junit + junit + 4.12 + test + + + org.hamcrest + hamcrest-core + 1.3 + test + + + + UTF-8 + 1.8 + 1.8 + + \ No newline at end of file diff --git a/Calculator/src/main/java/ru/caf82/homework/calculator/MyCalculator.java b/Calculator/src/main/java/ru/caf82/homework/calculator/MyCalculator.java new file mode 100644 index 0000000..29cfc3c --- /dev/null +++ b/Calculator/src/main/java/ru/caf82/homework/calculator/MyCalculator.java @@ -0,0 +1,32 @@ + +package ru.caf82.homework.calculator; + +/** + * + * @author Алена + */ +public class MyCalculator { + public MyCalculator() { + + } + + public long add (long x, long y) { + return x+y; + } + + public long sub (long x, long y) { + return x-y; + } + + public long div (long x, long y) { + try { + return x/y; + }catch (ArithmeticException e) { + throw new ArithmeticException(); + } + } + + public long mult (long x, long y) { + return x*y; + } +} diff --git a/Calculator/src/test/java/MyTests/MyTest.java b/Calculator/src/test/java/MyTests/MyTest.java new file mode 100644 index 0000000..aff57e4 --- /dev/null +++ b/Calculator/src/test/java/MyTests/MyTest.java @@ -0,0 +1,70 @@ + +package MyTests; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; +import ru.caf82.homework.calculator.MyCalculator; + +/** + * + * @author Алена + */ +public class MyTest { + private MyCalculator myCalc; + + public MyTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + myCalc = new MyCalculator(); + } + + @After + public void tearDown() { + } + + @Test + public void checkAdd() { + assertTrue(myCalc.add(4, 5)==9); + assertTrue(myCalc.add(122, 100)==222); + assertTrue(myCalc.add(23, 23)==46); + } + + @Test + public void checkSub() { + assertTrue(myCalc.sub(100, 14)==86); + assertTrue(myCalc.sub(10, 3)==7); + assertTrue(myCalc.sub(200, 32)==168); + } + + @Test + public void checkMult() { + assertTrue(myCalc.mult(3, 4)==12); + assertTrue(myCalc.mult(10, 10)==100); + assertTrue(myCalc.mult(0, 4)==0); + } + + @Test + public void checkDiv() { + assertTrue(myCalc.div(20, 4)==5); + assertTrue(myCalc.div(1, 1)==1); + } + + @Test(expected = ArithmeticException.class) + public void checkZeroDiv() { + myCalc.div(13, 0); + } +} diff --git a/Calculator/target/classes/ru/caf82/homework/calculator/MyCalculator.class b/Calculator/target/classes/ru/caf82/homework/calculator/MyCalculator.class new file mode 100644 index 0000000..00bf426 Binary files /dev/null and b/Calculator/target/classes/ru/caf82/homework/calculator/MyCalculator.class differ diff --git a/Calculator/target/surefire-reports/MyTests.MyTest.txt b/Calculator/target/surefire-reports/MyTests.MyTest.txt new file mode 100644 index 0000000..1855e14 --- /dev/null +++ b/Calculator/target/surefire-reports/MyTests.MyTest.txt @@ -0,0 +1,4 @@ +------------------------------------------------------------------------------- +Test set: MyTests.MyTest +------------------------------------------------------------------------------- +Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.203 sec diff --git a/Calculator/target/surefire-reports/TEST-MyTests.MyTest.xml b/Calculator/target/surefire-reports/TEST-MyTests.MyTest.xml new file mode 100644 index 0000000..b5b52dc --- /dev/null +++ b/Calculator/target/surefire-reports/TEST-MyTests.MyTest.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Calculator/target/test-classes/MyTests/MyTest.class b/Calculator/target/test-classes/MyTests/MyTest.class new file mode 100644 index 0000000..0e8c819 Binary files /dev/null and b/Calculator/target/test-classes/MyTests/MyTest.class differ diff --git a/LectureUpdDatabaseHibernate/pom.xml b/LectureUpdDatabaseHibernate/pom.xml new file mode 100644 index 0000000..6c58dbc --- /dev/null +++ b/LectureUpdDatabaseHibernate/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + com.hibernatehomework + LectureUpdDatabaseHibernate + 2.0 + jar + LectureUpdDatabaseHibernate + + + 4.3.6.Final + 5.1.31 + + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + + + mysql + mysql-connector-java + ${mysql.connector.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.6 + 1.6 + + + + + + \ No newline at end of file diff --git a/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/DutiesDao.java b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/DutiesDao.java new file mode 100644 index 0000000..a606879 --- /dev/null +++ b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/DutiesDao.java @@ -0,0 +1,36 @@ + +package com.hibernatehomework.lectureupddatabase.dao; +import com.hibernatehomework.lectureupddatabase.entity.Duties; +import com.hibernatehomework.lectureupddatabase.util.HibernateUtil; +import org.hibernate.Session; +/** + * + * @author + */ +public class DutiesDao { + + public void save(Duties d) { + Session session = HibernateUtil.getSession(); + session.beginTransaction(); + session.persist(d); + session.save(d); + session.getTransaction().commit(); + session.close(); + } + + public Duties findId(Integer id) { + Session session = HibernateUtil.getSession(); + Duties duty = (Duties) session.get(Duties.class, id); + session.close(); + return duty; + } + + public void delete(Integer id) { + Session session = HibernateUtil.getSession(); + session.beginTransaction(); + Duties users = (Duties) session.get(Duties.class, id); + session.delete(users); + session.getTransaction().commit(); + session.close(); + } +} diff --git a/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/PasswordDao.java b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/PasswordDao.java new file mode 100644 index 0000000..8e69118 --- /dev/null +++ b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/PasswordDao.java @@ -0,0 +1,27 @@ + +package com.hibernatehomework.lectureupddatabase.dao; + +import com.hibernatehomework.lectureupddatabase.entity.Password; +import com.hibernatehomework.lectureupddatabase.util.HibernateUtil; +import java.util.List; +import org.hibernate.Session; + +/** + * + * @author + */ +public class PasswordDao { + public Password findId(Integer id) { + Session session = HibernateUtil.getSession(); + Password pass = (Password) session.get(Password.class, id); + session.close(); + return pass; + } + + public List findALl() { + Session session = HibernateUtil.getSession(); + List listPassword = (List)session.createQuery("from Password ").list(); + session.close(); + return listPassword; + } +} diff --git a/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/RunTest.java b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/RunTest.java new file mode 100644 index 0000000..63b7350 --- /dev/null +++ b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/RunTest.java @@ -0,0 +1,57 @@ + +package com.hibernatehomework.lectureupddatabase.dao; + +import com.hibernatehomework.lectureupddatabase.entity.Duties; +import com.hibernatehomework.lectureupddatabase.entity.Password; +import com.hibernatehomework.lectureupddatabase.entity.Users; +import java.util.List; + +/** + * + * @author + */ +public class RunTest { + + + public static void main(String[] args) { + // + DutiesDao dd = new DutiesDao(); + UserPasswordDutiesDao upd = new UserPasswordDutiesDao(); + UsersDao ud = new UsersDao(); + + /*Duties d1 = new Duties("admin"); + Duties d2 = new Duties("moderator"); + Duties d3 = new Duties("user"); + + Users u1 = new Users("alena", 20); + Users u2 = new Users("veronica", 18); + Users u3 = new Users("diana", 19); + Users u4 = new Users("katya", 9); + + Password p1 = new Password("050505"); + Password p2 = new Password("202020"); + Password p3 = new Password("222222"); + Password p4 = new Password("292929"); + + upd.save(u1, p1, d1); + upd.save(u2, p2, d2); + upd.save(u3, p3, d3); + upd.save(u4, p4, 3);*/ + + + // + List list = ud.findALl(); + for (Users u: list) { + System.out.println(("Row -->") + u); + } + + // + // upd.delete(3); + + // + System.out.println(upd.checkPass("alena", "050507")); + System.out.println(upd.checkPass("alena", "050505")); + + } + +} diff --git a/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/UserPasswordDutiesDao.java b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/UserPasswordDutiesDao.java new file mode 100644 index 0000000..dbe23c0 --- /dev/null +++ b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/UserPasswordDutiesDao.java @@ -0,0 +1,75 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.hibernatehomework.lectureupddatabase.dao; + +import com.hibernatehomework.lectureupddatabase.entity.Duties; +import com.hibernatehomework.lectureupddatabase.entity.Password; +import com.hibernatehomework.lectureupddatabase.entity.Users; +import com.hibernatehomework.lectureupddatabase.util.HibernateUtil; +import java.util.List; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.criterion.Restrictions; + +/** + * + * @author + */ +public class UserPasswordDutiesDao { + + public void save(Users u, Password p, Duties d) { + Session session = HibernateUtil.getSession(); + session.beginTransaction(); + session.save(d); + u.setDuties(d); + d.getUsers().add(u); + session.persist(u); + p.setId(u.getId()); + u.setPassword(p); + session.save(u); + session.getTransaction().commit(); + session.close(); + } + + public void save(Users u, Password p, Integer id) { + Session session = HibernateUtil.getSession(); + DutiesDao dd = new DutiesDao(); + session.beginTransaction(); + Duties d = dd.findId(id); + u.setDuties(d); + d.getUsers().add(u); + session.persist(u); + p.setId(u.getId()); + u.setPassword(p); + session.save(u); + session.getTransaction().commit(); + session.close(); + } + + public void delete(Integer id) { + Session session = HibernateUtil.getSession(); + session.beginTransaction(); + Users users = (Users) session.get(Users.class, id); + Duties d = users.getDuties(); + d.getUsers().remove(users); + session.delete(users); + session.getTransaction().commit(); + session.close(); + } + + public boolean checkPass(String login, String pass) { + UsersDao ud = new UsersDao(); + Users user = ud.findLogin(login); + if (user.getLogin().equals(null)) + return false; + else { + if (user.getPassword().getPass().equals(pass)) + return true; + else + return false; + } + } +} diff --git a/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/UsersDao.java b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/UsersDao.java new file mode 100644 index 0000000..1985316 --- /dev/null +++ b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/dao/UsersDao.java @@ -0,0 +1,44 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.hibernatehomework.lectureupddatabase.dao; + +import com.hibernatehomework.lectureupddatabase.entity.Users; +import com.hibernatehomework.lectureupddatabase.util.HibernateUtil; +import java.io.Serializable; +import java.util.List; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.criterion.Restrictions; + +/** + * + * @author + */ +public class UsersDao { + + public Users findId(Integer id) { + Session session = HibernateUtil.getSession(); + Users users = (Users) session.get(Users.class, id); + session.close(); + return users; + } + + public List findALl() { + Session session = HibernateUtil.getSession(); + List listUsers = (List)session.createQuery("from Users ").list(); + session.close(); + return listUsers; + } + + public Users findLogin (String login) { + Session session = HibernateUtil.getSession(); + Criteria criteria = session.createCriteria(Users.class); + criteria.add(Restrictions.eq("login", login)); + Users users = (Users) criteria.uniqueResult(); + session.close(); + return users; + } +} diff --git a/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/entity/Duties.java b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/entity/Duties.java new file mode 100644 index 0000000..f79b55b --- /dev/null +++ b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/entity/Duties.java @@ -0,0 +1,73 @@ + +package com.hibernatehomework.lectureupddatabase.entity; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +/** + * + * @author + */ +@Entity +@Table(name = "duties", schema = "databasehib") +public class Duties { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "idD", nullable = false) + private Integer id; + + @Column(name = "rule", nullable = false) + private String rule; + + @OneToMany(fetch = FetchType.EAGER, mappedBy = "duties", cascade = CascadeType.ALL) + private Set setUsers = new HashSet(); + + public Duties() { + + } + + public Duties(String s) { + rule = s; + } + + public Integer getId() { + return id; + } + + public void setId (Integer id) { + this.id = id; + } + + public String getRule() { + return rule; + } + + public void setRule(String rule) { + this.rule = rule; + } + + public Set getUsers() { + return setUsers; + } + + public void setUsers(Set setUsers) { + this.setUsers = setUsers; + } + + @Override + public String toString() { + return ("|id: "+ id + "; rule: " + rule + "|"); + } + +} diff --git a/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/entity/Password.java b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/entity/Password.java new file mode 100644 index 0000000..2ae27aa --- /dev/null +++ b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/entity/Password.java @@ -0,0 +1,56 @@ +package com.hibernatehomework.lectureupddatabase.entity; + +/** + * + * @author Alena + */ +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.Table; + +@Entity +@Table(name = "password", schema = "databasehib") +public class Password { + + @Id + @Column(name = "idP") + private Integer id; + + @Column(name = "pass") + private String pass; + + public Password() { + + } + + public Password(String pass) { + this.pass = pass; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getPass() { + return pass; + } + + public void setPass(String pass) { + this.pass = pass; + } + + @Override + public String toString() { + return ("|id: "+ id + "; password: " + pass + "|"); + } +} \ No newline at end of file diff --git a/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/entity/Users.java b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/entity/Users.java new file mode 100644 index 0000000..63f0709 --- /dev/null +++ b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/entity/Users.java @@ -0,0 +1,97 @@ +package com.hibernatehomework.lectureupddatabase.entity; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToOne; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.Table; + +/** + * + * @author + */ +@Entity +@Table(name = "users", schema = "databasehib") +public class Users { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "idU", nullable = false) + private Integer id; + + @Column(name = "login", nullable = false) + private String login; + + @Column(name = "age", nullable = false) + private int age; + + @OneToOne(cascade = CascadeType.ALL) + @PrimaryKeyJoinColumn + private Password password; + + @ManyToOne + @JoinColumn(name = "idDu", nullable = false) + private Duties duties; + + public Users() { + + } + + public Users(String login, int age) { + this.login = login; + this.age = age; + } + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login){ + this.login = login; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public Password getPassword() { + return password; + } + + public void setPassword(Password password) { + this.password = password; + } + + public Duties getDuties() { + return duties; + } + public void setDuties(Duties d) { + duties = d; + } + + + @Override + public String toString() { + return ("|id: " + id + "; login: " + login + "; age: " + age + "; duty: " + duties.getRule() + "|"); + } + + + +} \ No newline at end of file diff --git a/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/util/HibernateUtil.java b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/util/HibernateUtil.java new file mode 100644 index 0000000..d66f364 --- /dev/null +++ b/LectureUpdDatabaseHibernate/src/main/java/com/hibernatehomework/lectureupddatabase/util/HibernateUtil.java @@ -0,0 +1,31 @@ + +package com.hibernatehomework.lectureupddatabase.util; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.AnnotationConfiguration; +import org.hibernate.cfg.Configuration; + +/** + * + * @author + */ +public class HibernateUtil { + private static final SessionFactory sessionFactory; + + static { + try { + Configuration configuration = new Configuration(); + + sessionFactory = configuration.configure("/hibernate.cfg.xml").buildSessionFactory(); + } catch (Throwable ex) { + throw new ExceptionInInitializerError(ex); + } + } + + public static Session getSession() throws HibernateException { + return sessionFactory.openSession(); + } + +} diff --git a/LectureUpdDatabaseHibernate/src/main/resources/hibernate.cfg.xml b/LectureUpdDatabaseHibernate/src/main/resources/hibernate.cfg.xml new file mode 100644 index 0000000..6b606d1 --- /dev/null +++ b/LectureUpdDatabaseHibernate/src/main/resources/hibernate.cfg.xml @@ -0,0 +1,17 @@ + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/databasehib + root + 1111 + org.hibernate.dialect.MySQLDialect + true + + + + + \ No newline at end of file diff --git a/LectureUpdDatabaseHibernate/target/LectureUpdDatabaseHibernate-2.0.jar b/LectureUpdDatabaseHibernate/target/LectureUpdDatabaseHibernate-2.0.jar new file mode 100644 index 0000000..9482903 Binary files /dev/null and b/LectureUpdDatabaseHibernate/target/LectureUpdDatabaseHibernate-2.0.jar differ diff --git a/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/DutiesDao.class b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/DutiesDao.class new file mode 100644 index 0000000..5f0e50e Binary files /dev/null and b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/DutiesDao.class differ diff --git a/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/PasswordDao.class b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/PasswordDao.class new file mode 100644 index 0000000..fa50520 Binary files /dev/null and b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/PasswordDao.class differ diff --git a/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/RunTest.class b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/RunTest.class new file mode 100644 index 0000000..8bb4022 Binary files /dev/null and b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/RunTest.class differ diff --git a/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/UserPasswordDutiesDao.class b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/UserPasswordDutiesDao.class new file mode 100644 index 0000000..295266d Binary files /dev/null and b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/UserPasswordDutiesDao.class differ diff --git a/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/UsersDao.class b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/UsersDao.class new file mode 100644 index 0000000..014966b Binary files /dev/null and b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/dao/UsersDao.class differ diff --git a/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/entity/Duties.class b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/entity/Duties.class new file mode 100644 index 0000000..7b495cd Binary files /dev/null and b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/entity/Duties.class differ diff --git a/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/entity/Password.class b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/entity/Password.class new file mode 100644 index 0000000..0353d46 Binary files /dev/null and b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/entity/Password.class differ diff --git a/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/entity/Users.class b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/entity/Users.class new file mode 100644 index 0000000..036307b Binary files /dev/null and b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/entity/Users.class differ diff --git a/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/util/HibernateUtil.class b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/util/HibernateUtil.class new file mode 100644 index 0000000..c391bf5 Binary files /dev/null and b/LectureUpdDatabaseHibernate/target/classes/com/hibernatehomework/lectureupddatabase/util/HibernateUtil.class differ diff --git a/LectureUpdDatabaseHibernate/target/classes/hibernate.cfg.xml b/LectureUpdDatabaseHibernate/target/classes/hibernate.cfg.xml new file mode 100644 index 0000000..6b606d1 --- /dev/null +++ b/LectureUpdDatabaseHibernate/target/classes/hibernate.cfg.xml @@ -0,0 +1,17 @@ + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/databasehib + root + 1111 + org.hibernate.dialect.MySQLDialect + true + + + + + \ No newline at end of file diff --git a/LectureUpdDatabaseHibernate/target/maven-archiver/pom.properties b/LectureUpdDatabaseHibernate/target/maven-archiver/pom.properties new file mode 100644 index 0000000..02178b1 --- /dev/null +++ b/LectureUpdDatabaseHibernate/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Sat Nov 18 18:44:00 MSK 2017 +version=2.0 +groupId=com.hibernatehomework +artifactId=LectureUpdDatabaseHibernate diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..7fb9177 --- /dev/null +++ b/build.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + Builds, tests, and runs the project TextClassifierProject. + + + diff --git a/build/classes/.netbeans_automatic_build b/build/classes/.netbeans_automatic_build new file mode 100644 index 0000000..e69de29 diff --git a/build/classes/.netbeans_update_resources b/build/classes/.netbeans_update_resources new file mode 100644 index 0000000..e69de29 diff --git a/build/classes/ru/caf82/lectures/diagramBomberman/GameObject.class b/build/classes/ru/caf82/lectures/diagramBomberman/GameObject.class new file mode 100644 index 0000000..b15820a Binary files /dev/null and b/build/classes/ru/caf82/lectures/diagramBomberman/GameObject.class differ diff --git a/build/classes/ru/caf82/lectures/diagramBomberman/GameSession.class b/build/classes/ru/caf82/lectures/diagramBomberman/GameSession.class new file mode 100644 index 0000000..1bf0a8c Binary files /dev/null and b/build/classes/ru/caf82/lectures/diagramBomberman/GameSession.class differ diff --git a/build/classes/ru/caf82/lectures/diagramBomberman/Movable.class b/build/classes/ru/caf82/lectures/diagramBomberman/Movable.class new file mode 100644 index 0000000..bf8113d Binary files /dev/null and b/build/classes/ru/caf82/lectures/diagramBomberman/Movable.class differ diff --git a/build/classes/ru/caf82/lectures/diagramBomberman/Positioanable.class b/build/classes/ru/caf82/lectures/diagramBomberman/Positioanable.class new file mode 100644 index 0000000..dca9d1b Binary files /dev/null and b/build/classes/ru/caf82/lectures/diagramBomberman/Positioanable.class differ diff --git a/build/classes/ru/caf82/lectures/diagramBomberman/Temporary.class b/build/classes/ru/caf82/lectures/diagramBomberman/Temporary.class new file mode 100644 index 0000000..2fbe339 Binary files /dev/null and b/build/classes/ru/caf82/lectures/diagramBomberman/Temporary.class differ diff --git a/build/classes/ru/caf82/lectures/diagramBomberman/Tickable.class b/build/classes/ru/caf82/lectures/diagramBomberman/Tickable.class new file mode 100644 index 0000000..839dc93 Binary files /dev/null and b/build/classes/ru/caf82/lectures/diagramBomberman/Tickable.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/BoxingExample.class b/build/classes/ru/caf82/lectures/lecture02/BoxingExample.class new file mode 100644 index 0000000..dd79ebc Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/BoxingExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/BreakAndContinueExample.class b/build/classes/ru/caf82/lectures/lecture02/BreakAndContinueExample.class new file mode 100644 index 0000000..fee3117 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/BreakAndContinueExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/CalculatorExample.class b/build/classes/ru/caf82/lectures/lecture02/CalculatorExample.class new file mode 100644 index 0000000..cba6209 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/CalculatorExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/CommentsExample.class b/build/classes/ru/caf82/lectures/lecture02/CommentsExample.class new file mode 100644 index 0000000..6b31809 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/CommentsExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/ConstructorExample$Rectangular.class b/build/classes/ru/caf82/lectures/lecture02/ConstructorExample$Rectangular.class new file mode 100644 index 0000000..0134209 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/ConstructorExample$Rectangular.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/ConstructorExample.class b/build/classes/ru/caf82/lectures/lecture02/ConstructorExample.class new file mode 100644 index 0000000..29425b9 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/ConstructorExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/ForAndForEachExample.class b/build/classes/ru/caf82/lectures/lecture02/ForAndForEachExample.class new file mode 100644 index 0000000..07149a9 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/ForAndForEachExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/IfElseAndSwitchCaseExample.class b/build/classes/ru/caf82/lectures/lecture02/IfElseAndSwitchCaseExample.class new file mode 100644 index 0000000..ff3a192 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/IfElseAndSwitchCaseExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/LinkTypes.class b/build/classes/ru/caf82/lectures/lecture02/LinkTypes.class new file mode 100644 index 0000000..8c6e7f6 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/LinkTypes.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/OperatorsExample.class b/build/classes/ru/caf82/lectures/lecture02/OperatorsExample.class new file mode 100644 index 0000000..e3d6c7f Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/OperatorsExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/PrimitiveTypes.class b/build/classes/ru/caf82/lectures/lecture02/PrimitiveTypes.class new file mode 100644 index 0000000..c449979 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/PrimitiveTypes.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/StringProcessing.class b/build/classes/ru/caf82/lectures/lecture02/StringProcessing.class new file mode 100644 index 0000000..7585d1c Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/StringProcessing.class differ diff --git a/build/classes/ru/caf82/lectures/lecture02/WhileAndDoWhileExample.class b/build/classes/ru/caf82/lectures/lecture02/WhileAndDoWhileExample.class new file mode 100644 index 0000000..d5a3e54 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture02/WhileAndDoWhileExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/AbstractAnimal.class b/build/classes/ru/caf82/lectures/lecture03/AbstractAnimal.class new file mode 100644 index 0000000..ea9922f Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/AbstractAnimal.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/Animal.class b/build/classes/ru/caf82/lectures/lecture03/Animal.class new file mode 100644 index 0000000..4250e08 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/Animal.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/Cat.class b/build/classes/ru/caf82/lectures/lecture03/Cat.class new file mode 100644 index 0000000..7c4df90 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/Cat.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/CompositionExample.class b/build/classes/ru/caf82/lectures/lecture03/CompositionExample.class new file mode 100644 index 0000000..5b60a85 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/CompositionExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/Crocodile.class b/build/classes/ru/caf82/lectures/lecture03/Crocodile.class new file mode 100644 index 0000000..82bae47 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/Crocodile.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/Dishware.class b/build/classes/ru/caf82/lectures/lecture03/Dishware.class new file mode 100644 index 0000000..7a196f2 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/Dishware.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/Dog.class b/build/classes/ru/caf82/lectures/lecture03/Dog.class new file mode 100644 index 0000000..cc1a267 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/Dog.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/InheritanceExample.class b/build/classes/ru/caf82/lectures/lecture03/InheritanceExample.class new file mode 100644 index 0000000..c923df7 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/InheritanceExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/InterfaceExample.class b/build/classes/ru/caf82/lectures/lecture03/InterfaceExample.class new file mode 100644 index 0000000..7d1e20e Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/InterfaceExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/Kitty.class b/build/classes/ru/caf82/lectures/lecture03/Kitty.class new file mode 100644 index 0000000..5b37e7e Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/Kitty.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/PassByValue.class b/build/classes/ru/caf82/lectures/lecture03/PassByValue.class new file mode 100644 index 0000000..b77ff91 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/PassByValue.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/PolymorphysmExample.class b/build/classes/ru/caf82/lectures/lecture03/PolymorphysmExample.class new file mode 100644 index 0000000..7f655f9 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/PolymorphysmExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/Season$1.class b/build/classes/ru/caf82/lectures/lecture03/Season$1.class new file mode 100644 index 0000000..9c0ec61 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/Season$1.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/Season.class b/build/classes/ru/caf82/lectures/lecture03/Season.class new file mode 100644 index 0000000..591f422 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/Season.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/Tiger.class b/build/classes/ru/caf82/lectures/lecture03/Tiger.class new file mode 100644 index 0000000..6114383 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/Tiger.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/Washable.class b/build/classes/ru/caf82/lectures/lecture03/Washable.class new file mode 100644 index 0000000..79fdc8f Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/Washable.class differ diff --git a/build/classes/ru/caf82/lectures/lecture03/Zoo.class b/build/classes/ru/caf82/lectures/lecture03/Zoo.class new file mode 100644 index 0000000..0775728 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture03/Zoo.class differ diff --git a/build/classes/ru/caf82/lectures/lecture04/ExceptionCatchingExample.class b/build/classes/ru/caf82/lectures/lecture04/ExceptionCatchingExample.class new file mode 100644 index 0000000..0a918cf Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture04/ExceptionCatchingExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture04/ExceptionCatchingIhExample.class b/build/classes/ru/caf82/lectures/lecture04/ExceptionCatchingIhExample.class new file mode 100644 index 0000000..a50980c Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture04/ExceptionCatchingIhExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture04/MyExceptionClassExample.class b/build/classes/ru/caf82/lectures/lecture04/MyExceptionClassExample.class new file mode 100644 index 0000000..6443809 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture04/MyExceptionClassExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture04/StackTraceExample.class b/build/classes/ru/caf82/lectures/lecture04/StackTraceExample.class new file mode 100644 index 0000000..98a7e65 Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture04/StackTraceExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture04/TemplateForMyExceptionClass.class b/build/classes/ru/caf82/lectures/lecture04/TemplateForMyExceptionClass.class new file mode 100644 index 0000000..8e9a99f Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture04/TemplateForMyExceptionClass.class differ diff --git a/build/classes/ru/caf82/lectures/lecture04/ThrowExample$NegException.class b/build/classes/ru/caf82/lectures/lecture04/ThrowExample$NegException.class new file mode 100644 index 0000000..2afbf2d Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture04/ThrowExample$NegException.class differ diff --git a/build/classes/ru/caf82/lectures/lecture04/ThrowExample.class b/build/classes/ru/caf82/lectures/lecture04/ThrowExample.class new file mode 100644 index 0000000..22536fc Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture04/ThrowExample.class differ diff --git a/build/classes/ru/caf82/lectures/lecture04/WorkWithExceptions.class b/build/classes/ru/caf82/lectures/lecture04/WorkWithExceptions.class new file mode 100644 index 0000000..6b0beac Binary files /dev/null and b/build/classes/ru/caf82/lectures/lecture04/WorkWithExceptions.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/models/AbstractModel.class b/build/classes/ru/caf82/result/machinelearning/models/AbstractModel.class new file mode 100644 index 0000000..97c761e Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/models/AbstractModel.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/models/Boosting.class b/build/classes/ru/caf82/result/machinelearning/models/Boosting.class new file mode 100644 index 0000000..ccd3ed8 Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/models/Boosting.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/models/KNeighbourhood.class b/build/classes/ru/caf82/result/machinelearning/models/KNeighbourhood.class new file mode 100644 index 0000000..b1545b1 Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/models/KNeighbourhood.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/models/LinearKernel.class b/build/classes/ru/caf82/result/machinelearning/models/LinearKernel.class new file mode 100644 index 0000000..7938ef6 Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/models/LinearKernel.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/models/LogisticRegression.class b/build/classes/ru/caf82/result/machinelearning/models/LogisticRegression.class new file mode 100644 index 0000000..3a88880 Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/models/LogisticRegression.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/models/NaiveBayes.class b/build/classes/ru/caf82/result/machinelearning/models/NaiveBayes.class new file mode 100644 index 0000000..6c81a26 Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/models/NaiveBayes.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/models/NormalKernel.class b/build/classes/ru/caf82/result/machinelearning/models/NormalKernel.class new file mode 100644 index 0000000..ecd05cc Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/models/NormalKernel.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/preprocessing/CountVectorizer.class b/build/classes/ru/caf82/result/machinelearning/preprocessing/CountVectorizer.class new file mode 100644 index 0000000..0050427 Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/preprocessing/CountVectorizer.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/preprocessing/PorterStemmer.class b/build/classes/ru/caf82/result/machinelearning/preprocessing/PorterStemmer.class new file mode 100644 index 0000000..a4e927a Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/preprocessing/PorterStemmer.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/preprocessing/SequenceProcessor.class b/build/classes/ru/caf82/result/machinelearning/preprocessing/SequenceProcessor.class new file mode 100644 index 0000000..8708158 Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/preprocessing/SequenceProcessor.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/preprocessing/TfidfVectorizer.class b/build/classes/ru/caf82/result/machinelearning/preprocessing/TfidfVectorizer.class new file mode 100644 index 0000000..210e922 Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/preprocessing/TfidfVectorizer.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/preprocessing/Transformer.class b/build/classes/ru/caf82/result/machinelearning/preprocessing/Transformer.class new file mode 100644 index 0000000..c456de6 Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/preprocessing/Transformer.class differ diff --git a/build/classes/ru/caf82/result/machinelearning/preprocessing/WordProcessor.class b/build/classes/ru/caf82/result/machinelearning/preprocessing/WordProcessor.class new file mode 100644 index 0000000..40e1aed Binary files /dev/null and b/build/classes/ru/caf82/result/machinelearning/preprocessing/WordProcessor.class differ diff --git a/build/classes/ru/caf82/result/others/Dao.class b/build/classes/ru/caf82/result/others/Dao.class new file mode 100644 index 0000000..9888da6 Binary files /dev/null and b/build/classes/ru/caf82/result/others/Dao.class differ diff --git a/build/classes/ru/caf82/result/others/DaoImplementation.class b/build/classes/ru/caf82/result/others/DaoImplementation.class new file mode 100644 index 0000000..64bdee4 Binary files /dev/null and b/build/classes/ru/caf82/result/others/DaoImplementation.class differ diff --git a/build/classes/ru/caf82/result/others/ModelSelectionHibernateEntity.class b/build/classes/ru/caf82/result/others/ModelSelectionHibernateEntity.class new file mode 100644 index 0000000..652d262 Binary files /dev/null and b/build/classes/ru/caf82/result/others/ModelSelectionHibernateEntity.class differ diff --git a/build/classes/ru/caf82/result/others/ReviewHibernateEntity.class b/build/classes/ru/caf82/result/others/ReviewHibernateEntity.class new file mode 100644 index 0000000..853f290 Binary files /dev/null and b/build/classes/ru/caf82/result/others/ReviewHibernateEntity.class differ diff --git a/build/classes/ru/caf82/result/others/SwingModel.class b/build/classes/ru/caf82/result/others/SwingModel.class new file mode 100644 index 0000000..b306059 Binary files /dev/null and b/build/classes/ru/caf82/result/others/SwingModel.class differ diff --git a/build/classes/ru/caf82/result/others/SwingTraining.class b/build/classes/ru/caf82/result/others/SwingTraining.class new file mode 100644 index 0000000..33defa2 Binary files /dev/null and b/build/classes/ru/caf82/result/others/SwingTraining.class differ diff --git a/build/classes/ru/caf82/result/workwithfiles/FileReader.class b/build/classes/ru/caf82/result/workwithfiles/FileReader.class new file mode 100644 index 0000000..27115f0 Binary files /dev/null and b/build/classes/ru/caf82/result/workwithfiles/FileReader.class differ diff --git a/build/classes/ru/caf82/result/workwithfiles/FileWorker.class b/build/classes/ru/caf82/result/workwithfiles/FileWorker.class new file mode 100644 index 0000000..1e230d4 Binary files /dev/null and b/build/classes/ru/caf82/result/workwithfiles/FileWorker.class differ diff --git a/build/classes/ru/caf82/result/workwithfiles/FileWriter.class b/build/classes/ru/caf82/result/workwithfiles/FileWriter.class new file mode 100644 index 0000000..cf97a27 Binary files /dev/null and b/build/classes/ru/caf82/result/workwithfiles/FileWriter.class differ diff --git a/lecture14JavaSwing/build.xml b/lecture14JavaSwing/build.xml new file mode 100644 index 0000000..0253988 --- /dev/null +++ b/lecture14JavaSwing/build.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + Builds, tests, and runs the project lecture14JavaSwing. + + + diff --git a/lecture14JavaSwing/build/classes/examples/LoginWindow$1.class b/lecture14JavaSwing/build/classes/examples/LoginWindow$1.class new file mode 100644 index 0000000..f2d46fb Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/LoginWindow$1.class differ diff --git a/lecture14JavaSwing/build/classes/examples/LoginWindow.class b/lecture14JavaSwing/build/classes/examples/LoginWindow.class new file mode 100644 index 0000000..cf924e3 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/LoginWindow.class differ diff --git a/lecture14JavaSwing/build/classes/examples/ProgressBarExample$1.class b/lecture14JavaSwing/build/classes/examples/ProgressBarExample$1.class new file mode 100644 index 0000000..0087e88 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/ProgressBarExample$1.class differ diff --git a/lecture14JavaSwing/build/classes/examples/ProgressBarExample$2.class b/lecture14JavaSwing/build/classes/examples/ProgressBarExample$2.class new file mode 100644 index 0000000..d4036e1 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/ProgressBarExample$2.class differ diff --git a/lecture14JavaSwing/build/classes/examples/ProgressBarExample$3.class b/lecture14JavaSwing/build/classes/examples/ProgressBarExample$3.class new file mode 100644 index 0000000..da2d1d0 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/ProgressBarExample$3.class differ diff --git a/lecture14JavaSwing/build/classes/examples/ProgressBarExample.class b/lecture14JavaSwing/build/classes/examples/ProgressBarExample.class new file mode 100644 index 0000000..5b4bc26 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/ProgressBarExample.class differ diff --git a/lecture14JavaSwing/build/classes/examples/ScrollPaneExample$1.class b/lecture14JavaSwing/build/classes/examples/ScrollPaneExample$1.class new file mode 100644 index 0000000..747b0dc Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/ScrollPaneExample$1.class differ diff --git a/lecture14JavaSwing/build/classes/examples/ScrollPaneExample.class b/lecture14JavaSwing/build/classes/examples/ScrollPaneExample.class new file mode 100644 index 0000000..1c167a0 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/ScrollPaneExample.class differ diff --git a/lecture14JavaSwing/build/classes/examples/SliderExample$1.class b/lecture14JavaSwing/build/classes/examples/SliderExample$1.class new file mode 100644 index 0000000..3881fc0 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/SliderExample$1.class differ diff --git a/lecture14JavaSwing/build/classes/examples/SliderExample$2.class b/lecture14JavaSwing/build/classes/examples/SliderExample$2.class new file mode 100644 index 0000000..8de0bcf Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/SliderExample$2.class differ diff --git a/lecture14JavaSwing/build/classes/examples/SliderExample.class b/lecture14JavaSwing/build/classes/examples/SliderExample.class new file mode 100644 index 0000000..27bad29 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/SliderExample.class differ diff --git a/lecture14JavaSwing/build/classes/examples/TreeExample$1.class b/lecture14JavaSwing/build/classes/examples/TreeExample$1.class new file mode 100644 index 0000000..4a32f24 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/TreeExample$1.class differ diff --git a/lecture14JavaSwing/build/classes/examples/TreeExample.class b/lecture14JavaSwing/build/classes/examples/TreeExample.class new file mode 100644 index 0000000..29c6101 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/TreeExample.class differ diff --git a/lecture14JavaSwing/build/classes/examples/jTable/ScrollPaneExample$1.class b/lecture14JavaSwing/build/classes/examples/jTable/ScrollPaneExample$1.class new file mode 100644 index 0000000..3360c36 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/jTable/ScrollPaneExample$1.class differ diff --git a/lecture14JavaSwing/build/classes/examples/table/ModelForTable.class b/lecture14JavaSwing/build/classes/examples/table/ModelForTable.class new file mode 100644 index 0000000..9c962fb Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/table/ModelForTable.class differ diff --git a/lecture14JavaSwing/build/classes/examples/table/TableExample$1.class b/lecture14JavaSwing/build/classes/examples/table/TableExample$1.class new file mode 100644 index 0000000..f0efd70 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/table/TableExample$1.class differ diff --git a/lecture14JavaSwing/build/classes/examples/table/TableExample.class b/lecture14JavaSwing/build/classes/examples/table/TableExample.class new file mode 100644 index 0000000..0c87cb8 Binary files /dev/null and b/lecture14JavaSwing/build/classes/examples/table/TableExample.class differ diff --git a/lecture14JavaSwing/build/classes/jTable/NewClass.class b/lecture14JavaSwing/build/classes/jTable/NewClass.class new file mode 100644 index 0000000..da95b30 Binary files /dev/null and b/lecture14JavaSwing/build/classes/jTable/NewClass.class differ diff --git a/lecture14JavaSwing/manifest.mf b/lecture14JavaSwing/manifest.mf new file mode 100644 index 0000000..1574df4 --- /dev/null +++ b/lecture14JavaSwing/manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/lecture14JavaSwing/nbproject/build-impl.xml b/lecture14JavaSwing/nbproject/build-impl.xml new file mode 100644 index 0000000..4120927 --- /dev/null +++ b/lecture14JavaSwing/nbproject/build-impl.xml @@ -0,0 +1,1420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No tests executed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + Must select one file in the IDE or set profile.class + This target only works when run from inside the NetBeans IDE. + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + Must select some files in the IDE or set test.includes + + + + + Must select one file in the IDE or set run.class + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + Must select some files in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + Must select one file in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lecture14JavaSwing/nbproject/genfiles.properties b/lecture14JavaSwing/nbproject/genfiles.properties new file mode 100644 index 0000000..8bacd2d --- /dev/null +++ b/lecture14JavaSwing/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=d9e52c5b +build.xml.script.CRC32=2b9bbdd9 +build.xml.stylesheet.CRC32=8064a381@1.80.1.48 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=d9e52c5b +nbproject/build-impl.xml.script.CRC32=024b6ea2 +nbproject/build-impl.xml.stylesheet.CRC32=830a3534@1.80.1.48 diff --git a/lecture14JavaSwing/nbproject/private/private.properties b/lecture14JavaSwing/nbproject/private/private.properties new file mode 100644 index 0000000..582f630 --- /dev/null +++ b/lecture14JavaSwing/nbproject/private/private.properties @@ -0,0 +1,2 @@ +compile.on.save=true +user.properties.file=C:\\Users\\\u0410\u043b\u0435\u043d\u0430\\AppData\\Roaming\\NetBeans\\8.2\\build.properties diff --git a/lecture14JavaSwing/nbproject/private/private.xml b/lecture14JavaSwing/nbproject/private/private.xml new file mode 100644 index 0000000..284eeec --- /dev/null +++ b/lecture14JavaSwing/nbproject/private/private.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/lecture14JavaSwing/nbproject/project.properties b/lecture14JavaSwing/nbproject/project.properties new file mode 100644 index 0000000..25c537d --- /dev/null +++ b/lecture14JavaSwing/nbproject/project.properties @@ -0,0 +1,74 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processor.options= +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# \u0424\u0430\u0439\u043b\u044b \u0432 \u043a\u0430\u0442\u0430\u043b\u043e\u0433\u0435 build.classes.dir, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044f \u0438\u0441\u043a\u043b\u044e\u0447\u0438\u0442\u044c \u0438\u0437 \u0440\u0430\u0441\u043f\u0440\u043e\u0441\u0442\u0440\u0430\u043d\u044f\u0435\u043c\u043e\u0433\u043e \u0430\u0440\u0445\u0438\u0432\u0430 jar +dist.archive.excludes= +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/lecture14JavaSwing.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.external.vm=true +javac.processorpath=\ + ${javac.classpath} +javac.source=1.8 +javac.target=1.8 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +main.class= +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/lecture14JavaSwing/nbproject/project.xml b/lecture14JavaSwing/nbproject/project.xml new file mode 100644 index 0000000..40ff491 --- /dev/null +++ b/lecture14JavaSwing/nbproject/project.xml @@ -0,0 +1,15 @@ + + + org.netbeans.modules.java.j2seproject + + + lecture14JavaSwing + + + + + + + + + diff --git a/lecture14JavaSwing/src/examples/JText.java b/lecture14JavaSwing/src/examples/JText.java new file mode 100644 index 0000000..7121782 --- /dev/null +++ b/lecture14JavaSwing/src/examples/JText.java @@ -0,0 +1,156 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package javaswing; + +import java.awt.Dimension; +import java.awt.GridBagLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; + +/** + * + * @author admin + */ +public class JText{ + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + JFrame frame = new JFrame("title form"); + + frame.setSize(600, 400); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setLocationRelativeTo(null); + frame.setLayout(new GridBagLayout()); + + + /////////JText + + /*JTextField textField = new JTextField(20); + JTextField textField2 = new JTextField(20); + textField.setHorizontalAlignment(JTextField.LEFT); + //textField.setText("My Test Text"); + JButton button = new JButton("klick"); + button.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + textField2.setText(textField.getText()); + } + }); + + frame.add(textField); + frame.add(textField2); + frame.add(button); + + */ + + ///////////JPasswordField + + + /*JPasswordField PasFie = new JPasswordField("", 20); + JTextField textField = new JTextField(20); + JButton button = new JButton("klick"); + button.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + //textField.setText(PasFie.getText()); + textField.setText(new String(PasFie.getPassword())); + } + }); + //PasFie.setEchoChar('*'); + //System.out.println(PasFie.getPassword()); + frame.add(PasFie); + frame.add(textField); + frame.add(button); + */ + + //////////JTextArea + + /*JButton button = new JButton("klick"); + JTextArea textArea = new JTextArea(5, 20); + textArea.setLineWrap(true); + textArea.setWrapStyleWord(true); //перенос слова на след строку + //textArea.append("Область для ввода текстового содержимого"); + //textArea.insert("ВСТАВКА", 30); + button.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + //textField.setText(PasFie.getText()); + FileWriter file = new FileWriter("testArea.txt"); + file.write(textArea.getText()); + file.close(); + textArea.setText("Текст записан"); + } catch (IOException ex) { + System.out.println("exception"); + } + } + }); + + frame.add(textArea); + frame.add(button); + + */ + + + //////JComboBox + + + /* + String []str = {"point 1", "point 2", "point 3"}; + JComboBox myBox = new JComboBox(str); + //myBox.setEditable(true); + //myBox.addItem("point 4"); + //myBox.insertItemAt("new point", 2); + //System.out.println(myBox.getItemAt(2)); + //myBox.removeAllItems(); + //myBox.removeItem("new point"); + //myBox.setSelectedItem("point 3"); + //System.out.println(myBox.getSelectedItem()); + frame.add(myBox); + */ + + + //////JList + + + /* String []str = {"Cat", "Dog", "Pig", "Bird", "Fish", "Rabbit", "11", "22", "33", "44", "55", "66", "77", "88", "99"}; + + JPanel mainPanel = new JPanel(); + JList myList = new JList(str); + myList.setLayoutOrientation(JList.VERTICAL); + //myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + System.out.println(myList.getSelectedIndex()); + + JScrollPane scroll = new JScrollPane(myList); + scroll.setPreferredSize(new Dimension(200, 100)); + mainPanel.add(scroll); + frame.getContentPane().add(mainPanel); + */ + + frame.setVisible(true); + + + } + +} diff --git a/lecture14JavaSwing/src/examples/LoginWindow.java b/lecture14JavaSwing/src/examples/LoginWindow.java new file mode 100644 index 0000000..4ff8cd3 --- /dev/null +++ b/lecture14JavaSwing/src/examples/LoginWindow.java @@ -0,0 +1,61 @@ + +package examples; + +import javax.swing.*; +import javax.swing.border.EmptyBorder; + +public class LoginWindow extends JFrame { + +/* Для того, чтобы впоследствии обращаться к содержимому текстовых полей, рекомендуется сделать их членами класса окна */ +JTextField loginField; +JPasswordField passwordField; + +LoginWindow(){ +super("Вход в систему"); +setDefaultCloseOperation(EXIT_ON_CLOSE); +// Настраиваем первую горизонтальную панель (для ввода логина) +Box box1 = Box.createHorizontalBox(); +JLabel loginLabel = new JLabel("Логин:"); +loginField = new JTextField(15); +box1.add(loginLabel); +box1.add(Box.createHorizontalStrut(6)); +box1.add(loginField); +// Настраиваем вторую горизонтальную панель (для ввода пароля) +Box box2 = Box.createHorizontalBox(); +JLabel passwordLabel = new JLabel("Пароль:"); +passwordField = new JPasswordField(15); +box2.add(passwordLabel); +box2.add(Box.createHorizontalStrut(6)); +box2.add(passwordField); +// Настраиваем третью горизонтальную панель (с кнопками) +Box box3 = Box.createHorizontalBox(); +JButton ok = new JButton("OK"); +JButton cancel = new JButton("Отмена"); +box3.add(Box.createHorizontalGlue()); +box3.add(ok); +box3.add(Box.createHorizontalStrut(12)); +box3.add(cancel); +// Уточняем размеры компонентов +loginLabel.setPreferredSize(passwordLabel.getPreferredSize()); +// Размещаем три горизонтальные панели на одной вертикальной +Box mainBox = Box.createVerticalBox(); +mainBox.setBorder(new EmptyBorder(12,12,12,12)); +mainBox.add(box1); +mainBox.add(Box.createVerticalStrut(12)); +mainBox.add(box2); +mainBox.add(Box.createVerticalStrut(17)); +mainBox.add(box3); +setContentPane(mainBox); +pack(); +setResizable(false); +setVisible(true); +} + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + new LoginWindow(); + } + }); + } +} \ No newline at end of file diff --git a/lecture14JavaSwing/src/examples/ProgressBarExample.java b/lecture14JavaSwing/src/examples/ProgressBarExample.java new file mode 100644 index 0000000..9e9993c --- /dev/null +++ b/lecture14JavaSwing/src/examples/ProgressBarExample.java @@ -0,0 +1,71 @@ +package examples; + +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JProgressBar; +import javax.swing.SwingUtilities; +import javax.swing.Timer; + +/** + * + * @author Alena + */ +public class ProgressBarExample { + + final static int interval = 1000; + int i; + Timer t; + JButton button; + JProgressBar progress; + + public ProgressBarExample() { + + JFrame frame = new JFrame(); + frame.getContentPane().setLayout(new GridLayout(2, 1)); + button = new JButton("Start"); + button.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + i = 0; + t.start(); + button.setEnabled(false); + } + }); + progress = new JProgressBar(0, 20); + progress.setValue(0); + progress.setStringPainted(true); + t = new Timer(interval, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (i==20) { + t.stop(); + button.setEnabled(true); + } else { + i = i+2; + progress.setValue(i); + System.out.println(progress.getPercentComplete()); + } + } + }); + frame.getContentPane().add(progress); + frame.getContentPane().add(button); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setSize(400,200); + frame.setResizable(false); + frame.setVisible(true); + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + new ProgressBarExample(); + } + }); + } + +} diff --git a/lecture14JavaSwing/src/examples/ScrollPaneExample.java b/lecture14JavaSwing/src/examples/ScrollPaneExample.java new file mode 100644 index 0000000..827c8f9 --- /dev/null +++ b/lecture14JavaSwing/src/examples/ScrollPaneExample.java @@ -0,0 +1,51 @@ +package examples; + +import java.awt.GridLayout; +import javax.swing.JFrame; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.ScrollPaneConstants; +import javax.swing.SwingUtilities; + +/** + * + * @author Alena + */ +public class ScrollPaneExample { + + ScrollPaneExample() { + JFrame frame = new JFrame(); + frame.getContentPane().setLayout(new GridLayout(2, 1)); + JTextArea text = new JTextArea(); + text.setText("Ученые также предполагают, что черно-белый окрас панды связан" + + "\n" + "с неспособностью животного переваривать какие-либо продукты," + + "\n" + "кроме бамбука. Это означает, что панда не может накопить " + + "\n" + "достаточное количество жира, чтобы зимой впадать в спячку," + + "\n" + "как это делают медведи. Таким образом, панда вынуждена " + + "\n" + "оставаться активной круглый год, постоянно меняя места " + + "\n" + "обитания, которые варьируются от снежных гор " + + "\n" + "до тропических лесов. Вместе с тем ученые полагают, " + + "\n" + "что темные уши панды пугают хищников, придавая им более" + + "\n" + "свирепый вид, а черные пятна вокруг глаз помогают " + + "\n" + "пандам узнавать друг друга среди других животных."); + JScrollPane pane = new JScrollPane(text); + pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + pane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); + //frame.getContentPane().add(text); + frame.getContentPane().add(pane); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setSize(400,200); + frame.setResizable(false); + frame.setVisible(true); + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + new ScrollPaneExample(); + } + }); + } +} \ No newline at end of file diff --git a/lecture14JavaSwing/src/examples/SliderExample.java b/lecture14JavaSwing/src/examples/SliderExample.java new file mode 100644 index 0000000..a4a80bd --- /dev/null +++ b/lecture14JavaSwing/src/examples/SliderExample.java @@ -0,0 +1,51 @@ +package examples; + +import java.awt.GridLayout; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JSlider; +import javax.swing.SwingUtilities; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +/** + * + * @author Alena + */ +public class SliderExample { + + public SliderExample() { + JFrame frame = new JFrame(); + JSlider slider = new JSlider(); + slider.setOrientation(0); + slider.setMaximum(100); + slider.setMinimum(0); + slider.setMajorTickSpacing(10); + slider.setPaintLabels(true); + slider.setValue(30); + JLabel label = new JLabel(); + label.setText("0"); + slider.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + label.setText(String.valueOf(slider.getValue())); + } + }); + frame.getContentPane().setLayout(new GridLayout(2, 1)); + frame.getContentPane().add(slider); + frame.getContentPane().add(label); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setSize(400,200); + frame.setVisible(true); + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + new SliderExample(); + } + }); + } +} \ No newline at end of file diff --git a/lecture14JavaSwing/src/examples/TreeExample.java b/lecture14JavaSwing/src/examples/TreeExample.java new file mode 100644 index 0000000..8e86d9c --- /dev/null +++ b/lecture14JavaSwing/src/examples/TreeExample.java @@ -0,0 +1,41 @@ +package examples; + +import java.awt.GridLayout; +import javax.swing.JFrame; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultMutableTreeNode; + +/** + * + * @author Dmitry + */ +public class TreeExample { + + public TreeExample() { + JFrame frame = new JFrame(); + DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); + DefaultMutableTreeNode vegetableNode = new DefaultMutableTreeNode("Vegetables"); + DefaultMutableTreeNode fruitNode = new DefaultMutableTreeNode("Fruits"); + root.add(vegetableNode); + root.add(fruitNode); + JTree tree = new JTree(root); + + frame.getContentPane().setLayout(new GridLayout(2, 1)); + frame.getContentPane().add(tree); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setSize(400,200); + frame.setVisible(true); + + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + new TreeExample(); + } + }); + } +} diff --git a/lecture14JavaSwing/src/examples/table/ModelForTable.java b/lecture14JavaSwing/src/examples/table/ModelForTable.java new file mode 100644 index 0000000..ad0f9f9 --- /dev/null +++ b/lecture14JavaSwing/src/examples/table/ModelForTable.java @@ -0,0 +1,76 @@ +package examples.table; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import javax.swing.event.TableModelListener; +import javax.swing.table.TableModel; + +/** + * + * @author Alena + */ +public class ModelForTable implements TableModel{ + private Set listeners = new HashSet(); + private ArrayList inner; + + public ModelForTable(ArrayList inner) { + this.inner = inner; + } + + @Override + public int getRowCount() { + return inner.size(); + } + + @Override + public int getColumnCount() { + return 3; + } + + @Override + public String getColumnName(int columnIndex) { + switch(columnIndex) { + case 0: + return "Artist"; + case 1: + return "Album"; + case 2: + return "Song"; + } + return ""; + } + + @Override + public Class getColumnClass(int columnIndex) { + return String.class; + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + String[] thisRow = inner.get(rowIndex); + return thisRow[columnIndex]; + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + String[] thisRow = inner.get(rowIndex); + thisRow[columnIndex] = (String) aValue; + inner.set(rowIndex, thisRow); + } + + @Override + public void addTableModelListener(TableModelListener l) { + listeners.add(l); + } + + @Override + public void removeTableModelListener(TableModelListener l) { + listeners.remove(l); + } +} \ No newline at end of file diff --git a/lecture14JavaSwing/src/examples/table/TableExample.java b/lecture14JavaSwing/src/examples/table/TableExample.java new file mode 100644 index 0000000..eeb74e2 --- /dev/null +++ b/lecture14JavaSwing/src/examples/table/TableExample.java @@ -0,0 +1,43 @@ +package examples.table; + +import java.util.ArrayList; +import java.util.List; +import javax.swing.JFrame; +import javax.swing.JTable; +import javax.swing.SwingUtilities; + +/** + * + * @author Alena + */ +public class TableExample { + + TableExample() { + JFrame frame = new JFrame(); + JTable myTable = createTable(); + frame.getContentPane().add(myTable); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setSize(400,200); + frame.setVisible(true); + } + + private JTable createTable() { + List list = new ArrayList<>(); + list.add(new String[]{"Metallica", "Master of Puppets", "Disposable Heroes"}); + list.add(new String[]{"Megadeth", "Rust In Peace", "Dawn Patrol"}); + list.add(new String[]{"Deep Purple", "Machine Head", "Smoke on the Water"}); + ModelForTable model = new ModelForTable((ArrayList) list); + JTable myTable = new JTable(model); + return myTable; + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + new TableExample(); + } + }); + } +} \ No newline at end of file diff --git a/lectureDatabaseJDBC/build.xml b/lectureDatabaseJDBC/build.xml new file mode 100644 index 0000000..b6a2ea0 --- /dev/null +++ b/lectureDatabaseJDBC/build.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + Builds, tests, and runs the project lectureDatabaseJDBC. + + + diff --git a/lectureDatabaseJDBC/manifest.mf b/lectureDatabaseJDBC/manifest.mf new file mode 100644 index 0000000..1574df4 --- /dev/null +++ b/lectureDatabaseJDBC/manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/lectureDatabaseJDBC/nbproject/build-impl.xml b/lectureDatabaseJDBC/nbproject/build-impl.xml new file mode 100644 index 0000000..cc111e8 --- /dev/null +++ b/lectureDatabaseJDBC/nbproject/build-impl.xml @@ -0,0 +1,1420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No tests executed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + Must select one file in the IDE or set profile.class + This target only works when run from inside the NetBeans IDE. + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + Must select some files in the IDE or set test.includes + + + + + Must select one file in the IDE or set run.class + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + Must select some files in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + Must select one file in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lectureDatabaseJDBC/nbproject/genfiles.properties b/lectureDatabaseJDBC/nbproject/genfiles.properties new file mode 100644 index 0000000..4fdda32 --- /dev/null +++ b/lectureDatabaseJDBC/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=585cc437 +build.xml.script.CRC32=2ee15279 +build.xml.stylesheet.CRC32=8064a381@1.80.1.48 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=585cc437 +nbproject/build-impl.xml.script.CRC32=dc3a77ac +nbproject/build-impl.xml.stylesheet.CRC32=830a3534@1.80.1.48 diff --git a/lectureDatabaseJDBC/nbproject/private/private.properties b/lectureDatabaseJDBC/nbproject/private/private.properties new file mode 100644 index 0000000..582f630 --- /dev/null +++ b/lectureDatabaseJDBC/nbproject/private/private.properties @@ -0,0 +1,2 @@ +compile.on.save=true +user.properties.file=C:\\Users\\\u0410\u043b\u0435\u043d\u0430\\AppData\\Roaming\\NetBeans\\8.2\\build.properties diff --git a/lectureDatabaseJDBC/nbproject/private/private.xml b/lectureDatabaseJDBC/nbproject/private/private.xml new file mode 100644 index 0000000..db03bb0 --- /dev/null +++ b/lectureDatabaseJDBC/nbproject/private/private.xml @@ -0,0 +1,4 @@ + + + + diff --git a/lectureDatabaseJDBC/nbproject/project.properties b/lectureDatabaseJDBC/nbproject/project.properties new file mode 100644 index 0000000..9ce7ccf --- /dev/null +++ b/lectureDatabaseJDBC/nbproject/project.properties @@ -0,0 +1,79 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processor.options=-Aeclipselink.canonicalmodel.use_static_factory=false +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# \u0424\u0430\u0439\u043b\u044b \u0432 \u043a\u0430\u0442\u0430\u043b\u043e\u0433\u0435 build.classes.dir, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044f \u0438\u0441\u043a\u043b\u044e\u0447\u0438\u0442\u044c \u0438\u0437 \u0440\u0430\u0441\u043f\u0440\u043e\u0441\u0442\u0440\u0430\u043d\u044f\u0435\u043c\u043e\u0433\u043e \u0430\u0440\u0445\u0438\u0432\u0430 jar +dist.archive.excludes= +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/lectureDatabaseJDBC.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +file.reference.com.mysql.jdbc_5.1.5.jar=../../../Downloads/com.mysql.jdbc_5.1.5.jar +file.reference.javax.persistence.jar=../../../Downloads/javax.persistence.jar +includes=** +jar.compress=false +javac.classpath=\ + ${file.reference.com.mysql.jdbc_5.1.5.jar}:\ + ${file.reference.javax.persistence.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.external.vm=true +javac.processorpath=\ + ${javac.classpath}:\ + ${libs.hibernate4-persistencemodelgen.classpath} +javac.source=1.8 +javac.target=1.8 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +main.class= +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/lectureDatabaseJDBC/nbproject/project.xml b/lectureDatabaseJDBC/nbproject/project.xml new file mode 100644 index 0000000..966ac09 --- /dev/null +++ b/lectureDatabaseJDBC/nbproject/project.xml @@ -0,0 +1,15 @@ + + + org.netbeans.modules.java.j2seproject + + + lectureDatabaseJDBC + + + + + + + + + diff --git a/lectureDatabaseJDBC/src/JDBC/SwingAddFrame.form b/lectureDatabaseJDBC/src/JDBC/SwingAddFrame.form new file mode 100644 index 0000000..20f27e7 --- /dev/null +++ b/lectureDatabaseJDBC/src/JDBC/SwingAddFrame.form @@ -0,0 +1,128 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/lectureDatabaseJDBC/src/JDBC/SwingAddFrame.java b/lectureDatabaseJDBC/src/JDBC/SwingAddFrame.java new file mode 100644 index 0000000..d76b68e --- /dev/null +++ b/lectureDatabaseJDBC/src/JDBC/SwingAddFrame.java @@ -0,0 +1,184 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package JDBC; + +import java.awt.Color; + +/** + * + * @author Алена + */ +public class SwingAddFrame extends javax.swing.JFrame { + + /** + * Creates new form AddFrame + */ + public SwingAddFrame() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("checked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + loginField = new javax.swing.JTextField(); + ageField = new javax.swing.JTextField(); + passwordField = new javax.swing.JPasswordField(); + addButton = new javax.swing.JButton(); + login = new javax.swing.JLabel(); + age = new javax.swing.JLabel(); + password = new javax.swing.JLabel(); + error = new javax.swing.JLabel(); + + setLocation(new java.awt.Point(300, 300)); + setResizable(false); + + loginField.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + loginFieldActionPerformed(evt); + } + }); + + passwordField.setToolTipText(""); + + addButton.setText("Добавить"); + addButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + addButtonActionPerformed(evt); + } + }); + + login.setText("Логин:"); + + age.setText("Возраст:"); + + password.setText("Пароль:"); + + error.setText("Введите данные:"); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(113, 113, 113) + .addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(83, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(login, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(age) + .addComponent(password)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(loginField) + .addComponent(ageField) + .addComponent(passwordField, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)) + .addGap(49, 49, 49)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addComponent(error) + .addGap(135, 135, 135)))) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(32, 32, 32) + .addComponent(error) + .addGap(18, 18, 18) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(loginField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(login, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGap(18, 18, 18) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(age, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(ageField)) + .addGap(18, 18, 18) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(password, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(passwordField)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE) + .addComponent(addButton) + .addGap(31, 31, 31)) + ); + + pack(); + }// //GEN-END:initComponents + + private void loginFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginFieldActionPerformed + // TODO add your handling code here: + }//GEN-LAST:event_loginFieldActionPerformed + + private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed + if ((ageField.getText().equals(null))||(loginField.getText().equals(null))||(passwordField.getText().equals(null))) { + error.setText("Введите данные."); + error.setForeground(Color.red); + } + try { + Integer.valueOf(ageField.getText()); + }catch (NumberFormatException e) { + error.setText("Некорректный ввод возраста."); + error.setForeground(Color.red); + } + WorkWithDatabaseJDBC wwdj = new WorkWithDatabaseJDBC(); + wwdj.insertInto(loginField.getText(), Integer.valueOf(ageField.getText()), new String(passwordField.getPassword())); + setVisible(false); + }//GEN-LAST:event_addButtonActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(SwingAddFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(SwingAddFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(SwingAddFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(SwingAddFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + // + + /* Create and display the form */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new SwingAddFrame().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton addButton; + private javax.swing.JLabel age; + private javax.swing.JTextField ageField; + private javax.swing.JLabel error; + private javax.swing.JLabel login; + private javax.swing.JTextField loginField; + private javax.swing.JLabel password; + private javax.swing.JPasswordField passwordField; + // End of variables declaration//GEN-END:variables +} diff --git a/lectureDatabaseJDBC/src/JDBC/SwingCheckPass.form b/lectureDatabaseJDBC/src/JDBC/SwingCheckPass.form new file mode 100644 index 0000000..dde66df --- /dev/null +++ b/lectureDatabaseJDBC/src/JDBC/SwingCheckPass.form @@ -0,0 +1,117 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/lectureDatabaseJDBC/src/JDBC/SwingCheckPass.java b/lectureDatabaseJDBC/src/JDBC/SwingCheckPass.java new file mode 100644 index 0000000..f84aa90 --- /dev/null +++ b/lectureDatabaseJDBC/src/JDBC/SwingCheckPass.java @@ -0,0 +1,174 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package JDBC; + +import java.awt.Color; + +/** + * + * @author Алена + */ +public class SwingCheckPass extends javax.swing.JFrame { + + /** + * Creates new form SwingCheckPass + */ + public SwingCheckPass() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("checked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + label = new javax.swing.JLabel(); + login = new javax.swing.JLabel(); + pass = new javax.swing.JLabel(); + loginfield = new javax.swing.JTextField(); + passfield = new javax.swing.JPasswordField(); + checklabel = new javax.swing.JLabel(); + checkBut = new javax.swing.JButton(); + + setLocation(new java.awt.Point(300, 300)); + setResizable(false); + + label.setText("Введите логин и пароль:"); + + login.setText("Логин:"); + + pass.setText("Пароль:"); + + passfield.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + passfieldActionPerformed(evt); + } + }); + + checklabel.setText("Введенные логин и пароль:"); + + checkBut.setText("Проверить"); + checkBut.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkButActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(51, 51, 51) + .addComponent(checklabel)) + .addGroup(layout.createSequentialGroup() + .addGap(37, 37, 37) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(pass) + .addComponent(login)) + .addGap(58, 58, 58) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(checkBut, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(label) + .addComponent(loginfield) + .addComponent(passfield, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE))))) + .addContainerGap(51, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(22, 22, 22) + .addComponent(label) + .addGap(38, 38, 38) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(loginfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(login)) + .addGap(18, 18, 18) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(pass) + .addComponent(passfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(18, 18, 18) + .addComponent(checkBut, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(checklabel) + .addGap(19, 19, 19)) + ); + + pack(); + }// //GEN-END:initComponents + + private void passfieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passfieldActionPerformed + // TODO add your handling code here: + }//GEN-LAST:event_passfieldActionPerformed + + private void checkButActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkButActionPerformed + WorkWithDatabaseJDBC wwdj = new WorkWithDatabaseJDBC(); + if ((loginfield.getText().equals(null))||(passfield.getText().equals(null))) { + label.setText("Введите данные."); + label.setForeground(Color.red); + } + if(wwdj.checkPass(loginfield.getText(), new String(passfield.getPassword()))) { + checklabel.setText("Введенные логин и пароль: корректны."); + checklabel.setForeground(Color.green); + } else { + checklabel.setText("Введенные логин и пароль: некорректны."); + checklabel.setForeground(Color.red); + } + }//GEN-LAST:event_checkButActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(SwingCheckPass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(SwingCheckPass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(SwingCheckPass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(SwingCheckPass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + // + + /* Create and display the form */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new SwingCheckPass().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton checkBut; + private javax.swing.JLabel checklabel; + private javax.swing.JLabel label; + private javax.swing.JLabel login; + private javax.swing.JTextField loginfield; + private javax.swing.JLabel pass; + private javax.swing.JPasswordField passfield; + // End of variables declaration//GEN-END:variables +} diff --git a/lectureDatabaseJDBC/src/JDBC/SwingMainClass.form b/lectureDatabaseJDBC/src/JDBC/SwingMainClass.form new file mode 100644 index 0000000..021111e --- /dev/null +++ b/lectureDatabaseJDBC/src/JDBC/SwingMainClass.form @@ -0,0 +1,134 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/lectureDatabaseJDBC/src/JDBC/SwingMainClass.java b/lectureDatabaseJDBC/src/JDBC/SwingMainClass.java new file mode 100644 index 0000000..1679753 --- /dev/null +++ b/lectureDatabaseJDBC/src/JDBC/SwingMainClass.java @@ -0,0 +1,186 @@ + +package JDBC; + +/** + * + * @author Алена + */ +public class SwingMainClass extends javax.swing.JFrame { + + /** + * Creates new form DatabaseJDBS + */ + public SwingMainClass() { + initComponents(); + + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("checked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + myTable = new javax.swing.JScrollPane(); + jTable1 = new javax.swing.JTable(); + addBut = new javax.swing.JButton(); + updateTable = new javax.swing.JButton(); + delBut = new javax.swing.JButton(); + testBut = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + setTitle("Database JDBC"); + setLocation(new java.awt.Point(100, 100)); + + myTable.setPreferredSize(new java.awt.Dimension(580, 250)); + + WorkWithDatabaseJDBC wwdj = new WorkWithDatabaseJDBC(); + SwingModelForTable mft = new SwingModelForTable(wwdj.loginAndAge); + jTable1.setModel(mft); + jTable1.addMouseListener(new java.awt.event.MouseAdapter() { + public void mouseClicked(java.awt.event.MouseEvent evt) { + jTable1MouseClicked(evt); + } + }); + myTable.setViewportView(jTable1); + + addBut.setText("Добавить пользователя"); + addBut.setToolTipText(""); + addBut.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + addButActionPerformed(evt); + } + }); + + updateTable.setText("Обновить таблицу"); + updateTable.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + updateTableActionPerformed(evt); + } + }); + + delBut.setText("Удалить пользователя"); + delBut.setEnabled(false); + delBut.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + delButActionPerformed(evt); + } + }); + + testBut.setText("Проверить пароль"); + testBut.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + testButActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(myTable, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addComponent(addBut) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(updateTable, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(delBut) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(testBut, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(50, 50, 50) + .addComponent(myTable, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(addBut, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE) + .addComponent(updateTable, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(delBut, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(testBut, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap(59, Short.MAX_VALUE)) + ); + + pack(); + }// //GEN-END:initComponents + + private void addButActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButActionPerformed + SwingAddFrame af = new SwingAddFrame(); + af.setVisible(true); + }//GEN-LAST:event_addButActionPerformed + + private void updateTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateTableActionPerformed + WorkWithDatabaseJDBC wwdj = new WorkWithDatabaseJDBC(); + SwingModelForTable mft = new SwingModelForTable(wwdj.loginAndAge); + jTable1.setModel(mft); + }//GEN-LAST:event_updateTableActionPerformed + + private void delButActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delButActionPerformed + if ((jTable1.getSelectedRow())!=(-1)) { + WorkWithDatabaseJDBC wwdj = new WorkWithDatabaseJDBC(); + wwdj.deleteFrom(Integer.valueOf((String)(jTable1.getValueAt(jTable1.getSelectedRow(), 0)))); + } + }//GEN-LAST:event_delButActionPerformed + + private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked + delBut.setEnabled(true); + }//GEN-LAST:event_jTable1MouseClicked + + private void testButActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testButActionPerformed + SwingCheckPass scp = new SwingCheckPass(); + scp.setVisible(true); + }//GEN-LAST:event_testButActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(SwingMainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(SwingMainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(SwingMainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(SwingMainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + // + + /* Create and display the form */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new SwingMainClass().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton addBut; + private javax.swing.JButton delBut; + private javax.swing.JTable jTable1; + private javax.swing.JScrollPane myTable; + private javax.swing.JButton testBut; + private javax.swing.JButton updateTable; + // End of variables declaration//GEN-END:variables +} diff --git a/lectureDatabaseJDBC/src/JDBC/SwingModelForTable.java b/lectureDatabaseJDBC/src/JDBC/SwingModelForTable.java new file mode 100644 index 0000000..67f7ad0 --- /dev/null +++ b/lectureDatabaseJDBC/src/JDBC/SwingModelForTable.java @@ -0,0 +1,81 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package JDBC; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import javax.swing.event.TableModelListener; +import javax.swing.table.TableModel; + +/** + * + * @author Алена + */ +public class SwingModelForTable implements TableModel{ + private Set listeners = new HashSet(); + private List inner; + + public SwingModelForTable(List inner) { + this.inner = inner; + } + + @Override + public int getRowCount() { + return inner.size(); + } + + @Override + public int getColumnCount() { + return 3; + } + + @Override + public String getColumnName(int columnIndex) { + switch(columnIndex) { + case 0: + return "ID"; + case 1: + return "Логин"; + case 2: + return "Возраст"; + } + return ""; + } + + @Override + public Class getColumnClass(int columnIndex) { + return String.class; + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + String[] thisRow = inner.get(rowIndex); + return thisRow[columnIndex]; + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + String[] thisRow = inner.get(rowIndex); + thisRow[columnIndex] = (String) aValue; + inner.set(rowIndex, thisRow); + } + + @Override + public void addTableModelListener(TableModelListener l) { + listeners.add(l); + } + + @Override + public void removeTableModelListener(TableModelListener l) { + listeners.remove(l); + } +} \ No newline at end of file diff --git a/lectureDatabaseJDBC/src/JDBC/WorkWithDatabaseJDBC.java b/lectureDatabaseJDBC/src/JDBC/WorkWithDatabaseJDBC.java new file mode 100644 index 0000000..02c67ac --- /dev/null +++ b/lectureDatabaseJDBC/src/JDBC/WorkWithDatabaseJDBC.java @@ -0,0 +1,154 @@ + +package JDBC; + +/** + * + * @author Алена + */ + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import com.mysql.jdbc.Driver; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +public class WorkWithDatabaseJDBC { + public Connection con; + public Statement stat; + public int size; + public ArrayList loginAndAge, idAndPass; + + public WorkWithDatabaseJDBC(){ + createTableUsers(); + createListForSwing(); + } + + private void createTableUsers() { + toConnect(); + try { + stat.execute("CREATE TABLE users("+ + "id INTEGER PRIMARY KEY,"+ + "login VARCHAR(20),"+ + "age INTEGER);"); + stat.execute("CREATE TABLE pass("+ + "id INTEGER PRIMARY KEY,"+ + "pass VARCHAR(20));"); + con.commit(); + + } catch (SQLException ex) { + try { + con.rollback(); + con.close(); + //System.out.println("SQL exception when table was creating."); + } catch (SQLException ex1) { + System.out.println("Can't roll back"); + } + } + } + + +public void insertInto(String login, int age, String password) { + toConnect(); + try { + size++; + stat.executeUpdate("INSERT INTO users " + + "VALUES ("+size+",'"+login+"',"+age+");"); + stat.executeUpdate("INSERT INTO pass " + + "VALUES (" + size + ", '" + password + "');"); + con.commit(); + con.close(); + + } catch (SQLException ex) { + System.out.println("SQL exception was created when something had been adding."); + } + } + + public void deleteFrom (int id) { + toConnect(); + try { + stat.executeUpdate("DELETE FROM users " + + "WHERE id = " + id + ";"); + stat.executeUpdate("DELETE FROM pass " + + "WHERE id = " + id + ";"); + con.commit(); + con.close(); + } catch (SQLException ex) { + System.out.println("SQL exception was created when something had been deleting"); + } + } + + public boolean checkPass (String login, String pass) { + toConnect(); + int id = 0; + String passFrom=""; + try { + ResultSet result = stat.executeQuery("SELECT * FROM users WHERE login = '" + login + "';"); + while (result.next()) + id = result.getInt("id"); + if (id==0) + return false; + else { + ResultSet result2 = stat.executeQuery("SELECT * FROM pass WHERE id = '"+id+"';"); + while (result2.next()) + passFrom = result2.getString("pass"); + con.close(); + if (passFrom.equals(pass)) + return true; + else + return false; + } + } catch (SQLException ex) { + System.out.println("SQL exception was created when something was cheecking"); + } + return false; + } + + + private void toConnect() { + try { + Class.forName("com.mysql.jdbc.Driver"); + } catch (ClassNotFoundException ex) { + System.out.println("Can't find this class."); + } + try { + con = DriverManager.getConnection("jdbc:mysql://localhost:3306/databaseforjdbc", "root", "1111"); + stat = con.createStatement(); + con.setAutoCommit(false); + } catch (SQLException ex) { + System.out.println("SQL exception was created."); + } + } + + private void createListForSwing() { + toConnect(); + + List arrayList1 = new ArrayList<>(); + List arrayList2 = new ArrayList<>(); + try { + ResultSet result1 = stat.executeQuery("SELECT * FROM users;"); + while (result1.next()) { + String[] value1 = new String[3]; + value1[0] = String.valueOf(result1.getInt("id")); + value1[1] = result1.getString("login"); + value1[2] = String.valueOf(result1.getInt("age")); + size = result1.getInt("id"); + arrayList1.add(value1); + } + loginAndAge = (ArrayList) arrayList1; + ResultSet result2 = stat.executeQuery("SELECT * FROM pass;"); + while (result2.next()) { + String[] value2 = new String[2]; + value2[0] = String.valueOf(result2.getInt("id")); + value2[1] = result2.getString("pass"); + arrayList2.add(value2); + } + idAndPass = (ArrayList) arrayList2; + con.close(); + } catch (SQLException e) { + System.out.println("Can't create it."); + } + } +} \ No newline at end of file diff --git a/manifest.mf b/manifest.mf new file mode 100644 index 0000000..328e8e5 --- /dev/null +++ b/manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/naivebayes/MlModel.java b/naivebayes/MlModel.java new file mode 100644 index 0000000..9d349e3 --- /dev/null +++ b/naivebayes/MlModel.java @@ -0,0 +1,26 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.naivebayes; + +import java.io.IOException; +import ru.caf82.result.exceptions.InconveninentShapeException; + +/** + * + * @author Алена + */ +public interface MlModel { + MlModel train(double[][] X, int[] y) throws InconveninentShapeException; + + int[] predict(double[] X) throws ModelNotFittedException, InconveninentShapeException; + + double[] predictProba(double[] X) throws ModelNotFittedException, InconveninentShapeException; + + + void saveToFile(String filename) throws IOException; + + +} diff --git a/naivebayes/ModelNotFittedException.java b/naivebayes/ModelNotFittedException.java new file mode 100644 index 0000000..50fe8b0 --- /dev/null +++ b/naivebayes/ModelNotFittedException.java @@ -0,0 +1,25 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.naivebayes; + +/** + * + * @author Алена + */ +class ModelNotFittedException extends Exception { + ModelNotFittedException() { + super(); + } + ModelNotFittedException(String message) { + super(message); + } + ModelNotFittedException(Throwable cause) { + super(cause); + } + ModelNotFittedException(Throwable cause, String message) { + super(message); + } +} diff --git a/naivebayes/NaiveBayes.java b/naivebayes/NaiveBayes.java new file mode 100644 index 0000000..7b20c56 --- /dev/null +++ b/naivebayes/NaiveBayes.java @@ -0,0 +1,108 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.naivebayes; + +import java.io.IOException; +import ru.caf82.result.exceptions.InconveninentShapeException; + +/** + * + * @author Алена + */ +public class NaiveBayes implements MlModel { + private float alpha; + private double[][] weights; + private boolean fitted; + private boolean parallel; + public NaiveBayes(float alpha, boolean parallel) { + //Миша сказал забить + } + public MlModel train(double[][] X, int[] y) throws InconveninentShapeException { + //считаем у=0 и y=1 + if (X.length != y.length) + throw new InconveninentShapeException("Неверные входные параметры."); + double yZer = 0, yOne = 0; + for (int i=0; i + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set src.java.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No tests executed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + Must select one file in the IDE or set profile.class + This target only works when run from inside the NetBeans IDE. + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + Must select some files in the IDE or set test.includes + + + + + Must select one file in the IDE or set run.class + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + Must select some files in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + Must select one file in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties new file mode 100644 index 0000000..6f43c7e --- /dev/null +++ b/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=d5755bb5 +build.xml.script.CRC32=687418d1 +build.xml.stylesheet.CRC32=8064a381@1.80.1.48 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=d5755bb5 +nbproject/build-impl.xml.script.CRC32=15ae12f4 +nbproject/build-impl.xml.stylesheet.CRC32=830a3534@1.80.1.48 diff --git a/nbproject/private/config.properties b/nbproject/private/config.properties new file mode 100644 index 0000000..e69de29 diff --git a/nbproject/private/private.properties b/nbproject/private/private.properties new file mode 100644 index 0000000..45af20d --- /dev/null +++ b/nbproject/private/private.properties @@ -0,0 +1,6 @@ +compile.on.save=true +do.depend=false +do.jar=true +javac.debug=true +javadoc.preview=true +user.properties.file=/home/ilysko/.netbeans/8.2/build.properties diff --git a/nbproject/private/private.xml b/nbproject/private/private.xml new file mode 100644 index 0000000..ba3008f --- /dev/null +++ b/nbproject/private/private.xml @@ -0,0 +1,9 @@ + + + + + + file:/home/ilysko/Desktop/WorkLearn/Coding/Java/JavaTeachingInMiphyaga/TextClassifierProject/src/ru/caf82/lectures/lecture02/StringProcessing.java + + + diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 0000000..e581035 --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,77 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=TextClassifierProject +application.vendor=\u0410\u043b\u0435\u043d\u0430 +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# Files in build.classes.dir which should be excluded from distribution jar +dist.archive.excludes= +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/TextClassifierProject.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.external.vm=true +javac.processorpath=\ + ${javac.classpath} +javac.source=1.8 +javac.target=1.8 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +main.class= +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +src.java.dir=result\\src\\main\\java +test.src.dir=test diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 0000000..4b1a601 --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + TextClassifierProject + + + + + + + + + + diff --git a/result/src/main/java/ru/caf82/result/exceptions/EmptyArrayException.java b/result/src/main/java/ru/caf82/result/exceptions/EmptyArrayException.java new file mode 100644 index 0000000..630a940 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/exceptions/EmptyArrayException.java @@ -0,0 +1,29 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.exceptions; + +/** + * + * @author Алена + */ +public class EmptyArrayException extends Exception{ + + public EmptyArrayException() { + super(); + }; + + public EmptyArrayException(String message) { + super(message); + }; + + public EmptyArrayException(String message, Throwable cause) { + super(message, cause); + }; + + public EmptyArrayException(Throwable cause) { + super(cause); + }; +} diff --git a/result/src/main/java/ru/caf82/result/exceptions/InconveninentShapeException.java b/result/src/main/java/ru/caf82/result/exceptions/InconveninentShapeException.java new file mode 100644 index 0000000..efe32f8 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/exceptions/InconveninentShapeException.java @@ -0,0 +1,31 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.exceptions; + +/** + * + * @author Алена + */ +public class InconveninentShapeException extends Exception { + + public InconveninentShapeException() { + super(); + }; + + public InconveninentShapeException(String message) { + super(message); + }; + + public InconveninentShapeException(String message, Throwable cause) { + super(message, cause); + }; + + public InconveninentShapeException(Throwable cause) { + super(cause); + }; + + +} diff --git a/result/src/main/java/ru/caf82/result/exceptions/InconveninentTypesException.java b/result/src/main/java/ru/caf82/result/exceptions/InconveninentTypesException.java new file mode 100644 index 0000000..6a78df5 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/exceptions/InconveninentTypesException.java @@ -0,0 +1,31 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.exceptions; + +/** + * + * @author Алена + */ +public class InconveninentTypesException extends Exception { + + public InconveninentTypesException() { + super(); + }; + + public InconveninentTypesException(String message) { + super(message); + }; + + public InconveninentTypesException(String message, Throwable cause) { + super(message, cause); + }; + + public InconveninentTypesException(Throwable cause) { + super(cause); + }; + + +} diff --git a/result/src/main/java/ru/caf82/result/exceptions/ModelNotFittedException.java b/result/src/main/java/ru/caf82/result/exceptions/ModelNotFittedException.java new file mode 100644 index 0000000..f2efa4c --- /dev/null +++ b/result/src/main/java/ru/caf82/result/exceptions/ModelNotFittedException.java @@ -0,0 +1,27 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.exceptions; + +import ru.caf82.naivebayes.*; + +/** + * + * @author Алена + */ +public class ModelNotFittedException extends Exception { + ModelNotFittedException() { + super(); + } + ModelNotFittedException(String message) { + super(message); + } + ModelNotFittedException(Throwable cause) { + super(cause); + } + ModelNotFittedException(Throwable cause, String message) { + super(message); + } +} diff --git a/result/src/main/java/ru/caf82/result/exceptions/OutOfBondsException.java b/result/src/main/java/ru/caf82/result/exceptions/OutOfBondsException.java new file mode 100644 index 0000000..bbdf2c2 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/exceptions/OutOfBondsException.java @@ -0,0 +1,31 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.exceptions; + +/** + * + * @author Алена + */ +public class OutOfBondsException extends Exception { + + public OutOfBondsException() { + super(); + }; + + public OutOfBondsException(String message) { + super(message); + }; + + public OutOfBondsException(String message, Throwable cause) { + super(message, cause); + }; + + public OutOfBondsException(Throwable cause) { + super(cause); + }; + + +} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/models/AbstractModel.java b/result/src/main/java/ru/caf82/result/machinelearning/models/AbstractModel.java new file mode 100644 index 0000000..ef49b81 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/machinelearning/models/AbstractModel.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.machinelearning.models; + +/** + * + * @author Алена + */ +public class AbstractModel { + +} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/models/Boosting.java b/result/src/main/java/ru/caf82/result/machinelearning/models/Boosting.java new file mode 100644 index 0000000..0533fd3 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/machinelearning/models/Boosting.java @@ -0,0 +1,20 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.machinelearning.models; + +import java.io.IOException; +import ru.caf82.naivebayes.ModelNotFittedException; +import ru.caf82.result.exceptions.InconveninentShapeException; + +/** + * + * @author Алена + */ +public class Boosting { + + + +} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/models/KNeighbourhood.java b/result/src/main/java/ru/caf82/result/machinelearning/models/KNeighbourhood.java new file mode 100644 index 0000000..1c061e9 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/machinelearning/models/KNeighbourhood.java @@ -0,0 +1,38 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.machinelearning.models; + +import java.io.IOException; +import ru.caf82.naivebayes.ModelNotFittedException; +import ru.caf82.result.exceptions.InconveninentShapeException; + +/** + * + * @author Алена + */ +public class KNeighbourhood implements MlModel{ + + @Override + public MlModel train(double[][] X, int[] y) throws InconveninentShapeException { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public int[] predict(double[] X) throws InconveninentShapeException { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public double[] predictProba(double[] X) throws InconveninentShapeException { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void saveToFile(String filename) throws IOException { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + +} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/models/LinearKernel.java b/result/src/main/java/ru/caf82/result/machinelearning/models/LinearKernel.java new file mode 100644 index 0000000..f7f1639 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/machinelearning/models/LinearKernel.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.machinelearning.models; + +/** + * + * @author Алена + */ +public class LinearKernel extends KNeighbourhood { + +} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/models/LogisticRegression.java b/result/src/main/java/ru/caf82/result/machinelearning/models/LogisticRegression.java new file mode 100644 index 0000000..52004b3 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/machinelearning/models/LogisticRegression.java @@ -0,0 +1,163 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package result.machinelearning.preprocessing; + +import Exeptions.EmptyArrayException; +import Exeptions.InconveninentShapeException; +import Exeptions.ModelNotFittedException; +import java.io.Serializable; +import java.util.Random; +import Other.MathService; +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author User + */ +public class LogisticRegression implements MlModel, Serializable { +//private float alpha; +//private float betta; +//private boolean parralize; +//private float learnRate; +//private Random initializer = new Random(); +private int ITERATES=1000; +private double rate=0.001; + +private double[] weights; +//private boolean fitted = false; + + // public LogisticRegression2(float alpha, float betta, int maxIter, float learnRate, boolean parralize) {} + public static double sigmoid(double z){ + return 1/(1+Math.exp(-z)); + } + /** + * Инициализация массива векторв - нужно добавить первый столбец с одними единицами + * @param X - координаты векторов + * @return + */ + static public double[][] init(double[][]X){ + int i,j; + double [][]Y=new double[X.length][X.length+1]; + for(i=0;i0.5){ + System.out.println("It is a dog"); + probability[0]=1; + }else if(ver<0.4)System.out.println("It is a cat"); + else System.out.println("I don't know"); + return probability; + } + + @Override + public double[] predictProba(double[] X) throws ModelNotFittedException, InconveninentShapeException { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void saveToFile(String filename) throws IOException { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + +} +// public double[] predictProba(double[] X) throws ModelNotFittedException, InconveninentShapeException {} +// public void saveToFile(String filename) throws IOException {} +// public double[] getWeights() {} +// public float getAlpha() {} +// public void setAlpha(float alpha) {} +// public float getBetta() {} +// public void setBetta(float betta) {} +// public int getMaxIter() {} +// public void setMaxIter(int maxIter) {} +// public boolean isParralize() {} +// public void setParralize(boolean parralize) {} +// public float getLearnRate() {} +// public void setLearnRate(float learnRate) {} +// private double lossFunction(double[][] X, double[] W, int[] y) throws InconveninentShapeException {} +// private double[] lossFunctionDerivative(double[][] X, double[] W, +// int[] y, float alpha, float betta) throws InconveninentShapeException {} +//} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/models/MlModel.java b/result/src/main/java/ru/caf82/result/machinelearning/models/MlModel.java new file mode 100644 index 0000000..eb6c00a --- /dev/null +++ b/result/src/main/java/ru/caf82/result/machinelearning/models/MlModel.java @@ -0,0 +1,27 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.machinelearning.models; + +import java.io.IOException; +import ru.caf82.result.exceptions.ModelNotFittedException; +import ru.caf82.result.exceptions.InconveninentShapeException; + +/** + * + * @author Алена + */ +public interface MlModel{ + MlModel train(double[][] X, int[] y) throws InconveninentShapeException; + + int[] predict(double[] X) throws ModelNotFittedException, InconveninentShapeException; + + double[] predictProba(double[] X) throws ModelNotFittedException, InconveninentShapeException; + + + void saveToFile(String filename) throws IOException; + + +} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/models/NaiveBayes.java b/result/src/main/java/ru/caf82/result/machinelearning/models/NaiveBayes.java new file mode 100644 index 0000000..3e905fe --- /dev/null +++ b/result/src/main/java/ru/caf82/result/machinelearning/models/NaiveBayes.java @@ -0,0 +1,111 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.machinelearning.models; + +import java.io.IOException; +import ru.caf82.result.exceptions.InconveninentShapeException; + +/** + * + * @author Алена + */ +public class NaiveBayes implements MlModel { + private float alpha; + private double[][] weights; + private boolean fitted; + private boolean parallel; + public NaiveBayes(float alpha, boolean parallel) { + //Миша сказал забить + } + + public MlModel train(double[][] X, int[] y) throws InconveninentShapeException { + //считаем у=0 и y=1 + if (X.length != y.length) + throw new InconveninentShapeException("Неверные входные параметры."); + double yZer = 0, yOne = 0; + for (int i=0; i matrix = new HashMap<>(); +private String[] stopWords; +final float minDf; +final float maxDf; +final boolean parralize; +private static List defaultStopWordsList = new ArrayList( +Arrays.asList(new String[]{ +"а","е","и","ж","м","о","на","не","ни","об","но","он","мне","мои","мож","она","они","оно", +"мной","много","многочисленное","многочисленная","многочисленные","многочисленный", +"мною","мой","мог","могут","можно","может","можно","мор","моя","моё","мочь","над","нее", +"оба","нам","нем","нами","ними","мимо","немного","одной","одного","менее","однажды","однако", +"меня","нему","меньше","ней","наверху","него","ниже","мало","надо","один","одиннадцать","одиннадцатый", +"назад","наиболее","недавно","миллионов","недалеко","между","низко","меля","нельзя","нибудь", +"непрерывно","наконец","никогда","никуда","нас","наш","нет","нею","неё","них","мира","наша", +"наше","наши","ничего","начала","нередко","несколько","обычно","опять","около","мы","ну","нх","от","отовсюду", +"особенно","нужно","очень","отсюда","в","во","вон","вниз","внизу","вокруг","вот","восемнадцать", +"восемнадцатый","восемь","восьмой","вверх","вам","вами","важное","важная","важные","важный","вдали","везде", +"ведь","вас","ваш","ваша","ваше","ваши","впрочем","весь","вдруг","вы","все","второй","всем","всеми","времени","время", +"всему","всего","всегда","всех","всею","всю","вся","всё","всюду","г","год","говорил","говорит","года","году","где", +"да","ее","за","из","ли","же","им","до","по","ими","под","иногда","довольно","именно","долго","позже", +"более","должно","пожалуйста","значит","иметь","больше","пока","ему","имя","пор","пора","потом","потому","после", +"почему","почти","посреди","ей","два","две","двенадцать","двенадцатый","двадцать","двадцатый", +"двух","его","дел","или","без","день","занят","занята","занято","заняты","действительно","давно", +"девятнадцать","девятнадцатый","девять","девятый","даже","алло","жизнь","далеко","близко","здесь","дальше","для", +"лет","зато","даром","первый","перед","затем","зачем","лишь","десять","десятый","ею","её","их","бы","еще","при", +"был","про","процентов","против","просто","бывает","бывь","если","люди","была","были","было","будем","будет","будете","будешь", +"прекрасно","буду","будь","будто","будут","ещё","пятнадцать","пятнадцатый","друго","другое","другой","другие","другая","других","есть","пять", +"быть","лучше","пятый","к","ком","конечно","кому","кого","когда","которой","которого","которая","которые","который","которых","кем", +"каждое","каждая","каждые","каждый","кажется","как","какой","какая","кто","кроме","куда","кругом","с","т","у","я", +"та","те","уж","со","то","том","снова","тому","совсем","того","тогда","тоже","собой","тобой","собою","тобою", +"сначала","только","уметь","тот","тою","хорошо","хотеть","хочешь","хоть","хотя","свое","свои","твой","своей","своего","своих", +"свою","твоя","твоё","раз","уже","сам","там","тем","чем","сама","сами","теми","само","рано","самом","самому", +"самой","самого","семнадцать","семнадцатый","самим","самими","самих","саму", +"семь","чему","раньше","сейчас","чего","сегодня","себе","тебе","сеаой","человек","разве","теперь","себя","тебя","седьмой","спасибо", +"слишком","так","такое","такой","такие","также","такая","сих","тех","чаще","четвертый","через","часто","шестой","шестнадцать","шестнадцатый", +"шесть","четыре","четырнадцать","четырнадцатый","сколько","сказал","сказала","сказать", +"ту","ты","три","эта","эти","что","это","чтоб","этом","этому","этой","этого","чтобы","этот","стал","туда", +"этим","этими","рядом","тринадцать","тринадцатый","этих","третий","тут","эту","суть","чуть","тысяч" +}) +); + +/** +* Заполняет матрицу +* @see CountVectorizer#matrix слова и возвращает список Мапов +* @param listOfTexts Список текстов +* @return Список Мапов +*/ +@Override +public List> fitAndTransform(List listOfTexts) { +List> listOfMaps = new ArrayList<>(); +for (String text : listOfTexts) { +List list = preprocess(text); +listOfMaps.add(countWordsAndEditMatrix(list)); +} +return listOfMaps; +} + +/** +* Заполняет матрицу +* @see CountVectorizer#matrix словами из списка текстов +* @param listOfTexts Список текстов +*/ +@Override +public void fit(List listOfTexts) { +for (String text : listOfTexts) { +List list = preprocess(text); +countWordsAndEditMatrix(list); +} +} + +/** +* Метод извлекающий слова из переданного в метод текста. +* Не учитываются слова поля из +* @see CountVectorizer#defaultStopWordsList +* Используется класс +* @see PorterStemmer для стемминга +* @param text Текст, из которого извлекаются слова +* @return Список слов +*/ +@Override +public List preprocess(String text) { +PorterStemmer stemmer = new PorterStemmer(); +text = text.toLowerCase().replaceAll("[^а-я -]","").replaceAll(" +-"," ").replaceAll("- +"," "); + +String[] array = text.split(" +"); +for (int i = 0; i list = new ArrayList(Arrays.asList(array)); +list.removeAll(defaultStopWordsList); +return list; +} + +/** +* Возвращает список Мапов из слов, взятых из переданного списка текстов +* @param listOfTexts Список текстов +* @return Список Мапов +*/ +@Override +public List> transform(List listOfTexts) { +List> listOfMaps = new ArrayList<>(); +for (String text : listOfTexts) { +List list = preprocess(text); +listOfMaps.add(countWords(list)); +} +return listOfMaps; +} + +/** +* Два конструктора +*/ +public CountVectorizer(float minDf, float maxDf, String[] stopWords, boolean parralize) { +this.minDf = minDf; +this.maxDf = maxDf; +this.stopWords = stopWords; +this.parralize = parralize; +} +public CountVectorizer(float minDf, float maxDf) { +this.minDf = minDf; +this.maxDf = maxDf; +parralize = false; +} +public CountVectorizer(String[] stopWords) { +this.stopWords = stopWords; +minDf = 1; +maxDf = 1; +parralize = false; +} +public CountVectorizer() { +minDf = 1; +maxDf = 1; +parralize = false; +} + +/** +* Геттеры для полей +* @see CountVectorizer#minDf и +* @see CountVectorizer#maxDf +*/ +public float getMinDf() { +return minDf; +} +public float getMaxDf() { +return maxDf; +} + +/** +* Считает, сколько раз встретилось одно слово в переданном списке слов +* @param words Список слов, в котором счиатем слова +* @return Map, в котором ключ - это слово, значение - сколько раз встретилось данное слово +*/ + +private Map countWords(List words) { +Map map = new HashMap(); +int value = 1; +for (String word : words) { +if (map.containsKey(word)) { +value += map.get(word); +} + +map.put(word, value); +} +return map; +} + +/** +* Делаем то же самое, что и в методе +* @see CountVectorizer#countWords(List), но еще и добавляем это в матрицу +* @see CountVectorizer#matrix +* @param words Список слов, в котором счиатем слова +* @return Map, в котором ключ - это слово, значение - сколько раз встретилось данное слово +*/ +private Map countWordsAndEditMatrix(List words) { +Map map = countWords(words); +int valueFromMatrix = 0; +for (Map.Entry pair : map.entrySet()) { +String key = pair.getKey(); +if (matrix.containsKey(key)) { +valueFromMatrix = matrix.get(key); +} +matrix.put(key, valueFromMatrix + pair.getValue()); +} +return map; +} + +} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/PorterStemmer.java b/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/PorterStemmer.java index 02fcf81..f525302 100644 --- a/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/PorterStemmer.java +++ b/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/PorterStemmer.java @@ -1,7 +1,100 @@ -package ru.caf82.result.machinelearning.preprocessing; - -/** - * Created by ilysko on 03.08.17. - */ -public class PorterStemmer implements Transformer, WordProcessor { -} +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package result.machinelearning.preprocessing; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Stolen by ilysko on 03.08.17. + * original: http://www.algorithmist.ru/2010/12/porter-stemmer-russian.html + */ +public class PorterStemmer { + + private static final Pattern PERFECTIVEGROUND = Pattern.compile("((ив|ивши|ившись|ыв|ывши|ывшись)|((?<=[ая])(в|вши|вшись)))$"); + + private static final Pattern REFLEXIVE = Pattern.compile("(с[яь])$"); + + private static final Pattern ADJECTIVE = Pattern.compile("(ее|ие|ые|ое|ими|ыми|ей|ий|ый|ой|ем|им|ым|ом|его|ого|ему|ому|их|ых|ую|юю|ая|яя|ою|ею)$"); + + private static final Pattern PARTICIPLE = Pattern.compile("((ивш|ывш|ующ)|((?<=[ая])(ем|нн|вш|ющ|щ)))$"); + + private static final Pattern VERB = Pattern.compile("((ила|ыла|ена|ейте|уйте|ите|или|ыли|ей|уй|ил|ыл|им|ым|ен|ило|ыло|ено|ят|ует|уют|ит|ыт|ены|ить|ыть|ишь|ую|ю)|((?<=[ая])(ла|на|ете|йте|ли|й|л|ем|н|ло|но|ет|ют|ны|ть|ешь|нно)))$"); + + private static final Pattern NOUN = Pattern.compile("(а|ев|ов|ие|ье|е|иями|ями|ами|еи|ии|и|ией|ей|ой|ий|й|иям|ям|ием|ем|ам|ом|о|у|ах|иях|ях|ы|ь|ию|ью|ю|ия|ья|я)$"); + + private static final Pattern RVRE = Pattern.compile("^(.*?[аеиоуыэюя])(.*)$"); + + private static final Pattern DERIVATIONAL = Pattern.compile(".*[^аеиоуыэюя]+[аеиоуыэюя].*ость?$"); + + private static final Pattern DER = Pattern.compile("ость?$"); + + private static final Pattern SUPERLATIVE = Pattern.compile("(ейше|ейш)$"); + + private static final Pattern I = Pattern.compile("и$"); + private static final Pattern P = Pattern.compile("ь$"); + private static final Pattern NN = Pattern.compile("нн$"); + + public String stem(String word) { + word = word.toLowerCase(); + word = word.replace('ё', 'е'); + Matcher m = RVRE.matcher(word); + if (m.matches()) { + String pre = m.group(1); + String rv = m.group(2); + String temp = PERFECTIVEGROUND.matcher(rv).replaceFirst(""); + if (temp.equals(rv)) { + rv = REFLEXIVE.matcher(rv).replaceFirst(""); + temp = ADJECTIVE.matcher(rv).replaceFirst(""); + if (!temp.equals(rv)) { + rv = temp; + rv = PARTICIPLE.matcher(rv).replaceFirst(""); + } else { + temp = VERB.matcher(rv).replaceFirst(""); + if (temp.equals(rv)) { + rv = NOUN.matcher(rv).replaceFirst(""); + } else { + rv = temp; + } + } + + } else { + rv = temp; + } + + rv = I.matcher(rv).replaceFirst(""); + + if (DERIVATIONAL.matcher(rv).matches()) { + rv = DER.matcher(rv).replaceFirst(""); + } + + temp = P.matcher(rv).replaceFirst(""); + if (temp.equals(rv)) { + rv = SUPERLATIVE.matcher(rv).replaceFirst(""); + rv = NN.matcher(rv).replaceFirst("н"); + } else { + rv = temp; + } + word = pre + rv; + + } + + return word; + } + + /** + * Some tests + */ + public static void main(String[] args) { + PorterStemmer porterStemmer = new PorterStemmer(); + String[] listOfWords = new String[] {"букварь", "здравие", + "птица", "интересный", "космос", "космический"}; + for (String word: listOfWords) { + System.out.println("Результат применения PorterStemmer к слову " + word + " : " +porterStemmer.stem(word)); + } + } + +} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/SequenceProcessor.java b/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/SequenceProcessor.java index 65e46d9..beba12b 100644 --- a/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/SequenceProcessor.java +++ b/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/SequenceProcessor.java @@ -1,7 +1,24 @@ -package ru.caf82.result.machinelearning.preprocessing; - -/** - * Created by ilysko on 03.08.17. - */ -public interface SequenceProcessor { -} +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package result.machinelearning.preprocessing; + +import java.util.List; +import java.util.Map; + +/** + * + * @author User + */ +public interface SequenceProcessor { + public List> fitAndTransform(List listOfTexts); + + public void fit(List listOfTexts); + + public List preprocess(String text); + + public List> transform(List listOfTexts); + +} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/TfidfVectorizer.java b/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/TfidfVectorizer.java index cf212ba..712372b 100644 --- a/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/TfidfVectorizer.java +++ b/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/TfidfVectorizer.java @@ -1,7 +1,27 @@ -package ru.caf82.result.machinelearning.preprocessing; - -/** - * Created by ilysko on 03.08.17. - */ -public class TfidfVectorizer implements SequenceProcessor, Transformer { -} +package ru.caf82.result.machinelearning.preprocessing; + +/** + * Created by ilysko on 03.08.17. + */ +public class TfidfVectorizer implements SequenceProcessor, Transformer { + + @Override + public List> fitAndTransform(List listOfTexts) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void fit(List listOfTexts) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public List preprocess(String text) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public List> transform(List listOfTexts) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } +} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/Transformer.java b/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/Transformer.java index b94b278..b3a93e0 100644 --- a/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/Transformer.java +++ b/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/Transformer.java @@ -1,7 +1,7 @@ -package ru.caf82.result.machinelearning.preprocessing; - -/** - * Created by ilysko on 03.08.17. - */ -public interface Transformer { -} +package ru.caf82.result.machinelearning.preprocessing; + +/** + * Created by ilysko on 03.08.17. + */ +public interface Transformer { +} diff --git a/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/WordProcessor.java b/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/WordProcessor.java index db8ead1..ff63ca2 100644 --- a/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/WordProcessor.java +++ b/result/src/main/java/ru/caf82/result/machinelearning/preprocessing/WordProcessor.java @@ -1,7 +1,7 @@ -package ru.caf82.result.machinelearning.preprocessing; - -/** - * Created by ilysko on 03.08.17. - */ -public interface WordProcessor { -} +package ru.caf82.result.machinelearning.preprocessing; + +/** + * Created by ilysko on 03.08.17. + */ +public interface WordProcessor { +} diff --git a/result/src/main/java/ru/caf82/result/others/Dao.java b/result/src/main/java/ru/caf82/result/others/Dao.java new file mode 100644 index 0000000..0f0fde3 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/others/Dao.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.others; + +/** + * + * @author Алена + */ +public interface Dao { + +} diff --git a/result/src/main/java/ru/caf82/result/others/DaoImplementation.java b/result/src/main/java/ru/caf82/result/others/DaoImplementation.java new file mode 100644 index 0000000..e238b08 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/others/DaoImplementation.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.others; + +/** + * + * @author Алена + */ +public class DaoImplementation { + +} diff --git a/result/src/main/java/ru/caf82/result/others/MathService.java b/result/src/main/java/ru/caf82/result/others/MathService.java new file mode 100644 index 0000000..ff76126 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/others/MathService.java @@ -0,0 +1,191 @@ + +package ru.caf82.result.others; + +import java.util.logging.Level; +import java.util.logging.Logger; +import ru.caf82.result.exceptions.EmptyArrayException; +import ru.caf82.result.exceptions.InconveninentShapeException; + +/** + * + * @author Алена + */ +public class MathService { + + public static double dotProduct(double[] a, double[] b) throws InconveninentShapeException, EmptyArrayException { + double result=0; + if ((a.length ==0 )|| (b.length== 0)) + throw new EmptyArrayException("Ошибка! Вектор нулевой длины!"); + else { + if (a.length != b.length) + throw new InconveninentShapeException("Ошибка! Длина векторов должна быть одинаковой!"); + else { + for (int i=0; i implements Iterable { + + private T[] inner; + private Class innerClass; + private int size; + private int capacity; + + MyOwnArrayList() { + size = 0; + capacity = 10; + } + + MyOwnArrayList(int cap) { + size = 0; + capacity = cap; + } + + MyOwnArrayList(Class inC) { + size = 0; + innerClass = inC; + capacity = 10; + } + public void add (T value) throws InconveninentTypesException { + + if (innerClass==null) + innerClass = value.getClass(); + else + if (value.getClass()!=innerClass) + throw new InconveninentTypesException("Добавленный элемент не соответсвует содержимому MyOwnArrayList"); + size++; + T[] oldInner = (T[])Array.newInstance(innerClass, size-1); + oldInner = inner; + if (size>capacity) + ensureCapacity((capacity*3)/2+1); + inner = (T[])Array.newInstance(innerClass, capacity); + for (int i = 0; i=size)|(position<0)) + throw new OutOfBondsException("Выбранная позиция выходит за предел"); + if (innerClass==null) + innerClass = value.getClass(); + else + if (value.getClass()!=innerClass) + throw new InconveninentTypesException("Добавленный элемент не соответсвует содержимому MyOwnArrayList"); + size++; + T[] oldInner = (T[])Array.newInstance(innerClass, size-1); + oldInner = inner; + if (size>capacity) + ensureCapacity((capacity*3)/2+1); + inner = (T[])Array.newInstance(innerClass, capacity); + for (int i = 0; i0) + return true; + else + return false; + } + + public void set (int position, T value) throws OutOfBondsException { + if ((position>=size)||(position<0)) + throw new OutOfBondsException("Выбранная позиция выходит за предел"); + inner[position] = value; + } + + public void clear () { + inner = null; + size = 0; + innerClass = null; + } + + public void printMyOwnArrayList() { + System.out.print("{"); + for (int i=0; i iter = myOwnArrayList.iterator(); + while (iter.hasNext()) + System.out.println(iter.next()); + } + + @Override + public Iterator iterator() { + return new Iterator() { + int nowPosition; + @Override + public boolean hasNext() { + + return nowPosition implements Iterable{ + + private MyLinkedList first; + private MyLinkedList last; + private int size; + + public MyOwnLinkedList() { + first = last = null; + size = 0; + } + public void add (T value) { + MyLinkedList mll = new MyLinkedList(value); + if (last==null) { + first = mll; + last = mll; + first.next =last; + first.prev = last; + last.prev = first; + last.next = first; + } + else { + MyLinkedList saved = last; + last.next = mll; + last = mll; + last.prev = saved; + first.prev = last; + last.next = first; + } + size++; + } + + public void add (T value, int position) throws OutOfBondsException { + if (position==0) + addFirst(value); + else { + MyLinkedList counter = first; + if ((position<0)|(position>size+1)) + throw new OutOfBondsException("Выбранная позиция выходит за предел"); + if (position==size+1) + addLast(value); + else { + int now = 0; + MyLinkedList added = new MyLinkedList(value); + counter = first; + while (now!=position-1) { + now = now + 1; + counter = counter.next; + } + added.prev = counter; + added.next = counter.next; + counter.next = added; + } + } + size++; + } + public void addFirst (T value) { + MyLinkedList mll = new MyLinkedList(value); + MyLinkedList saved = first; + mll.next = saved; + mll.prev = last; + saved.prev = mll; + last.next = mll; + first = mll; + size++; + } + + public void addLast (T value) { + add(value); + } + + public void printMyOwnLinkedList() { + MyLinkedList mll = first; + int now = 0; + while (now!=size) { + System.out.print(mll.element.toString()+ " "); + mll = mll.next; + now++; + } + System.out.println(); + } + + public boolean contains (T value) { + MyLinkedList mll = first; + int now = 0; + while (now!=size) { + if (mll.element==value) + return true; + mll = mll.next; + now++; + } + return false; + } + + public void remove () { + MyLinkedList mustBeDeleted = first; + first = mustBeDeleted.next; + first.prev = last; + last.next = first; + mustBeDeleted = null; + size--; + } + + public void remove (int position) throws OutOfBondsException { + if (position==0) + removeFirst(); + else { + if ((position<0)||(position>size+1)) + throw new OutOfBondsException("Выбранная позиция выходит за предел"); + if (position==size+1) + removeLast(); + else { + MyLinkedList counter = first; + int now = 0; + while (now!=position-1) { + now = now + 1; + counter = counter.next; + } + MyLinkedList mustBeDeleted = counter.next; + counter.next = mustBeDeleted.next; + mustBeDeleted.next.prev = counter; + mustBeDeleted = null; + size--; + } + } + } + + public void remove (T value) throws OutOfBondsException { + MyLinkedList mll = first; + int position=0; + if (position >size+1 ) + throw new OutOfBondsException("Элемент не найден."); + else { + while ((mll.element!=value)){ + mll = mll.next; + position++; + } + remove(position); + } + } + + public void removeFirst () { + remove(); + } + + public void removeLast() { + MyLinkedList mll = first; + int now = 0; + while (now!=size-1) { + mll = mll.next; + now++; + } + last = mll.prev; + mll.next = null; + last.next = first; + first.prev = last; + size--; + + } + + public void set (T value, int position) throws OutOfBondsException { + if (position==0) + first.element = value; + else { + MyLinkedList counter = first; + + if ((position<0)||(position>=size)) + throw new OutOfBondsException("Выбранная позиция выходит за предел"); + + int now = 0; + + counter = first; + while (now!=position) { + now = now + 1; + counter = counter.next; + } + counter.element = value; + } + } + public T peekFirst() { + return peek(); + } + + public T peekLast() { + if (last.element!=null) + return last.element; + else + return null; + } + + public T peek () { + if (first.element!=null) + return first.element; + else + return null; + } + + public T poll () { + T thisElem = peek(); + removeFirst(); + return thisElem; + } + + public T pollFirst() { + return poll(); + } + + public T pollLast() { + T thisElem = peekLast(); + removeLast(); + return thisElem; + } + public boolean addAll(int index,Collection collection) { + T[] mustBeAdded = (T[]) collection.toArray(); + if ((index>size)|(mustBeAdded.length==0)) + return false; + else { + MyOwnLinkedList moll = toBond(mustBeAdded); + if (index==0) { + MyLinkedList mll = first; + first = moll.first; + moll.last.next = mll; + mll.prev = moll.last; + last.next = first; + first.prev = last; + } + else { + if (index==size) { + last.next = moll.first; + moll.first.prev = last; + last = moll.last; + first.prev = last; + last.next = first; + } + else { + int now = 0; + MyLinkedList mll = first; + while (now!=index-1) { + now++; + mll = mll.next; + } + MyLinkedList saved = mll.next; + mll.next = moll.first; + moll.first.prev = mll; + moll.last.next = saved; + saved.prev = moll.last; + } + } + size = size+mustBeAdded.length; + return true; + } + } + + public boolean addAll (Collection collection) { + T[] mustBeAdded = (T[]) collection.toArray(); + if (mustBeAdded.length==0) + return false; + else + { + MyOwnLinkedList moal = toBond(mustBeAdded); + last.next = moal.first; + moal.first.prev = last; + last = moal.last; + first.prev = last; + last.next = first; + size = size+mustBeAdded.length; + return true; + } + } + + private MyOwnLinkedList toBond (T[] array) { + MyOwnLinkedList moll = new MyOwnLinkedList(); + for (int i = 0; i iterator() { + return new Iterator() { + MyLinkedList nowPosition = first; + + @Override + public boolean hasNext() { + + return nowPosition.next!=first; + } + + @Override + public T next() { + nowPosition = nowPosition.next; + return (T) nowPosition.prev.element; + + } + }; + } + public class MyLinkedList { + MyLinkedList next; + MyLinkedList prev; + T element; + public MyLinkedList(T el) { + element = el; + } + } + + public static void main(String[] args) { + try { + MyOwnLinkedList myOwnLinkedList = new MyOwnLinkedList(); + System.out.println("Добавим элементы: "); + myOwnLinkedList.add("Apple"); + myOwnLinkedList.add("Bear"); + myOwnLinkedList.add("Candy"); + myOwnLinkedList.add("Door"); + myOwnLinkedList.add("Eagle"); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("Есть ли элемент Apple? "); + boolean isC = myOwnLinkedList.contains("Apple"); + System.out.println(isC); + System.out.println("Есть ли элемент Discovery? "); + isC = myOwnLinkedList.contains("Discovery"); + System.out.println(isC); + System.out.println("Добавим элемент Swan на третье место: "); + myOwnLinkedList.add("Swan", 3); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("Добавим элемент Handsome в начало: "); + myOwnLinkedList.addFirst("Handsome"); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("Добавим элемент Flu в конец: "); + myOwnLinkedList.addLast("Flu"); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("Удалим первый элемент: "); + myOwnLinkedList.remove(); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("Добавим элемент Dwarf на четвертую позицию: "); + myOwnLinkedList.add("Dwarf",4); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("Удалим элемент на позиции 2: "); + myOwnLinkedList.remove(2); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("Удалим элемент Bear: "); + myOwnLinkedList.remove("Bear"); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("Удалим последний элемент: "); + myOwnLinkedList.removeLast(); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("Заменим второй элемент на Beauty: "); + myOwnLinkedList.set("Beauty", 2); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("peek/peek first: " + myOwnLinkedList.peek()); + System.out.println("peek last: " + myOwnLinkedList.peekLast()); + System.out.println("poll/poll first: " + myOwnLinkedList.poll()); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("poll last: " + myOwnLinkedList.pollLast()); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("Создадим новую коллекцию: "); + Collection col1 = new ArrayList(); + col1.add("Liver"); + col1.add("Heart"); + col1.add("Boom"); + System.out.println(col1.toString()); + System.out.println("Вставим ее в конец: "); + myOwnLinkedList.addAll(col1); + myOwnLinkedList.printMyOwnLinkedList(); + System.out.println("Создадим новую коллекцию: "); + Collection col = new ArrayList(); + col.add("Miracle"); + col.add("Friend"); + col.add("Factory"); + System.out.println(col.toString()); + System.out.println("Вставим ее на место 1: "); + myOwnLinkedList.addAll(1, col); + myOwnLinkedList.printMyOwnLinkedList(); + Iterator iter = myOwnLinkedList.iterator(); + while (iter.hasNext()) + System.out.println(iter.next()); + } catch (OutOfBondsException ex) { + System.out.println(ex.getMessage()); + } + + } +} \ No newline at end of file diff --git a/result/src/main/java/ru/caf82/result/others/ReviewHibernateEntity.java b/result/src/main/java/ru/caf82/result/others/ReviewHibernateEntity.java new file mode 100644 index 0000000..9a60077 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/others/ReviewHibernateEntity.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.others; + +/** + * + * @author Алена + */ +public class ReviewHibernateEntity { + +} diff --git a/result/src/main/java/ru/caf82/result/others/SwingModel.java b/result/src/main/java/ru/caf82/result/others/SwingModel.java new file mode 100644 index 0000000..947f4e3 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/others/SwingModel.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.others; + +/** + * + * @author Алена + */ +public class SwingModel { + +} diff --git a/result/src/main/java/ru/caf82/result/others/SwingTraining.java b/result/src/main/java/ru/caf82/result/others/SwingTraining.java new file mode 100644 index 0000000..5392aa8 --- /dev/null +++ b/result/src/main/java/ru/caf82/result/others/SwingTraining.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.caf82.result.others; + +/** + * + * @author Алена + */ +public class SwingTraining { + +} diff --git a/result/src/main/java/ru/caf82/result/workwithfiles/FileReader.java b/result/src/main/java/ru/caf82/result/workwithfiles/FileReader.java index 993dc1d..c9cd982 100644 --- a/result/src/main/java/ru/caf82/result/workwithfiles/FileReader.java +++ b/result/src/main/java/ru/caf82/result/workwithfiles/FileReader.java @@ -1,7 +1,51 @@ -package ru.caf82.result.workwithfiles; - -/** - * Created by ilysko on 03.08.17. - */ -public class FileReader implements FileWorker { -} +package ru.caf82.result.workwithfiles; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import ru.caf82.result.machinelearning.models.MlModel; +/** + * Created by ilysko on 03.08.17. + */ +public class FileReader implements FileWorker { + public static String readFrom (String pathToFile) { + String textString = ""; + try(FileInputStream reader = new FileInputStream(pathToFile)) + { + byte[] arByte = new byte[reader.available()]; + reader.read(arByte); + textString = new String(arByte); + } + catch(IOException ex){ + System.out.println(ex.getMessage()); + } finally { + return textString; + } + } + + public static void saveMlModelToFile (MlModel model) throws IOException { + FileOutputStream fos = new FileOutputStream("MlModel.out"); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(model); + oos.flush(); + oos.close(); + + } + public static MlModel loadMlModelToFile () throws IOException, ClassNotFoundException { + FileInputStream fis = new FileInputStream("MlModel.out"); + ObjectInputStream oin = new ObjectInputStream(fis); + MlModel model = (MlModel)oin.readObject(); + return model; + } + + + public static void main(String[] args) { + /* String directory = "C:\\SomeDir\\notes3.txt"; + String textFromFile = readFrom(directory); + System.out.println(textFromFile); + */ + } +} diff --git a/result/src/main/java/ru/caf82/result/workwithfiles/FileWorker.java b/result/src/main/java/ru/caf82/result/workwithfiles/FileWorker.java index 9fe4f42..434ca7b 100644 --- a/result/src/main/java/ru/caf82/result/workwithfiles/FileWorker.java +++ b/result/src/main/java/ru/caf82/result/workwithfiles/FileWorker.java @@ -1,7 +1,7 @@ -package ru.caf82.result.workwithfiles; - -/** - * Created by ilysko on 03.08.17. - */ -public interface FileWorker { -} +package ru.caf82.result.workwithfiles; + +/** + * Created by ilysko on 03.08.17. + */ +public interface FileWorker { +} diff --git a/result/src/main/java/ru/caf82/result/workwithfiles/FileWriter.java b/result/src/main/java/ru/caf82/result/workwithfiles/FileWriter.java index 3de089c..ea5b694 100644 --- a/result/src/main/java/ru/caf82/result/workwithfiles/FileWriter.java +++ b/result/src/main/java/ru/caf82/result/workwithfiles/FileWriter.java @@ -1,7 +1,7 @@ -package ru.caf82.result.workwithfiles; - -/** - * Created by ilysko on 03.08.17. - */ -public class FileWriter implements FileWorker { -} +package ru.caf82.result.workwithfiles; + +/** + * Created by ilysko on 03.08.17. + */ +public class FileWriter implements FileWorker { +} diff --git a/src/ru/caf82/lectures/diagramBomberman/GameObject.java b/src/ru/caf82/lectures/diagramBomberman/GameObject.java new file mode 100644 index 0000000..7006157 --- /dev/null +++ b/src/ru/caf82/lectures/diagramBomberman/GameObject.java @@ -0,0 +1,9 @@ +package ru.caf82.lectures.diagramBomberman; + +/** + * Created by ilysko on 18.09.17. + */ +public interface GameObject { + void start(); + void finish(); +} diff --git a/src/ru/caf82/lectures/diagramBomberman/GameSession.java b/src/ru/caf82/lectures/diagramBomberman/GameSession.java new file mode 100644 index 0000000..4877b8f --- /dev/null +++ b/src/ru/caf82/lectures/diagramBomberman/GameSession.java @@ -0,0 +1,11 @@ +package ru.caf82.lectures.diagramBomberman; + +/** + * Created by ilysko on 18.09.17. + */ +public class GameSession implements Tickable { + @Override + public void tick() { + System.out.println("tick!"); + } +} diff --git a/src/ru/caf82/lectures/diagramBomberman/Movable.java b/src/ru/caf82/lectures/diagramBomberman/Movable.java new file mode 100644 index 0000000..6629aa9 --- /dev/null +++ b/src/ru/caf82/lectures/diagramBomberman/Movable.java @@ -0,0 +1,8 @@ +package ru.caf82.lectures.diagramBomberman; + +/** + * Created by ilysko on 18.09.17. + */ +public interface Movable extends Positioanable, Tickable{ + void move(); +} diff --git a/src/ru/caf82/lectures/diagramBomberman/Positioanable.java b/src/ru/caf82/lectures/diagramBomberman/Positioanable.java new file mode 100644 index 0000000..5b2a20e --- /dev/null +++ b/src/ru/caf82/lectures/diagramBomberman/Positioanable.java @@ -0,0 +1,9 @@ +package ru.caf82.lectures.diagramBomberman; + +/** + * Created by ilysko on 18.09.17. + */ +public interface Positioanable extends GameObject { + int getXPosition(); + int getYPosition(); +} diff --git a/src/ru/caf82/lectures/diagramBomberman/Temporary.java b/src/ru/caf82/lectures/diagramBomberman/Temporary.java new file mode 100644 index 0000000..e32ee17 --- /dev/null +++ b/src/ru/caf82/lectures/diagramBomberman/Temporary.java @@ -0,0 +1,9 @@ +package ru.caf82.lectures.diagramBomberman; + +/** + * Created by ilysko on 18.09.17. + */ +public interface Temporary extends GameObject { + int getBornTime(); + int getFinishTime(); +} diff --git a/src/ru/caf82/lectures/diagramBomberman/Tickable.java b/src/ru/caf82/lectures/diagramBomberman/Tickable.java new file mode 100644 index 0000000..8d51018 --- /dev/null +++ b/src/ru/caf82/lectures/diagramBomberman/Tickable.java @@ -0,0 +1,8 @@ +package ru.caf82.lectures.diagramBomberman; + +/** + * Created by ilysko on 18.09.17. + */ +public interface Tickable { + void tick(); +} diff --git a/src/ru/caf82/lectures/lecture02/BoxingExample.java b/src/ru/caf82/lectures/lecture02/BoxingExample.java new file mode 100644 index 0000000..1f64c70 --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/BoxingExample.java @@ -0,0 +1,26 @@ +package ru.caf82.lectures.lecture02; + +public class BoxingExample { + + public static void main(String[] args) { + Integer i = Integer.valueOf(50); + Integer iTwo = Integer.valueOf(50); + Integer iThree = 50; + + System.out.println(i == iThree); + System.out.println(i == iTwo); + System.out.println(i.equals(iThree)); + System.out.println(i.equals(iTwo)); + + System.out.println("----------------------------------------"); + + Integer iNew = Integer.valueOf(1000); + Integer iNewTwo = Integer.valueOf(1000); + Integer iNewThree = 1000; + + System.out.println(iNew == iNewThree); + System.out.println(iNew == iNewTwo); + System.out.println(iNew.equals(iNewThree)); + System.out.println(iNew.equals(iNewTwo)); + } +} diff --git a/src/ru/caf82/lectures/lecture02/BreakAndContinueExample.java b/src/ru/caf82/lectures/lecture02/BreakAndContinueExample.java new file mode 100644 index 0000000..ad6005e --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/BreakAndContinueExample.java @@ -0,0 +1,44 @@ +package ru.caf82.lectures.lecture02; + +/** + * Created by ilysko on 24.08.17. + */ +public class BreakAndContinueExample { + public static void main(String[] args) { + // Break example + for (int i = 0; i < 100; i++) { + if (i == 4) { + break; + } + System.out.print(i + " "); + } + + System.out.println(); + + // Continue example + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + continue; + } + System.out.print(i + " "); + } + + System.out.println("\n"); + + // Continue and Break with "tags" + outer: + for (int i = 0; i < 10; i++) { + inner: + for (int j = 0; j < 10; j++) { + if (j > i) { + System.out.println(); + continue outer; + } + if (i == 8) { + break outer; + } + System.out.print(" " + (i * j)); + } + } + } +} diff --git a/src/ru/caf82/lectures/lecture02/CalculatorExample.java b/src/ru/caf82/lectures/lecture02/CalculatorExample.java new file mode 100644 index 0000000..edfa955 --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/CalculatorExample.java @@ -0,0 +1,35 @@ +package ru.caf82.lectures.lecture02; + +public class CalculatorExample { + private int x; + private int y; + + CalculatorExample(int x, int y) { + this.x = x; + this.y = y; + } + + public void setX(int x) { + this.x = x; + } + + public void setY(int y) { + this.y = y; + } + + public int getSubst() { + return x-y; + } + + public float getSum() { + return (float) x + y; + } + + public static void main(String[] args) { + CalculatorExample calc = new CalculatorExample(5, 2); + System.out.println(calc.getSum()); + System.out.println(calc.getSubst()); + + //todo create new calculator, add abs function from Math + } +} diff --git a/src/ru/caf82/lectures/lecture02/CommentsExample.java b/src/ru/caf82/lectures/lecture02/CommentsExample.java new file mode 100644 index 0000000..7923149 --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/CommentsExample.java @@ -0,0 +1,18 @@ +package ru.caf82.lectures.lecture02; + +/** + * @author ilysko + * @version 1.0 + * Class for comment representation + */ +public class CommentsExample { + public static void main(String[] args) { + System.out.println("Let's look to comments in Java"); + /* + * Realy big + * comment + */ + + //System.out.println("Cool!"); + } +} diff --git a/src/ru/caf82/lectures/lecture02/ConstructorExample.java b/src/ru/caf82/lectures/lecture02/ConstructorExample.java new file mode 100644 index 0000000..81727c9 --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/ConstructorExample.java @@ -0,0 +1,15 @@ +package ru.caf82.lectures.lecture02; + +public class ConstructorExample { + + public class Rectangular { + + //todo create fields weight and length, create constructor, create method Square + + } + + + public static void main(String[] args) { + //todo write some test + } +} diff --git a/src/ru/caf82/lectures/lecture02/ForAndForEachExample.java b/src/ru/caf82/lectures/lecture02/ForAndForEachExample.java new file mode 100644 index 0000000..31e25d5 --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/ForAndForEachExample.java @@ -0,0 +1,17 @@ +package ru.caf82.lectures.lecture02; + +/** + * Created by ilysko on 24.08.17. + */ +public class ForAndForEachExample { + public static void main(String[] args) { + for (int i = 1; i < 5; i++) { + System.out.println("i = " + i); + } + System.out.println(); + int[] intList = {1,2,3,4}; + for (int i : intList) { + System.out.println("i = " + i); + } + } +} diff --git a/src/ru/caf82/lectures/lecture02/IfElseAndSwitchCaseExample.java b/src/ru/caf82/lectures/lecture02/IfElseAndSwitchCaseExample.java new file mode 100644 index 0000000..22f0f4a --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/IfElseAndSwitchCaseExample.java @@ -0,0 +1,32 @@ +package ru.caf82.lectures.lecture02; + +/** + * Created by ilysko on 24.08.17. + */ +public class IfElseAndSwitchCaseExample { + public static void main(String[] args) { + int myMark = 5; + + if (myMark == 5) { + System.out.println("Excellent"); + } else if (myMark <= 4 && myMark >=3) { + System.out.println("Not bad"); + } else { + System.out.println("Bad"); + } + + switch (myMark) { + case 5: + System.out.println("Excellent"); + break; + case 4: + System.out.println("Good"); + break; + case 2: + System.out.println("Bad"); + default: + System.out.println("Not bad"); + break; + } + } +} diff --git a/src/ru/caf82/lectures/lecture02/LinkTypes.java b/src/ru/caf82/lectures/lecture02/LinkTypes.java new file mode 100644 index 0000000..d3c581c --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/LinkTypes.java @@ -0,0 +1,32 @@ +package ru.caf82.lectures.lecture02; + +public class LinkTypes { + + public static void main(String[] args) { + String a = "Hello", b = "World"; + + System.out.println(a + " " + b); + + String c = 2 + 2 + ""; + String d = "" + 2 + 2; + String g = "" + (2 + 2); + + System.out.println(c); + System.out.println(d); + System.out.println(g); + + String foo = "a string"; + String bar = "a string"; + String baz = new String("a string"); + + System.out.println("foo == bar ? " + (foo == bar)); + System.out.println("foo равен bar ? " + (foo.equals(bar))); + System.out.println("foo == baz ? " + (foo == baz)); + System.out.println("foo равен baz ? " + (foo.equals(baz))); + + + + } + + +} diff --git a/src/ru/caf82/lectures/lecture02/OperatorsExample.java b/src/ru/caf82/lectures/lecture02/OperatorsExample.java new file mode 100644 index 0000000..6bcc959 --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/OperatorsExample.java @@ -0,0 +1,58 @@ +package ru.caf82.lectures.lecture02; + +import com.sun.org.apache.xpath.internal.SourceTree; + +/** + * Created by ilysko on 24.08.17. + */ +public class OperatorsExample { + public static void main(String[] args) { + System.out.println("Arithmetical operators:"); + int a = 10, b = 3, c = 2; + float g = 5.14f, f = 2.05f; + System.out.println("a + c - b = " + (a + c - b)); + System.out.println("b * c = " + b * c); + System.out.println("a / b = " + a / b); // pay attention for this (integer division) + System.out.println("g / f = " + g / f); + + System.out.println("\nUnary operators:"); + int d = 4; + boolean e = true; + System.out.println("d++ = " + d++); + System.out.println("d = " + d); + System.out.println("++d = " + ++d); + System.out.println("(byte) d = " + Integer.toBinaryString(d)); + System.out.println("(byte) ~d = " + Integer.toBinaryString(~d)); + System.out.println("!e = " + !e); + + System.out.println("\nRelational operators:"); + double p = 5.5d, r = 2.7500000000000001d; + System.out.println("p / 2 == r = " + (p / 2 == r)); + + System.out.println("\nBitwise operators:"); + // TODO разобраться с битовыми представлениями! + byte t = 0b1110, q = 0b0111; + byte y = -13; + System.out.println("t & q = " + Integer.toBinaryString(t & q)); + System.out.println("t | q = " + Integer.toBinaryString(t | q)); + System.out.println("t ^ q = " + Integer.toBinaryString(t ^ q)); + System.out.println("y = " + String.format("%8s", Integer.toBinaryString(y & 0xFF)).replace(' ', '0')); + System.out.println("-y = " + String.format("%8s", Integer.toBinaryString(-y & 0xFF)).replace(' ', '0')); + System.out.println("y << 2 = " + (y << 2)); + System.out.println("y >> 2 = " + (y >> 2)); + System.out.println("y >>> 2 = " + (y >>> 2)); + System.out.println("y << 2 = " + Integer.toBinaryString(y << 2)); + System.out.println("y >> 2 = " + Integer.toBinaryString(y >> 2)); + System.out.println("y >>> 2 = " + Integer.toBinaryString(y >>> 2)); + + System.out.println("\nLogical operators:"); + boolean b1 = false, b2 = true; + System.out.println("b1 || b2 = " + (b1 || b2)); + System.out.println("b1 && b2 = " + (b1 && b2)); + + System.out.println("\nTernary operators:"); + boolean b3 = true; + System.out.println("Rolling " + (b3 ? "Stones" : "Trees")); + System.out.println("Paint It " + (!b3 ? "Red" : "Black")); + } +} diff --git a/src/ru/caf82/lectures/lecture02/PrimitiveTypes.java b/src/ru/caf82/lectures/lecture02/PrimitiveTypes.java new file mode 100644 index 0000000..a5dcc37 --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/PrimitiveTypes.java @@ -0,0 +1,43 @@ +package ru.caf82.lectures.lecture02; + +public class PrimitiveTypes { + + + public static void main(String[] args) { + + //byte b = 216; + short s = 1123; + int i = 64536; + long l = 2147483648L; + int j = 10; + + System.out.println(i); + //System.out.println(b); + System.out.println(s); + System.out.println(l); + + System.out.println(i + 2147483647); + System.out.println(l + j); + System.out.println(j + l); + + char a = 'a', c = 'c'; + int b; + b = ((a + c) / 2); + System.out.println(b); + System.out.println((char) b); + + System.out.println((char) b + i); + System.out.println(b+i); + + double doubleOne, doubleTwo = 4.12; + doubleOne = 22.1 + doubleTwo; + float pi = 3.14f; + //float anotherPi = 3.14; + double doubleThree = 27; + double d = pi * doubleThree; + + System.out.println(d); + System.out.println(doubleOne); + System.out.println(pi); + } +} diff --git a/src/ru/caf82/lectures/lecture02/StringProcessing.java b/src/ru/caf82/lectures/lecture02/StringProcessing.java new file mode 100644 index 0000000..b51d9b5 --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/StringProcessing.java @@ -0,0 +1,39 @@ +package ru.caf82.lectures.lecture02; + +public class StringProcessing { + + public static void main(String[] args) { + + //String Buffer examples + StringBuffer sb = new StringBuffer("Котэ"); + + System.out.println("Длина: " + sb.length()); + System.out.println("Объем: " + sb.capacity()); + + sb.setCharAt(1, 'o'); + + System.out.println("Было Котэ, стало: " + sb.toString()); + + String str1 = "У кота "; + String str2 = " лапы"; + int paws = 4; + StringBuffer sbNew = new StringBuffer(20); + sbNew.append(str1).append(paws).append(str2); + + System.out.println(sbNew.toString()); + + sb.insert(0, "Люблю "); + System.out.println(sb.toString()); + + sb.reverse(); + System.out.println(sb.toString()); + + //TODO delete, deleteCharAt, replace, substring write your own code + + + + //TODO StringBuilder the same methods implementation + + } + +} diff --git a/src/ru/caf82/lectures/lecture02/WhileAndDoWhileExample.java b/src/ru/caf82/lectures/lecture02/WhileAndDoWhileExample.java new file mode 100644 index 0000000..d3fbb84 --- /dev/null +++ b/src/ru/caf82/lectures/lecture02/WhileAndDoWhileExample.java @@ -0,0 +1,20 @@ +package ru.caf82.lectures.lecture02; + +/** + * Created by ilysko on 24.08.17. + */ +public class WhileAndDoWhileExample { + public static void main(String[] args) { + int i = 3; + + while (i > 0) { + System.out.println(i--); + } + + System.out.println("\n" + i + "\n"); + + do { + System.out.println(i--); + } while (i > 0); + } +} diff --git a/src/ru/caf82/lectures/lecture03/AbstractAnimal.java b/src/ru/caf82/lectures/lecture03/AbstractAnimal.java new file mode 100644 index 0000000..3034cf2 --- /dev/null +++ b/src/ru/caf82/lectures/lecture03/AbstractAnimal.java @@ -0,0 +1,20 @@ +package ru.caf82.lectures.lecture03; + +/** + * Created by ilysko on 16.09.17. + */ +public abstract class AbstractAnimal { + final int legsAmount; + final String animalName; + + public abstract void move(); + + public void sayYourName() { + System.out.println("My name is " + animalName); + } + + protected AbstractAnimal(int legsAmount, String animalName) { + this.legsAmount = legsAmount; + this.animalName = animalName; + } +} diff --git a/src/ru/caf82/lectures/lecture03/CompositionExample.java b/src/ru/caf82/lectures/lecture03/CompositionExample.java new file mode 100644 index 0000000..8ee40d5 --- /dev/null +++ b/src/ru/caf82/lectures/lecture03/CompositionExample.java @@ -0,0 +1,83 @@ +package ru.caf82.lectures.lecture03; + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.function.DoublePredicate; + +/** + * Created by ilysko on 17.09.17. + */ +public class CompositionExample { + Cat cat = new Cat(); // в точке определения + Dog dog; + Crocodile crocodile; + Zoo zoo = new Zoo(new Animal[] {cat, dog, crocodile}); // с использованием инициализации экземпляров + + CompositionExample(Dog dog) { + this.dog = dog; // в конструкторе + } + + @Override + public String toString() { + if (crocodile == null) { + this.crocodile = new Crocodile(); // перед использованием объекта + } + return "CompositionExample{" + + "cat=" + cat + + ", dog=" + dog + + ", crocodile=" + crocodile + + ", zoo=" + zoo + + '}'; + } + + public static void main(String[] args) { + Dog dog = new Dog(true); + CompositionExample compositionExample = new CompositionExample(dog); + + System.out.println(compositionExample.toString()); + + compositionExample.crocodile.eatMeat(); + compositionExample.cat.sayMeow(); + System.out.println(compositionExample.dog.isFriendly); + System.out.println(Arrays.toString(compositionExample.zoo.animals)); + } +} + +abstract class Animal {} + +class Cat extends Animal { + int legCount = 4; + void sayMeow() { + System.out.println("Meow"); + } +} + +class Dog extends Animal { + boolean isFriendly; + + Dog(boolean isFriendly) { + this.isFriendly = isFriendly; + } +} + +class Crocodile extends Animal { + void eatMeat() { + System.out.println("Delicious!"); + } +} + +class Zoo { + Animal[] animals; + + Zoo(Animal[] animals) { + this.animals = animals; + } + + void open() { + System.out.println("open"); + } + + void close() { + System.out.println("close"); + } +} diff --git a/src/ru/caf82/lectures/lecture03/InheritanceExample.java b/src/ru/caf82/lectures/lecture03/InheritanceExample.java new file mode 100644 index 0000000..c6b207a --- /dev/null +++ b/src/ru/caf82/lectures/lecture03/InheritanceExample.java @@ -0,0 +1,39 @@ +package ru.caf82.lectures.lecture03; + +/** + * Created by ilysko on 17.09.17. + */ +public class InheritanceExample { + void tryToGetAnimalName(AbstractAnimal abstractAnimal) { + // нисходящее преобразование + abstractAnimal.sayYourName(); + + // нельзя, т.к. мы работаем с AbstractAnimal + //abstractAnimal.jump() + } + + public static void main(String[] args) { + AbstractAnimal tiger = new Tiger(); + tiger.move(); + tiger.sayYourName(); + System.out.println(tiger.legsAmount); + } +} + +class Tiger extends AbstractAnimal { + + protected Tiger() { + super(4, "Tiger"); + } + + @Override + public void move() { + System.out.println("run"); + } + + public void jump() { + System.out.println("jump"); + } +} + + diff --git a/src/ru/caf82/lectures/lecture03/InterfaceExample.java b/src/ru/caf82/lectures/lecture03/InterfaceExample.java new file mode 100644 index 0000000..4517fbe --- /dev/null +++ b/src/ru/caf82/lectures/lecture03/InterfaceExample.java @@ -0,0 +1,17 @@ +package ru.caf82.lectures.lecture03; + +/** + * Created by ilysko on 17.09.17. + */ +public interface InterfaceExample { + default void printSomething() { + System.out.println("Something"); + } + + String returnName(); + + // можно не писать static final, это "по умолчанию" + static final int amount1 = 3; + int amount2 = 4; + +} diff --git a/src/ru/caf82/lectures/lecture03/PassByValue.java b/src/ru/caf82/lectures/lecture03/PassByValue.java new file mode 100644 index 0000000..1e07dae --- /dev/null +++ b/src/ru/caf82/lectures/lecture03/PassByValue.java @@ -0,0 +1,51 @@ +package ru.caf82.lectures.lecture03; + +import java.util.Arrays; + +/** + * Created by ilysko on 17.09.17. + */ +public class PassByValue { + static void changePrimitiveInt(int a) { + a++; + } + + static void changeReferenceInteger(Integer a) { + a++; + } + + static void replaceReferenceInteger(Integer a) { + a = new Integer(42); + } + + static void changeStringArray(String[] listOfBands) { + listOfBands[2] = "Guns N' Roses"; + } + + static void doSomethingBad(String[] listOfBands) { + listOfBands = new String[]{"Justin Bieber", "Тимати"}; + } + + public static void main(String[] args) { + int a1 = 2; + + changePrimitiveInt(a1); + System.out.println("int primitive after changePrimitiveInt() : " + a1); + + Integer a2 = new Integer(2); + + changeReferenceInteger(a2); + System.out.println("Integer object after changeReferenceInteger() : " + a2); + + replaceReferenceInteger(a2); + System.out.println("Integer object after replaceReferenceInteger() : " + a2); + + String[] listOfBands = {"Led Zeppelin", "Pink Floyd", ""}; + + changeStringArray(listOfBands); + System.out.println("String[] after changeStringArray() : " + Arrays.toString(listOfBands)); + + doSomethingBad(listOfBands); + System.out.println("String[] after something bad : " + Arrays.toString(listOfBands)); + } +} diff --git a/src/ru/caf82/lectures/lecture03/PolymorphysmExample.java b/src/ru/caf82/lectures/lecture03/PolymorphysmExample.java new file mode 100644 index 0000000..0661fb8 --- /dev/null +++ b/src/ru/caf82/lectures/lecture03/PolymorphysmExample.java @@ -0,0 +1,34 @@ +package ru.caf82.lectures.lecture03; + +/** + * Created by ilysko on 17.09.17. + */ +public class PolymorphysmExample { + static void wash(Washable washable) { + System.out.println("cleaning " + washable.toString()); + } + + public static void main(String[] args) { + Kitty kitty = new Kitty(); + Dishware dishware = new Dishware(); + + wash(kitty); + wash(dishware); + } +} + +interface Washable{} + +class Kitty implements Washable { + @Override + public String toString() { + return "Kitty"; + } +} + +class Dishware implements Washable { + @Override + public String toString() { + return "Dishware"; + } +} \ No newline at end of file diff --git a/src/ru/caf82/lectures/lecture03/Season.java b/src/ru/caf82/lectures/lecture03/Season.java new file mode 100644 index 0000000..bd6c131 --- /dev/null +++ b/src/ru/caf82/lectures/lecture03/Season.java @@ -0,0 +1,52 @@ +package ru.caf82.lectures.lecture03; + +import java.io.Serializable; +import java.util.Arrays; + +/** + * Created by ilysko on 16.09.17. + */ +public enum Season { + WINTER ("Зима"), + SPRING ("Весна"), + SUMMER ("Лето"), + AUTUMN ("Осень"); + + private String russianName; + Season(String russianName) { + this.russianName = russianName; + } + + public String getRussianName() { + return russianName; + } + + public static void printMonthsOfSeason(Season season) { + switch (season) { + case WINTER: + System.out.println("December, January and February"); + break; + case AUTUMN: + System.out.println("September, October and November"); + break; + case SUMMER: + System.out.println("June, July and August"); + break; + case SPRING: + System.out.println("April, March and May"); + break; + } + } + + public static void main(String[] args) { + Season season = Season.AUTUMN; + System.out.println(season); + + // get all enum values + System.out.println(Arrays.toString(Season.values())); + + printMonthsOfSeason(season); + + System.out.println(season.getRussianName()); + } +} diff --git a/src/ru/caf82/lectures/lecture04/ExceptionCatchingExample.java b/src/ru/caf82/lectures/lecture04/ExceptionCatchingExample.java new file mode 100644 index 0000000..8456e7c --- /dev/null +++ b/src/ru/caf82/lectures/lecture04/ExceptionCatchingExample.java @@ -0,0 +1,21 @@ +package ru.caf82.lectures.lecture04; + + +public class ExceptionCatchingExample { + + public static void main(String[] args) { + try { + System.out.println(6 / 0); + } catch (ArithmeticException ex) { + System.out.println("Ошибка! Ошибка!"); + System.out.println(ex.toString()); + } + + try { + System.out.println(Long.parseLong("Mama")); + } catch (NumberFormatException ex) { + System.out.println("Снова косяк!"); + System.out.println(ex.toString()); + } + } +} diff --git a/src/ru/caf82/lectures/lecture04/ExceptionCatchingIhExample.java b/src/ru/caf82/lectures/lecture04/ExceptionCatchingIhExample.java new file mode 100644 index 0000000..c4dfc32 --- /dev/null +++ b/src/ru/caf82/lectures/lecture04/ExceptionCatchingIhExample.java @@ -0,0 +1,24 @@ +package ru.caf82.lectures.lecture04; + +public class ExceptionCatchingIhExample { + + public static void main(String[] args) { +// try { +// System.out.println(6 / 0); +// } catch (Exception ex) { +// System.out.println("Ошибка верхнего увроня"); +// } catch (ArithmeticException ex) { +// System.out.println("Ошибка! Ошибка!"); +// System.out.println(ex.toString()); +// } + + try { + System.out.println(Long.parseLong("Mama")); + } catch (NumberFormatException ex) { + System.out.println("Снова косяк!"); + System.out.println(ex.toString()); + } catch (Exception ex) { + System.out.println("Ошибка верхнего уровня"); + } + } +} diff --git a/src/ru/caf82/lectures/lecture04/MyExceptionClassExample.java b/src/ru/caf82/lectures/lecture04/MyExceptionClassExample.java new file mode 100644 index 0000000..b741e17 --- /dev/null +++ b/src/ru/caf82/lectures/lecture04/MyExceptionClassExample.java @@ -0,0 +1,52 @@ +package ru.caf82.lectures.lecture04; + +/** + * Created by ilysko on 24.09.17. + */ +public class MyExceptionClassExample extends TemplateForMyExceptionClass { + int amountOfSmth; + + void someMethod() { + System.out.println(amountOfSmth); + } + + void f() { + someMethod(); + } + + public MyExceptionClassExample() { + super(); + } + + public MyExceptionClassExample(Exception e) { + super(e); + } + + public MyExceptionClassExample(int amountOfSmth) { + super(); + this.amountOfSmth = amountOfSmth; + } + + public MyExceptionClassExample(String messageFullOfAnger) { + super(messageFullOfAnger); + } + + public static void main(String[] args) { + System.out.println("let's throw an exception!"); +// throw new MyExceptionClassExample("lol"); + } +} + +class TemplateForMyExceptionClass extends Exception { + TemplateForMyExceptionClass() { + super(); + } + + TemplateForMyExceptionClass(String message) { + super(message); + } + + TemplateForMyExceptionClass(Exception e) { + super(e); + } +} diff --git a/src/ru/caf82/lectures/lecture04/StackTraceExample.java b/src/ru/caf82/lectures/lecture04/StackTraceExample.java new file mode 100644 index 0000000..96b7f71 --- /dev/null +++ b/src/ru/caf82/lectures/lecture04/StackTraceExample.java @@ -0,0 +1,32 @@ +package ru.caf82.lectures.lecture04; + +/** + * Created by ilysko on 24.09.17. + */ +public class StackTraceExample { + static void f() { + try { + throw new Exception(); + } catch (Exception e) { + for (StackTraceElement ste : e.getStackTrace()) { + System.out.println(ste.getMethodName()); + } + } + } + + static void g() { + f(); + } + + static void h() { + g(); + } + + public static void main(String[] args) { + f(); + System.out.println("---------------"); + g(); + System.out.println("---------------"); + h(); + } +} diff --git a/src/ru/caf82/lectures/lecture04/ThrowExample.java b/src/ru/caf82/lectures/lecture04/ThrowExample.java new file mode 100644 index 0000000..8c3a31a --- /dev/null +++ b/src/ru/caf82/lectures/lecture04/ThrowExample.java @@ -0,0 +1,51 @@ +package ru.caf82.lectures.lecture04; + +public class ThrowExample { + + public static int divide(int a, int b) throws ArithmeticException, NegException { + if (b == 0) { + throw new ArithmeticException("Ты че как лох-то, на нуль делить нельзя"); + } else if( b < 0) { + throw new NegException("Мы решили, что на отрицательные числа делить нельзя"); + } + return a / b; + } + + public static void main(String[] args) { + try { + System.out.println(divide(5, 2)); + System.out.println(divide(5, 0)); + } catch (ArithmeticException ex){ + System.out.println("Мы поймали ошибку!"); + } catch (Exception ex) { + // + } + try { + System.out.println(divide(5, 2)); + System.out.println(divide(5, -1)); + } catch (NegException ex){ + System.out.println("Мы поймали ошибку!"); + } catch (Exception ex) { + // + } + try { + System.out.println(divide(5, -1)); + System.out.println(divide(5, 0)); + } catch (ArithmeticException ex){ + System.out.println("Мы поймали ошибку!"); + } catch (NegException ex) { + System.out.println("Отрицательное деление"); + } + + } + + + public static class NegException extends Exception { + NegException(){ + super(); + } + NegException(String message) { + super(message); + } + } +} diff --git a/src/ru/caf82/lectures/lecture04/WorkWithExceptions.java b/src/ru/caf82/lectures/lecture04/WorkWithExceptions.java new file mode 100644 index 0000000..0791ab8 --- /dev/null +++ b/src/ru/caf82/lectures/lecture04/WorkWithExceptions.java @@ -0,0 +1,36 @@ +package ru.caf82.lectures.lecture04; + +/** + * Created by ilysko on 24.09.17. + */ +public class WorkWithExceptions { + void ignore() throws Exception { + throw new Exception(); + } + + void catchHere() { + try { + throw new Exception(); + } catch (Exception e) { + System.out.println("Lol, i caught it just here!"); + } + } + + void throwAhead() { + try { + ignore(); + } catch (Exception e) { + System.out.println("We didn't try to catch exception in ignore(). " + + "We did it here"); + } + } + + void createNewExceptionWhileWorkingWithOld() throws MyExceptionClassExample { + try { + ignore(); + } catch (Exception e) { + System.out.println("do smth"); + throw new MyExceptionClassExample(e); + } + } +}