file_id
stringlengths
4
8
content
stringlengths
302
35.8k
repo
stringlengths
9
109
path
stringlengths
9
163
token_length
int64
88
7.79k
original_comment
stringlengths
11
3.46k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
259
35.6k
793_10
/** * Αυτή η κλάση αναπαραριστά ένα ηχοσύστημα. Κάθε ηχοσύστημα αποτελείται από 2 ήχεια (κλάση Speaker). * This class represents a sound system. Each sound system has 2 speakers (Speaker class). */ public class SoundSystem { Speaker speaker1; Speaker speaker2; // Κατασκευάστε δύο κατασκευαστές (υπερφόρτωση). Ο πρώτος κατασκευαστής δεν θα δέχεται κανένα όρισμα και το // ηχοσύστημα θα αποτελείται από 2 ήχεια των 40 watts και 60 spl. Ο δεύτερος κατασκευαστής θα δέχεται δύο ηχεία ως // παραμέτρους. // Create two constructors (overload). The first constructor should not have any parameters and the sound system will // have two speakers of 40 watts and 60 spl. The second constructor should have two parameters which should be // the two speakers. public SoundSystem() { this.speaker1 = new Speaker(40, 60); this.speaker2 = new Speaker(40, 60); } public SoundSystem(Speaker speaker1, Speaker speaker2) { this.speaker1 = speaker1; this.speaker2 = speaker2; } /** * Μέθοδος που αλλάζει το πρώτο ηχείο. * This method should change the first speaker. */ public void setSpeaker1(Speaker speaker) { this.speaker1 = speaker; } /** * Μέθοδος που αλλάζει το δεύτερο ηχείο. * This method should change the second speaker. */ public void setSpeaker2(Speaker speaker) { this.speaker2 = speaker; } /** * Μέθοδος που επιστρέφει το πρώτο ηχείο. * This method should return the first speaker. */ public Speaker getSpeaker1() { return speaker1; } /** * Μέθοδος που επιστρέφει το δεύτερο ηχείο. * This method should return the second speaker. */ public Speaker getSpeaker2() { return speaker2; } /** * Αυτή η μέθοδος επιστρέφει το άθροισμα της ισχύς του ηχοσυστήματος. * This method should return the sound system's total power. */ public int getTotalWatts() { return this.speaker1.getWatts() + this.speaker2.getWatts(); } /** * Ένα ηχείο θεωρήτο επικίνδυνο για το ανθρώπινο αυτί αν ξεπερνά τα 130 spl. Αυτή η μέθοδος θα πρέπει να επιστρέφει * αν το ηχοσύστημα είναι επικίνδυνο ή όχι. * A speaker is considered dangerous if it exceeds the threshold of 130 spl. This method should return if the * sound system is dangerous or not. */ public boolean isDangerous() { return this.speaker1.getSPL() > 130 || this.speaker2.getSPL() > 130; } /** * Αυτή η μέθοδος θα πρέπει να επιστρέφει την μέση βαθμολογία του ηχοσυστήματος. * This method should return the average rating of the sound system. */ public double getAverageRating() { return (this.speaker1.getRating() + this.speaker2.getRating()) / 2.0; } }
auth-csd-oop-2020/lab-objectInteraction-SoundSystem-solved
src/SoundSystem.java
1,213
/** * Αυτή η μέθοδος επιστρέφει το άθροισμα της ισχύς του ηχοσυστήματος. * This method should return the sound system's total power. */
block_comment
el
/** * Αυτή η κλάση αναπαραριστά ένα ηχοσύστημα. Κάθε ηχοσύστημα αποτελείται από 2 ήχεια (κλάση Speaker). * This class represents a sound system. Each sound system has 2 speakers (Speaker class). */ public class SoundSystem { Speaker speaker1; Speaker speaker2; // Κατασκευάστε δύο κατασκευαστές (υπερφόρτωση). Ο πρώτος κατασκευαστής δεν θα δέχεται κανένα όρισμα και το // ηχοσύστημα θα αποτελείται από 2 ήχεια των 40 watts και 60 spl. Ο δεύτερος κατασκευαστής θα δέχεται δύο ηχεία ως // παραμέτρους. // Create two constructors (overload). The first constructor should not have any parameters and the sound system will // have two speakers of 40 watts and 60 spl. The second constructor should have two parameters which should be // the two speakers. public SoundSystem() { this.speaker1 = new Speaker(40, 60); this.speaker2 = new Speaker(40, 60); } public SoundSystem(Speaker speaker1, Speaker speaker2) { this.speaker1 = speaker1; this.speaker2 = speaker2; } /** * Μέθοδος που αλλάζει το πρώτο ηχείο. * This method should change the first speaker. */ public void setSpeaker1(Speaker speaker) { this.speaker1 = speaker; } /** * Μέθοδος που αλλάζει το δεύτερο ηχείο. * This method should change the second speaker. */ public void setSpeaker2(Speaker speaker) { this.speaker2 = speaker; } /** * Μέθοδος που επιστρέφει το πρώτο ηχείο. * This method should return the first speaker. */ public Speaker getSpeaker1() { return speaker1; } /** * Μέθοδος που επιστρέφει το δεύτερο ηχείο. * This method should return the second speaker. */ public Speaker getSpeaker2() { return speaker2; } /** * Αυτή η μέθοδος<SUF>*/ public int getTotalWatts() { return this.speaker1.getWatts() + this.speaker2.getWatts(); } /** * Ένα ηχείο θεωρήτο επικίνδυνο για το ανθρώπινο αυτί αν ξεπερνά τα 130 spl. Αυτή η μέθοδος θα πρέπει να επιστρέφει * αν το ηχοσύστημα είναι επικίνδυνο ή όχι. * A speaker is considered dangerous if it exceeds the threshold of 130 spl. This method should return if the * sound system is dangerous or not. */ public boolean isDangerous() { return this.speaker1.getSPL() > 130 || this.speaker2.getSPL() > 130; } /** * Αυτή η μέθοδος θα πρέπει να επιστρέφει την μέση βαθμολογία του ηχοσυστήματος. * This method should return the average rating of the sound system. */ public double getAverageRating() { return (this.speaker1.getRating() + this.speaker2.getRating()) / 2.0; } }
13320_1
import java.util.ArrayList; import java.util.HashSet; /** * Η κλάση αυτή αποθηκεύει στη μνήμη τις συναλλαγές σε ένα σούπερ μάρκετ. * This class saves in memory all the transactions of a supermarket. * * @author Grigorios Tsoumakas */ public class Supermarket { ArrayList<Transaction> transactions = new ArrayList<>(); /** * Αυτή η μέθοδος αποθηκεύει μια συναλλαγή * This method saves a transaction * * @param t μια συναλλαγή , a transaction */ public void addTransaction(Transaction t) { transactions.add(t); } /** * Αυτή η μέθοδος επιστρέφει το πλήθος όλων των πωλήσεων ενός προϊόντος σε * όλες τις αποθηκευμένες συναλλαγές. * This method returns the total number of sales of a product from all saved transactions. * * @param product ένα προϊόν. A product * @return το πλήθος των πωλήσεων του προϊόντος. The total sales number */ public int getTotalSalesOfProduct(String product) { int total = 0; for (Transaction t : transactions) { total += t.getAmountOfProduct(product); } return total; } /** * Η μέθοδος αυτή επιστρέφει το πλήθος των μοναδικών προϊόντων που έχουν * βρεθεί σε συναλλαγές. * This method returns the number of unique products that have been found * in the transactions. * * @return Το πλήθος των μοναδικών προϊόντων. The total number of unique products */ public int uniqueProducts() { HashSet<String> unique = new HashSet<>(); for (Transaction t : transactions) { String[] products = t.getProducts(); for (String product : products) { unique.add(product); } } return unique.size(); } }
auth-csd-oop-2022/lab-advancedBehavior-Supermarket-solved
src/Supermarket.java
672
/** * Αυτή η μέθοδος αποθηκεύει μια συναλλαγή * This method saves a transaction * * @param t μια συναλλαγή , a transaction */
block_comment
el
import java.util.ArrayList; import java.util.HashSet; /** * Η κλάση αυτή αποθηκεύει στη μνήμη τις συναλλαγές σε ένα σούπερ μάρκετ. * This class saves in memory all the transactions of a supermarket. * * @author Grigorios Tsoumakas */ public class Supermarket { ArrayList<Transaction> transactions = new ArrayList<>(); /** * Αυτή η μέθοδος<SUF>*/ public void addTransaction(Transaction t) { transactions.add(t); } /** * Αυτή η μέθοδος επιστρέφει το πλήθος όλων των πωλήσεων ενός προϊόντος σε * όλες τις αποθηκευμένες συναλλαγές. * This method returns the total number of sales of a product from all saved transactions. * * @param product ένα προϊόν. A product * @return το πλήθος των πωλήσεων του προϊόντος. The total sales number */ public int getTotalSalesOfProduct(String product) { int total = 0; for (Transaction t : transactions) { total += t.getAmountOfProduct(product); } return total; } /** * Η μέθοδος αυτή επιστρέφει το πλήθος των μοναδικών προϊόντων που έχουν * βρεθεί σε συναλλαγές. * This method returns the number of unique products that have been found * in the transactions. * * @return Το πλήθος των μοναδικών προϊόντων. The total number of unique products */ public int uniqueProducts() { HashSet<String> unique = new HashSet<>(); for (Transaction t : transactions) { String[] products = t.getProducts(); for (String product : products) { unique.add(product); } } return unique.size(); } }
714_2
import java.util.ArrayList; /** * To σύστημα πληρωμής φόρων αποτελείται από δύο λίστες μία που περιέχει όλα τα αυτοκίνητα για τα οποία πρέπει να * πληρωθεί φόρος και μία για τα σπίτια. Επιπλέον έχει και έναν τρόπο υπολογισμού αυτών των φόρων * <p> * The tax payment system consists of two lists one for all the cars whose taxes need to be payed and one for the * houses. Furthermore it contains a way of calculating those taxes. */ public class TaxSystem { private ArrayList<Car> cars; private ArrayList<House> houses; private Tax tax; /** * Κατασκευαστής/Constructor * * @param tax ο τρόπος υπολογισμού των φόρων/ The way of calculating the taxes */ public TaxSystem(Tax tax) { this.tax = tax; cars = new ArrayList<>(); houses = new ArrayList<>(); } /** * Προσθήκη ενός αυτοκινήτου/ add a car */ public void addCar(Car car) { cars.add(car); } /** * Προσθήκη ενός σπιτιού/ add a house */ public void addHouse(House house) { houses.add(house); } /** * Υπολογίζει και επιστρέφει μια λίστα με τους τελικούς φόρους για κάθε αυτοκίνητο Computes and returns a list with * the final taxes for each car */ public ArrayList<Double> getCarTaxes() { ArrayList<Double> carTaxes = new ArrayList<>(); for (Car car : this.cars) { carTaxes.add(this.tax.carTax(car)); } return carTaxes; } /** * Υπολογίζει και επιστρέφει μια λίστα με τoυς τελικούς φόρους για κάθε σπίτι Computes and returns a list with the * final taxes for each house */ public ArrayList<Double> geHouseTaxes() { ArrayList<Double> houseTaxes = new ArrayList<>(); for (House house : this.houses) { houseTaxes.add(this.tax.houseTax(house)); } return houseTaxes; } /** * Υπολογίζει και επιστρέφει το συνολικό πόσο όλων των φόρων (και για τα αυτοκίνητα και για τα σπίτια). Computes and * returns the total amount of taxes (for both the cars and the houses) */ public double getTotalTaxes() { double total = 0; for (Double carTaxes : this.getCarTaxes()) { total += carTaxes; } for (Double houseTaxes : this.geHouseTaxes()) { total += houseTaxes; } return total; } }
auth-csd-oop-2023/lab-abstraction-TaxSystem-solved
src/TaxSystem.java
958
/** * Προσθήκη ενός αυτοκινήτου/ add a car */
block_comment
el
import java.util.ArrayList; /** * To σύστημα πληρωμής φόρων αποτελείται από δύο λίστες μία που περιέχει όλα τα αυτοκίνητα για τα οποία πρέπει να * πληρωθεί φόρος και μία για τα σπίτια. Επιπλέον έχει και έναν τρόπο υπολογισμού αυτών των φόρων * <p> * The tax payment system consists of two lists one for all the cars whose taxes need to be payed and one for the * houses. Furthermore it contains a way of calculating those taxes. */ public class TaxSystem { private ArrayList<Car> cars; private ArrayList<House> houses; private Tax tax; /** * Κατασκευαστής/Constructor * * @param tax ο τρόπος υπολογισμού των φόρων/ The way of calculating the taxes */ public TaxSystem(Tax tax) { this.tax = tax; cars = new ArrayList<>(); houses = new ArrayList<>(); } /** * Προσθήκη ενός αυτοκινήτου/<SUF>*/ public void addCar(Car car) { cars.add(car); } /** * Προσθήκη ενός σπιτιού/ add a house */ public void addHouse(House house) { houses.add(house); } /** * Υπολογίζει και επιστρέφει μια λίστα με τους τελικούς φόρους για κάθε αυτοκίνητο Computes and returns a list with * the final taxes for each car */ public ArrayList<Double> getCarTaxes() { ArrayList<Double> carTaxes = new ArrayList<>(); for (Car car : this.cars) { carTaxes.add(this.tax.carTax(car)); } return carTaxes; } /** * Υπολογίζει και επιστρέφει μια λίστα με τoυς τελικούς φόρους για κάθε σπίτι Computes and returns a list with the * final taxes for each house */ public ArrayList<Double> geHouseTaxes() { ArrayList<Double> houseTaxes = new ArrayList<>(); for (House house : this.houses) { houseTaxes.add(this.tax.houseTax(house)); } return houseTaxes; } /** * Υπολογίζει και επιστρέφει το συνολικό πόσο όλων των φόρων (και για τα αυτοκίνητα και για τα σπίτια). Computes and * returns the total amount of taxes (for both the cars and the houses) */ public double getTotalTaxes() { double total = 0; for (Double carTaxes : this.getCarTaxes()) { total += carTaxes; } for (Double houseTaxes : this.geHouseTaxes()) { total += houseTaxes; } return total; } }
1033_0
import java.util.ArrayList; import java.util.HashSet; /** * Η κλάση αυτή αποθηκεύει στη μνήμη τις συναλλαγές σε ένα σούπερ μάρκετ. * This class saves in memory all the transactions of a supermarket. * * @author Grigorios Tsoumakas */ public class Supermarket { ArrayList<Transaction> transactions = new ArrayList<>(); /** * Αυτή η μέθοδος αποθηκεύει μια συναλλαγή * This method saves a transaction * * @param t μια συναλλαγή , a transaction */ public void addTransaction(Transaction t) { transactions.add(t); } /** * Αυτή η μέθοδος επιστρέφει το πλήθος όλων των πωλήσεων ενός προϊόντος σε * όλες τις αποθηκευμένες συναλλαγές. * This method returns the total number of sales of a product from all saved transactions. * * @param product ένα προϊόν. A product * @return το πλήθος των πωλήσεων του προϊόντος. The total sales number */ public int getTotalSalesOfProduct(String product) { int total = 0; for (Transaction t : transactions) { total += t.getAmountOfProduct(product); } return total; } /** * Η μέθοδος αυτή επιστρέφει το πλήθος των μοναδικών προϊόντων που έχουν * βρεθεί σε συναλλαγές. * This method returns the number of unique products that have been found * in the transactions. * * @return Το πλήθος των μοναδικών προϊόντων. The total number of unique products */ public int uniqueProducts() { HashSet<String> unique = new HashSet<>(); for (Transaction t : transactions) { String[] products = t.getProducts(); for (String product : products) { unique.add(product); } } return unique.size(); } }
auth-csd-oop-2023/lab-advancedBehavior-Supermarket-solved
src/Supermarket.java
672
/** * Η κλάση αυτή αποθηκεύει στη μνήμη τις συναλλαγές σε ένα σούπερ μάρκετ. * This class saves in memory all the transactions of a supermarket. * * @author Grigorios Tsoumakas */
block_comment
el
import java.util.ArrayList; import java.util.HashSet; /** * Η κλάση αυτή<SUF>*/ public class Supermarket { ArrayList<Transaction> transactions = new ArrayList<>(); /** * Αυτή η μέθοδος αποθηκεύει μια συναλλαγή * This method saves a transaction * * @param t μια συναλλαγή , a transaction */ public void addTransaction(Transaction t) { transactions.add(t); } /** * Αυτή η μέθοδος επιστρέφει το πλήθος όλων των πωλήσεων ενός προϊόντος σε * όλες τις αποθηκευμένες συναλλαγές. * This method returns the total number of sales of a product from all saved transactions. * * @param product ένα προϊόν. A product * @return το πλήθος των πωλήσεων του προϊόντος. The total sales number */ public int getTotalSalesOfProduct(String product) { int total = 0; for (Transaction t : transactions) { total += t.getAmountOfProduct(product); } return total; } /** * Η μέθοδος αυτή επιστρέφει το πλήθος των μοναδικών προϊόντων που έχουν * βρεθεί σε συναλλαγές. * This method returns the number of unique products that have been found * in the transactions. * * @return Το πλήθος των μοναδικών προϊόντων. The total number of unique products */ public int uniqueProducts() { HashSet<String> unique = new HashSet<>(); for (Transaction t : transactions) { String[] products = t.getProducts(); for (String product : products) { unique.add(product); } } return unique.size(); } }
451_6
import java.util.ArrayList; /** * Αυτή η κλάση αναπαριστά έναν/μία ηθοποιό με το όνομα του/της, την ηλικία του/της και την λίστα με τις ταινίες * στις οποίες έχει παίξει. * This class represents an actor/actress with his/her name, age and list of movies he/she participated. */ public class Actor { private String name; private int age; private ArrayList<Movie> movies; /** * Κατασκευαστής - Constructor */ public Actor(String name, int age) { this.name = name; this.age = age; this.movies = new ArrayList<>(); } /** * Αυτή η μέθοδος επιστρέφει το όνομα του ηθοποιού. * This method returns the actor's name. */ public String getName() { return name; } /** * Αυτή η μέθοδος επιστρέφει την ηλικία του ηθοποιού. * This method returns the actor's age. */ public int getAge() { return age; } /** * Αυτή η μέθοδος προσθέτει μια ταινία στην λίστα ταινιών του ηθοποιού. * This methods adds a movie to hir/her lists of movies. */ public void addMovie(String title, int duration, int oscars, int budget) { this.movies.add(new Movie(title, duration, oscars, budget)); } /** * Αυτή η μέθοδος επιστρέφει τις ταινίες στις οποίες έχει παίξει ο ηθοποιός. * This methods returns the movies the actor has participated. */ public ArrayList<Movie> getMovies() { return this.movies; } /** * Αυτή η μέθοδος υπολογίζει τον χρόνο σε λεπτά που ο/η ηθοποιός έχει παίξει σε ταινίες μεγάλου μήκους (>1 ώρα) * This method computes the total play time of the actor in long movies (>1 hour) */ public int totalActingTime() { int sum = 0; for (Movie movie : this.movies) { if (movie.getDuration() > 60) { sum += movie.getDuration(); } } return sum; } /** * Αυτή η μέθοδος υπολογίζει την "δημοφιλία" του/της ηθοποιού. Η δημοφιλία υπολογίζεται ως ο συνολικός αριθμός των * ταινιών που έχει παίξει προς τον αριθμό των οσκαρικών ταινιών που έχει παίξει. * This method computes the "popularity" of the actor. The popularity is the total number of movies he/she * participated to the total number of oscar-winning movies he/she participated. */ public double popularity() { int totalOscars = 0; for (Movie movie : this.movies) { if (movie.getOscars() > 0) { totalOscars += 1; } } return this.movies.size() / (double) totalOscars; } }
auth-csd-oop-2023/lab-groupingObjects-MovieActor-solved
src/Actor.java
1,097
/** * Αυτή η μέθοδος υπολογίζει τον χρόνο σε λεπτά που ο/η ηθοποιός έχει παίξει σε ταινίες μεγάλου μήκους (>1 ώρα) * This method computes the total play time of the actor in long movies (>1 hour) */
block_comment
el
import java.util.ArrayList; /** * Αυτή η κλάση αναπαριστά έναν/μία ηθοποιό με το όνομα του/της, την ηλικία του/της και την λίστα με τις ταινίες * στις οποίες έχει παίξει. * This class represents an actor/actress with his/her name, age and list of movies he/she participated. */ public class Actor { private String name; private int age; private ArrayList<Movie> movies; /** * Κατασκευαστής - Constructor */ public Actor(String name, int age) { this.name = name; this.age = age; this.movies = new ArrayList<>(); } /** * Αυτή η μέθοδος επιστρέφει το όνομα του ηθοποιού. * This method returns the actor's name. */ public String getName() { return name; } /** * Αυτή η μέθοδος επιστρέφει την ηλικία του ηθοποιού. * This method returns the actor's age. */ public int getAge() { return age; } /** * Αυτή η μέθοδος προσθέτει μια ταινία στην λίστα ταινιών του ηθοποιού. * This methods adds a movie to hir/her lists of movies. */ public void addMovie(String title, int duration, int oscars, int budget) { this.movies.add(new Movie(title, duration, oscars, budget)); } /** * Αυτή η μέθοδος επιστρέφει τις ταινίες στις οποίες έχει παίξει ο ηθοποιός. * This methods returns the movies the actor has participated. */ public ArrayList<Movie> getMovies() { return this.movies; } /** * Αυτή η μέθοδος<SUF>*/ public int totalActingTime() { int sum = 0; for (Movie movie : this.movies) { if (movie.getDuration() > 60) { sum += movie.getDuration(); } } return sum; } /** * Αυτή η μέθοδος υπολογίζει την "δημοφιλία" του/της ηθοποιού. Η δημοφιλία υπολογίζεται ως ο συνολικός αριθμός των * ταινιών που έχει παίξει προς τον αριθμό των οσκαρικών ταινιών που έχει παίξει. * This method computes the "popularity" of the actor. The popularity is the total number of movies he/she * participated to the total number of oscar-winning movies he/she participated. */ public double popularity() { int totalOscars = 0; for (Movie movie : this.movies) { if (movie.getOscars() > 0) { totalOscars += 1; } } return this.movies.size() / (double) totalOscars; } }
467_3
/** * Αυτή η κλάση αναπαριστά ένα σκούτερ με μηχανή εσωτερικής καύσης. * <p> * This class represents a scooter with an internal combustion engine. */ public class Scooter { private int maxKM; private int year; public Scooter() { } /** * Κατασκευαστής / Constructor * * @param maxKM Ο μέγιστος αριθμός χιλιομέτρων που μπορεί να διανύσει με ένα γέμισμα. The maximum number of * kilometers you can travel with a full tank. * @param year Το έτος κυκλοφορίας του οχήματος / the release year of the vehicle. */ public Scooter(int maxKM, int year) { this.maxKM = maxKM; this.year = year; } /** * @return Το μέγιστο αριθμό χιλιομέτρων που μπορεί να διανύσει με ένα γέμισμα. * <p> * The maximum number of kilometers you can travel with a full tank. */ public int getMaxKM() { return this.maxKM; } /** * @return Το έτος κυκλοφορίας του οχήματος / the release year of the vehicle. */ public int getYear() { return this.year; } /** * Κάθε όχημα χαρακτηρίζεται από μια βαθμολογία ανάλογα με τους ρύπους που παράγει. Το σκορ αυτό είναι ίσο με τον * αριθμό των μέγιστων χιλιομέτρων επί τον μέσο αριθμό γεμισμάτων ανα έτος (250), διά το σύνολο των ημερών ενός * έτους (365) * <p> * Each vehicle has a score that represents the pollutants that produces. This score equals the maximum kilometers * of the vehicle multiplied by the average number of fillings during a year (250), divided by the number of days * in a year (365) * * @return Το σκορ μόλυνσης του περιβάλλοντος, the pollution score. */ public double getPollutionScore() { return this.maxKM * 250 / 365d; } /** * Μέθοδος που υπολογίζει τα τέλη κυκλοφορίας του οχήματος. Τα τέλη κυκλοφορίας ισούται με τα έτη που κυκλοφορεί το * όχημα μέχρι σήμερα (2018) επι 12.5 που είναι ένας σταθερός αριθμός. * <p> * This method computes the annual taxes of the vehicle. The annual taxes equal the number of years from the release * day till today (2018) multiplied by 12.5 which is a constant value. * * @return Τα τέλη κυκλοφορίας / the annual tax of the vehicle */ public double getTaxes() { return (2018 - this.year) * 12.5; } }
auth-csd-oop-2023/lab-inheritance-Scooter-solved
src/Scooter.java
1,101
/** * @return Το έτος κυκλοφορίας του οχήματος / the release year of the vehicle. */
block_comment
el
/** * Αυτή η κλάση αναπαριστά ένα σκούτερ με μηχανή εσωτερικής καύσης. * <p> * This class represents a scooter with an internal combustion engine. */ public class Scooter { private int maxKM; private int year; public Scooter() { } /** * Κατασκευαστής / Constructor * * @param maxKM Ο μέγιστος αριθμός χιλιομέτρων που μπορεί να διανύσει με ένα γέμισμα. The maximum number of * kilometers you can travel with a full tank. * @param year Το έτος κυκλοφορίας του οχήματος / the release year of the vehicle. */ public Scooter(int maxKM, int year) { this.maxKM = maxKM; this.year = year; } /** * @return Το μέγιστο αριθμό χιλιομέτρων που μπορεί να διανύσει με ένα γέμισμα. * <p> * The maximum number of kilometers you can travel with a full tank. */ public int getMaxKM() { return this.maxKM; } /** * @return Το έτος<SUF>*/ public int getYear() { return this.year; } /** * Κάθε όχημα χαρακτηρίζεται από μια βαθμολογία ανάλογα με τους ρύπους που παράγει. Το σκορ αυτό είναι ίσο με τον * αριθμό των μέγιστων χιλιομέτρων επί τον μέσο αριθμό γεμισμάτων ανα έτος (250), διά το σύνολο των ημερών ενός * έτους (365) * <p> * Each vehicle has a score that represents the pollutants that produces. This score equals the maximum kilometers * of the vehicle multiplied by the average number of fillings during a year (250), divided by the number of days * in a year (365) * * @return Το σκορ μόλυνσης του περιβάλλοντος, the pollution score. */ public double getPollutionScore() { return this.maxKM * 250 / 365d; } /** * Μέθοδος που υπολογίζει τα τέλη κυκλοφορίας του οχήματος. Τα τέλη κυκλοφορίας ισούται με τα έτη που κυκλοφορεί το * όχημα μέχρι σήμερα (2018) επι 12.5 που είναι ένας σταθερός αριθμός. * <p> * This method computes the annual taxes of the vehicle. The annual taxes equal the number of years from the release * day till today (2018) multiplied by 12.5 which is a constant value. * * @return Τα τέλη κυκλοφορίας / the annual tax of the vehicle */ public double getTaxes() { return (2018 - this.year) * 12.5; } }
465_4
/** * Αυτή η κλάση αναπαριστά ένα ηχείο. Το ηχείο έχει δύο χαρακτηριστικά, την ισχύ (Watts) και την πίεση του ήχου (Sound * Pressure Level - SPL) που την μετράμε σε deciBels (dB). * This class represents a speaker. The speaker has two attributes, its power (Watts) and its Sound Pressure Level - SPL * measured in deviBels (dB). */ public class Speaker { private int watts; // Δημιουργήστε έναν κατασκευαστή που να δέχεται ως παραμέτρους τα χαρακτηριστικά του ηχείου. // Create a constructor that has as parameters the speakers attributes. public Speaker(int watts) { this.watts = watts; } /** * Μέθοδος που αλλάζει τα watts του ηχείου. * This method should change the speaker's watts. */ public void setWatts(int watts) { this.watts = watts; } /** * Μέθοδος που επιστρέφει τα Watts του ηχείου. * This method should return the speaker's Watts. */ public int getWatts() { return this.watts; } /** * Το ηχείο παίρνει μια βαθμολογία (1-5) ανάλογα με την ισχύ του. Αν η ισχύς είναι κάτω από 30 Watts παίρνει τον * βαθμό 1. Αντίστοιχα (60 -> 2, 80 -> 3, 100-> 4, >100 -> 5). Αυτή η μέθοδος επιστρέφει την βαθμολογία. * Each speaker is rated from 1 to 5 based on its power (watts). If its power is less than 30 watts it is rated with * 1. Respectively (60 -> 2, 80 -> 3, 100-> 4, >100 -> 5). This method should return the speakers rating, * * βαθμό 1. Αντίστοιχα */ public int getRating() { if (this.watts < 30) { return 1; } else if (this.watts < 60) { return 2; } else if (this.watts < 80) { return 3; } else if (this.watts < 100) { return 4; } else { return 5; } } }
auth-csd-oop-2023/lab-objectInteraction-SoundSystem-Simple-solved
src/Speaker.java
837
/** * Μέθοδος που επιστρέφει τα Watts του ηχείου. * This method should return the speaker's Watts. */
block_comment
el
/** * Αυτή η κλάση αναπαριστά ένα ηχείο. Το ηχείο έχει δύο χαρακτηριστικά, την ισχύ (Watts) και την πίεση του ήχου (Sound * Pressure Level - SPL) που την μετράμε σε deciBels (dB). * This class represents a speaker. The speaker has two attributes, its power (Watts) and its Sound Pressure Level - SPL * measured in deviBels (dB). */ public class Speaker { private int watts; // Δημιουργήστε έναν κατασκευαστή που να δέχεται ως παραμέτρους τα χαρακτηριστικά του ηχείου. // Create a constructor that has as parameters the speakers attributes. public Speaker(int watts) { this.watts = watts; } /** * Μέθοδος που αλλάζει τα watts του ηχείου. * This method should change the speaker's watts. */ public void setWatts(int watts) { this.watts = watts; } /** * Μέθοδος που επιστρέφει<SUF>*/ public int getWatts() { return this.watts; } /** * Το ηχείο παίρνει μια βαθμολογία (1-5) ανάλογα με την ισχύ του. Αν η ισχύς είναι κάτω από 30 Watts παίρνει τον * βαθμό 1. Αντίστοιχα (60 -> 2, 80 -> 3, 100-> 4, >100 -> 5). Αυτή η μέθοδος επιστρέφει την βαθμολογία. * Each speaker is rated from 1 to 5 based on its power (watts). If its power is less than 30 watts it is rated with * 1. Respectively (60 -> 2, 80 -> 3, 100-> 4, >100 -> 5). This method should return the speakers rating, * * βαθμό 1. Αντίστοιχα */ public int getRating() { if (this.watts < 30) { return 1; } else if (this.watts < 60) { return 2; } else if (this.watts < 80) { return 3; } else if (this.watts < 100) { return 4; } else { return 5; } } }
42_6
/** * Η κλάση αυτή αφορά σε ένα θερμαντικό σώμα, το οποίο θα ξεκινάει στους 15 * βαθμούς κελσίου. Η θερμοκρασία του θα μπορεί να αυξηθεί ή να μειωθεί κατά * ένα βήμα, το οποίο αρχικά θα είναι 5 βαθμοί κελσίου. Η ρύθμιση της * θερμοκρασίας δεν θα πρέπει να βγαίνει εκτός ενός κατώτερου και ενός ανώτερου * ορίου. * <p> * This class represents a heater/radiator which has a starting temperature of 15 * degrees. Its temperature should be able to be increased or decreased using a step. * Initially, this step is set to 5 degrees. The temperature should not exceed an upper * and a lower limit. */ public class Heater { /* O κατασκευαστής θα δέχεται δύο παραμέτρους. Η πρώτη παράμετρος θα αφορά στην ελάχιστη και η δεύτερη στην μέγιστη θερμοκρασία στην οποία επιτρέπεται να ρυθμιστεί το θερμαντικό σώμα. The constructor should have two parameters. The first is the minimum temperature and the second parameter is the maximum temperature which the heater can be set to. */ double min = 0; double max = 0; double currentTemperature = 15; double step = 5; public Heater(double min, double max) { this.min = min; this.max = max; } // Η μέθοδος αυτή θα αυξάνει την θερμοκρασία σύμφωνα με το βήμα // This method increases the temperature using the step public void warmer() { double temporaryTemp = this.currentTemperature + this.step; if (temporaryTemp <= this.max) { this.currentTemperature = temporaryTemp; } } // Η μέθοδος αυτή θα μειώνει την θερμοκρασία σύμφωνα με το βήμα // This method decreases the temperature using the step public void colder() { double temporaryTemp = this.currentTemperature - this.step; if (temporaryTemp >= this.min) { this.currentTemperature = temporaryTemp; } } //Η μέθοδος αυτή θα αλλάζει το βήμα // This method changes the step public void setIncrement(double step) { this.step = Math.abs(step); } // η μέθοδος αυτή θα επιστρέφει την ρύθμιση της θερμοκρασίας // This method should return the current temperature of the heater public double getTemperature() { return this.currentTemperature; } }
auth-csd-oop-master/lab-introduction-solved
src/Heater.java
994
//Η μέθοδος αυτή θα αλλάζει το βήμα
line_comment
el
/** * Η κλάση αυτή αφορά σε ένα θερμαντικό σώμα, το οποίο θα ξεκινάει στους 15 * βαθμούς κελσίου. Η θερμοκρασία του θα μπορεί να αυξηθεί ή να μειωθεί κατά * ένα βήμα, το οποίο αρχικά θα είναι 5 βαθμοί κελσίου. Η ρύθμιση της * θερμοκρασίας δεν θα πρέπει να βγαίνει εκτός ενός κατώτερου και ενός ανώτερου * ορίου. * <p> * This class represents a heater/radiator which has a starting temperature of 15 * degrees. Its temperature should be able to be increased or decreased using a step. * Initially, this step is set to 5 degrees. The temperature should not exceed an upper * and a lower limit. */ public class Heater { /* O κατασκευαστής θα δέχεται δύο παραμέτρους. Η πρώτη παράμετρος θα αφορά στην ελάχιστη και η δεύτερη στην μέγιστη θερμοκρασία στην οποία επιτρέπεται να ρυθμιστεί το θερμαντικό σώμα. The constructor should have two parameters. The first is the minimum temperature and the second parameter is the maximum temperature which the heater can be set to. */ double min = 0; double max = 0; double currentTemperature = 15; double step = 5; public Heater(double min, double max) { this.min = min; this.max = max; } // Η μέθοδος αυτή θα αυξάνει την θερμοκρασία σύμφωνα με το βήμα // This method increases the temperature using the step public void warmer() { double temporaryTemp = this.currentTemperature + this.step; if (temporaryTemp <= this.max) { this.currentTemperature = temporaryTemp; } } // Η μέθοδος αυτή θα μειώνει την θερμοκρασία σύμφωνα με το βήμα // This method decreases the temperature using the step public void colder() { double temporaryTemp = this.currentTemperature - this.step; if (temporaryTemp >= this.min) { this.currentTemperature = temporaryTemp; } } //Η μέθοδος<SUF> // This method changes the step public void setIncrement(double step) { this.step = Math.abs(step); } // η μέθοδος αυτή θα επιστρέφει την ρύθμιση της θερμοκρασίας // This method should return the current temperature of the heater public double getTemperature() { return this.currentTemperature; } }
20214_6
/** * Copyright (c) 2018-present, A2 Rešitve d.o.o. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package solutions.a2.cdc.oracle; import static org.junit.jupiter.api.Assertions.fail; import java.sql.SQLException; import org.junit.jupiter.api.Test; /** * * @author <a href="mailto:[email protected]">Aleksei Veremeev</a> * */ public class OraDumpDecoderTest { @Test public void test() { // select DUMP('thanks', 16) from DUAL; // Typ=96 Len=6: 74,68,61,6e,6b,73 String sUsAscii = "7468616e6b73"; // select DUMP('謝謝啦', 16) from DUAL; // Typ=96 Len=9: e8,ac,9d,e8,ac,9d,e5,95,a6 String sTrChinese = "e8ac9de8ac9de595a6"; // select DUMP('Σας ευχαριστώ', 16) from DUAL; // Typ=96 Len=25: ce,a3,ce,b1,cf,82,20,ce,b5,cf,85,cf,87,ce,b1,cf,81,ce,b9,cf,83,cf,84,cf,8e String sGreek = "cea3ceb1cf8220ceb5cf85cf87ceb1cf81ceb9cf83cf84cf8e"; // select DUMP('Спасибо', 16) from DUAL; // Typ=96 Len=14: d0,a1,d0,bf,d0,b0,d1,81,d0,b8,d0,b1,d0,be String sCyrillic = "d0a1d0bfd0b0d181d0b8d0b1d0be"; /* create table NUMBER_TEST(ID NUMBER, BF BINARY_FLOAT, BD BINARY_DOUBLE, NN117 NUMBER(11,7)); insert into NUMBER_TEST values(-.1828, SQRT(3),SQRT(3),SQRT(3)); SQL> select dump(ID, 16) from NUMBER_TEST; DUMP(ID,16) -------------------------------------------------------------------------------- Typ=2 Len=4: 3f,53,49,66 SQL> select dump(BF, 16) from NUMBER_TEST; DUMP(BF,16) -------------------------------------------------------------------------------- Typ=100 Len=4: bf,dd,b3,d7 SQL> select dump(BD, 16) from NUMBER_TEST; DUMP(BD,16) -------------------------------------------------------------------------------- Typ=101 Len=8: bf,fb,b6,7a,e8,58,4c,aa SQL> select dump(NN117, 16) from NUMBER_TEST; DUMP(NN117,16) -------------------------------------------------------------------------------- Typ=2 Len=6: c1,2,4a,15,33,51 */ String bdNegative = "3f534966"; String binaryFloatSqrt3 = "bfddb3d7"; String binaryDoubleSqrt3 = "bffbb67ae8584caa"; String number_11_7_Sqrt3 = "c1024a153351"; OraDumpDecoder odd = null; odd = new OraDumpDecoder("AL32UTF8", "AL16UTF16"); try { System.out.println(odd.fromVarchar2(sUsAscii)); System.out.println(odd.fromVarchar2(sTrChinese)); System.out.println(odd.fromVarchar2(sGreek)); System.out.println(odd.fromVarchar2(sCyrillic)); System.out.println(OraDumpDecoder.toBigDecimal(bdNegative)); System.out.println(OraDumpDecoder.toFloat(bdNegative)); System.out.println(OraDumpDecoder.toDouble(bdNegative)); System.out.println(OraDumpDecoder.fromBinaryFloat(binaryFloatSqrt3)); System.out.println(OraDumpDecoder.fromBinaryDouble(binaryDoubleSqrt3)); System.out.println(OraDumpDecoder.toBigDecimal(number_11_7_Sqrt3)); System.out.println(OraDumpDecoder.toFloat(number_11_7_Sqrt3)); System.out.println(OraDumpDecoder.toDouble(number_11_7_Sqrt3)); } catch (SQLException e) { e.printStackTrace(); fail("Exception " + e.getMessage()); } } }
averemee-si/oracdc
src/test/java/solutions/a2/cdc/oracle/OraDumpDecoderTest.java
1,373
// select DUMP('Σας ευχαριστώ', 16) from DUAL;
line_comment
el
/** * Copyright (c) 2018-present, A2 Rešitve d.o.o. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package solutions.a2.cdc.oracle; import static org.junit.jupiter.api.Assertions.fail; import java.sql.SQLException; import org.junit.jupiter.api.Test; /** * * @author <a href="mailto:[email protected]">Aleksei Veremeev</a> * */ public class OraDumpDecoderTest { @Test public void test() { // select DUMP('thanks', 16) from DUAL; // Typ=96 Len=6: 74,68,61,6e,6b,73 String sUsAscii = "7468616e6b73"; // select DUMP('謝謝啦', 16) from DUAL; // Typ=96 Len=9: e8,ac,9d,e8,ac,9d,e5,95,a6 String sTrChinese = "e8ac9de8ac9de595a6"; // select DUMP('Σας<SUF> // Typ=96 Len=25: ce,a3,ce,b1,cf,82,20,ce,b5,cf,85,cf,87,ce,b1,cf,81,ce,b9,cf,83,cf,84,cf,8e String sGreek = "cea3ceb1cf8220ceb5cf85cf87ceb1cf81ceb9cf83cf84cf8e"; // select DUMP('Спасибо', 16) from DUAL; // Typ=96 Len=14: d0,a1,d0,bf,d0,b0,d1,81,d0,b8,d0,b1,d0,be String sCyrillic = "d0a1d0bfd0b0d181d0b8d0b1d0be"; /* create table NUMBER_TEST(ID NUMBER, BF BINARY_FLOAT, BD BINARY_DOUBLE, NN117 NUMBER(11,7)); insert into NUMBER_TEST values(-.1828, SQRT(3),SQRT(3),SQRT(3)); SQL> select dump(ID, 16) from NUMBER_TEST; DUMP(ID,16) -------------------------------------------------------------------------------- Typ=2 Len=4: 3f,53,49,66 SQL> select dump(BF, 16) from NUMBER_TEST; DUMP(BF,16) -------------------------------------------------------------------------------- Typ=100 Len=4: bf,dd,b3,d7 SQL> select dump(BD, 16) from NUMBER_TEST; DUMP(BD,16) -------------------------------------------------------------------------------- Typ=101 Len=8: bf,fb,b6,7a,e8,58,4c,aa SQL> select dump(NN117, 16) from NUMBER_TEST; DUMP(NN117,16) -------------------------------------------------------------------------------- Typ=2 Len=6: c1,2,4a,15,33,51 */ String bdNegative = "3f534966"; String binaryFloatSqrt3 = "bfddb3d7"; String binaryDoubleSqrt3 = "bffbb67ae8584caa"; String number_11_7_Sqrt3 = "c1024a153351"; OraDumpDecoder odd = null; odd = new OraDumpDecoder("AL32UTF8", "AL16UTF16"); try { System.out.println(odd.fromVarchar2(sUsAscii)); System.out.println(odd.fromVarchar2(sTrChinese)); System.out.println(odd.fromVarchar2(sGreek)); System.out.println(odd.fromVarchar2(sCyrillic)); System.out.println(OraDumpDecoder.toBigDecimal(bdNegative)); System.out.println(OraDumpDecoder.toFloat(bdNegative)); System.out.println(OraDumpDecoder.toDouble(bdNegative)); System.out.println(OraDumpDecoder.fromBinaryFloat(binaryFloatSqrt3)); System.out.println(OraDumpDecoder.fromBinaryDouble(binaryDoubleSqrt3)); System.out.println(OraDumpDecoder.toBigDecimal(number_11_7_Sqrt3)); System.out.println(OraDumpDecoder.toFloat(number_11_7_Sqrt3)); System.out.println(OraDumpDecoder.toDouble(number_11_7_Sqrt3)); } catch (SQLException e) { e.printStackTrace(); fail("Exception " + e.getMessage()); } } }
2042_5
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template */ package gr.mycompany.btree; /** * * @author Spyros */ public class BtreeMain { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO create the root node and the rest nodes without connection BtreeNode rootNode = new BtreeNode("root"); rootNode.printBtreeNode(); BtreeNode aNode = new BtreeNode("a"); aNode.printBtreeNode(); BtreeNode bNode = new BtreeNode("b"); bNode.printBtreeNode(); BtreeNode cNode = new BtreeNode("c"); cNode.printBtreeNode(); BtreeNode dNode = new BtreeNode("d"); dNode.printBtreeNode(); BtreeNode eNode = new BtreeNode("e"); eNode.printBtreeNode(); //TODO create the connections as the following example in comments /* Binary Tree Ακριβώς μία ρίζα Το πολύ δύο παιδιά ανά κόμβο Ακριβώς ένα μονοπάτι για κάθε κόμβο Οι κόμβοι χωρίς κανένα παιδί λέγονται φύλλα [root] / \ a b / \ \ c d e */ rootNode.setLeft(aNode); rootNode.setRight(bNode); System.out.println("\n*** root node has now two children ***\n"); rootNode.printBtreeNode(); //TODO complete the tree in the comments above //TODO create a method in BtreeNode class to see if the node is leaf (has no children) } }
avlonitiss/BtreeJava
src/main/java/gr/mycompany/btree/BtreeMain.java
504
/* Binary Tree Ακριβώς μία ρίζα Το πολύ δύο παιδιά ανά κόμβο Ακριβώς ένα μονοπάτι για κάθε κόμβο Οι κόμβοι χωρίς κανένα παιδί λέγονται φύλλα [root] / \ a b / \ \ c d e */
block_comment
el
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template */ package gr.mycompany.btree; /** * * @author Spyros */ public class BtreeMain { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO create the root node and the rest nodes without connection BtreeNode rootNode = new BtreeNode("root"); rootNode.printBtreeNode(); BtreeNode aNode = new BtreeNode("a"); aNode.printBtreeNode(); BtreeNode bNode = new BtreeNode("b"); bNode.printBtreeNode(); BtreeNode cNode = new BtreeNode("c"); cNode.printBtreeNode(); BtreeNode dNode = new BtreeNode("d"); dNode.printBtreeNode(); BtreeNode eNode = new BtreeNode("e"); eNode.printBtreeNode(); //TODO create the connections as the following example in comments /* Binary Tree <SUF>*/ rootNode.setLeft(aNode); rootNode.setRight(bNode); System.out.println("\n*** root node has now two children ***\n"); rootNode.printBtreeNode(); //TODO complete the tree in the comments above //TODO create a method in BtreeNode class to see if the node is leaf (has no children) } }
611_2
package org.rome.easycity; import androidx.fragment.app.FragmentActivity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class EasyCityMapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_easy_city_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Προσδιορισμός εκδηλώσεων από backend float zoomLevel = (float) 13.0; LatLng myLocation = new LatLng(37.98, 23.72); LatLng museum = new LatLng(37.989, 23.732); LatLng acropol = new LatLng(37.971, 23.725); mMap.addMarker(new MarkerOptions().position(myLocation).title("Είμαι εδώ")); mMap.addMarker(new MarkerOptions().position(museum).title("ΕΘΝΙΚΟ ΑΡΧΑΙΟΛΟΓΙΚΟ ΜΟΥΣΕΙΟ").snippet("Ομιλία του καθηγητή Ερενίδη 12 Ιουνίου στις 13:30")); mMap.addMarker(new MarkerOptions().position(acropol).title("ΑΚΡΟΠΟΛΙΣ ΑΘΗΝΩΝ").snippet("Ξενάγηση με τον καθηγητή κ. Χαραλαμπόπουλο 20 Μαΐου στις 11:00 πμ ")); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation,zoomLevel)); } }
avlonitiss/EasyCity
app/src/main/java/org/rome/easycity/EasyCityMapsActivity.java
787
// Προσδιορισμός εκδηλώσεων από backend
line_comment
el
package org.rome.easycity; import androidx.fragment.app.FragmentActivity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class EasyCityMapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_easy_city_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Προσδιορισμός εκδηλώσεων<SUF> float zoomLevel = (float) 13.0; LatLng myLocation = new LatLng(37.98, 23.72); LatLng museum = new LatLng(37.989, 23.732); LatLng acropol = new LatLng(37.971, 23.725); mMap.addMarker(new MarkerOptions().position(myLocation).title("Είμαι εδώ")); mMap.addMarker(new MarkerOptions().position(museum).title("ΕΘΝΙΚΟ ΑΡΧΑΙΟΛΟΓΙΚΟ ΜΟΥΣΕΙΟ").snippet("Ομιλία του καθηγητή Ερενίδη 12 Ιουνίου στις 13:30")); mMap.addMarker(new MarkerOptions().position(acropol).title("ΑΚΡΟΠΟΛΙΣ ΑΘΗΝΩΝ").snippet("Ξενάγηση με τον καθηγητή κ. Χαραλαμπόπουλο 20 Μαΐου στις 11:00 πμ ")); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation,zoomLevel)); } }
5144_2
/* * 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 iek.agdimitr.associationsdemo; /** * * @author User */ import java.util.Vector; public class Xenodoxeio { private String epwnymia; private Vector <Ypallilos> proswpiko; // πίνακας-αναφορά public Xenodoxeio(String epwnymia) { this.epwnymia = epwnymia; //Αρχικοποιούμε το vector proswpiko = new Vector<Ypallilos>(); } public void addYpallilos(Ypallilos yp) { // AGGREGAION: προσθέτουμε τους Υπαλλήλους proswpiko.add(yp); } public String getEpwnymia() { return epwnymia; } public void printProswpiko() { System.out.println("\nTa proswpiko tou Xenodoxeiou"); if ( proswpiko.isEmpty() ) System.out.println( "Μήνυμα λάθους." ); else for ( Ypallilos element : proswpiko ) System.out.printf( "%s\n", element.toString() ); } }
avlonitiss/JavaAssociationsDemo
src/main/java/iek/agdimitr/associationsdemo/Xenodoxeio.java
391
//Αρχικοποιούμε το vector
line_comment
el
/* * 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 iek.agdimitr.associationsdemo; /** * * @author User */ import java.util.Vector; public class Xenodoxeio { private String epwnymia; private Vector <Ypallilos> proswpiko; // πίνακας-αναφορά public Xenodoxeio(String epwnymia) { this.epwnymia = epwnymia; //Αρχικοποιούμε το<SUF> proswpiko = new Vector<Ypallilos>(); } public void addYpallilos(Ypallilos yp) { // AGGREGAION: προσθέτουμε τους Υπαλλήλους proswpiko.add(yp); } public String getEpwnymia() { return epwnymia; } public void printProswpiko() { System.out.println("\nTa proswpiko tou Xenodoxeiou"); if ( proswpiko.isEmpty() ) System.out.println( "Μήνυμα λάθους." ); else for ( Ypallilos element : proswpiko ) System.out.printf( "%s\n", element.toString() ); } }
6146_5
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template */ package com.iek.javaarraylistlesson; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * * @author Spyros */ public class ArrayListLesson { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here ArrayList<List> complexArray = new ArrayList<>(); // προσθήκη εγγραφών στοιχείων διαφορετικών data types στη λίστα complexArray.add(Arrays.asList("Costas",15,34.12)); //εδώ προστέθηκε μια εγγραφή με τρία διαφορετικά data types σε μία εγγραφή //(String, int, double) complexArray.add(Arrays.asList("Giannis",14,30.35)); //εδώ προστέθηκε μια εγγγραφή με τρία διαφορετικά data types σε μία εγγραφή //(String, double, int) διαφιρετικά από την προηγούμενη εγγραφή complexArray.add(Arrays.asList("Elenh",15,32.20)); //εδώ προστέθηκαν μία εγγραφή με ένα data type σε μία εγγραφή //Τροποποίηση εκτύπωσης με απόκρυψη βάρους System.out.println("Name, Age"); for (List myRecords : complexArray) { System.out.println( myRecords.get(0)+" "+myRecords.get(1)); } //Αναζήτηση βάρους με Input το όνομα Scanner myKeyboard = new Scanner(System.in); System.out.println("Enter name to find weight"); String name=myKeyboard.nextLine(); System.out.println("I'm searchnig "+name+" weight"); complexArray.forEach(arrayName->{ if(arrayName.get(0).equals(name)){ System.out.println("I found the person..."); System.out.println(name+" is weighting "+arrayName.get(2)+" Kg"); System.exit(0); }else { System.out.println("This person isn't found yet"); } }); } }
avlonitiss/javaArrayListLesson
src/main/java/com/iek/javaarraylistlesson/ArrayListLesson.java
762
//εδώ προστέθηκε μια εγγραφή με τρία διαφορετικά data types σε μία εγγραφή
line_comment
el
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template */ package com.iek.javaarraylistlesson; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * * @author Spyros */ public class ArrayListLesson { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here ArrayList<List> complexArray = new ArrayList<>(); // προσθήκη εγγραφών στοιχείων διαφορετικών data types στη λίστα complexArray.add(Arrays.asList("Costas",15,34.12)); //εδώ προστέθηκε<SUF> //(String, int, double) complexArray.add(Arrays.asList("Giannis",14,30.35)); //εδώ προστέθηκε μια εγγγραφή με τρία διαφορετικά data types σε μία εγγραφή //(String, double, int) διαφιρετικά από την προηγούμενη εγγραφή complexArray.add(Arrays.asList("Elenh",15,32.20)); //εδώ προστέθηκαν μία εγγραφή με ένα data type σε μία εγγραφή //Τροποποίηση εκτύπωσης με απόκρυψη βάρους System.out.println("Name, Age"); for (List myRecords : complexArray) { System.out.println( myRecords.get(0)+" "+myRecords.get(1)); } //Αναζήτηση βάρους με Input το όνομα Scanner myKeyboard = new Scanner(System.in); System.out.println("Enter name to find weight"); String name=myKeyboard.nextLine(); System.out.println("I'm searchnig "+name+" weight"); complexArray.forEach(arrayName->{ if(arrayName.get(0).equals(name)){ System.out.println("I found the person..."); System.out.println(name+" is weighting "+arrayName.get(2)+" Kg"); System.exit(0); }else { System.out.println("This person isn't found yet"); } }); } }
4290_2
package com.frontis.methuselah.methuselah_sdy51; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.shiva.try1.R; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; /** * Άρχικός κώδικας by shiva on 31-01-2018. * Τροποποιήθηκε από την ομάδα Αυλωνίτης - Ερενίδης Χαραλαμπόπουλος για την 5η ΓΕ της ΣΔΥ51 */ public class login extends AppCompatActivity { EditText Email, Password; Button LogInButton, RegisterButton; FirebaseAuth mAuth; FirebaseAuth.AuthStateListener mAuthListner; FirebaseUser mUser; String email, password; ProgressDialog dialog; public static final String userEmail=""; public static final String TAG="LOGIN"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LogInButton = (Button) findViewById(R.id.buttonLogin); RegisterButton = (Button) findViewById(R.id.buttonRegister); Email = (EditText) findViewById(R.id.editEmail); Password = (EditText) findViewById(R.id.editPassword); dialog = new ProgressDialog(this); mAuth = FirebaseAuth.getInstance(); mUser = FirebaseAuth.getInstance().getCurrentUser(); mAuthListner = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { if (mUser != null) { Intent intent = new Intent(login.this, DashboardActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else { Log.d(TAG,"AuthStateChanged:Logout"); } } }; LogInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Έλεγχος άδειου EditText. userSign(); } }); RegisterButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // για νέο χρήστη εκκίνηση registration activity . Intent intent = new Intent(login.this, Register.class); startActivity(intent); } }); } @Override protected void onStart() { super.onStart(); //τερματισμός του listener στο logout. mAuth.removeAuthStateListener(mAuthListner); } @Override protected void onStop() { super.onStop(); if (mAuthListner != null) { mAuth.removeAuthStateListener(mAuthListner); } } @Override public void onBackPressed() { login.super.finish(); } private void userSign() { email = Email.getText().toString().trim(); password = Password.getText().toString().trim(); if (TextUtils.isEmpty(email)) { Toast.makeText(login.this, "Γράψτε το σωστό Email", Toast.LENGTH_SHORT).show(); return; } else if (TextUtils.isEmpty(password)) { Toast.makeText(login.this, "Γράψτε το σωστό password", Toast.LENGTH_SHORT).show(); return; } dialog.setMessage("Συνδέεται..."); dialog.setIndeterminate(true); dialog.show(); mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (!task.isSuccessful()) { dialog.dismiss(); Toast.makeText(login.this, "Αποτυχία σύνδεσης", Toast.LENGTH_SHORT).show(); } else { dialog.dismiss(); checkIfEmailVerified(); } } }); } //Έλεγχος επιβεβαίωσης email. private void checkIfEmailVerified(){ FirebaseUser users=FirebaseAuth.getInstance().getCurrentUser(); boolean emailVerified=users.isEmailVerified(); if(!emailVerified){ Toast.makeText(this,"Επιβεβαίωση Email Id",Toast.LENGTH_SHORT).show(); mAuth.signOut(); finish(); } else { Email.getText().clear(); Password.getText().clear(); Intent intent = new Intent(login.this, DashboardActivity.class); // Αποστολή email. intent.putExtra(userEmail,email); startActivity(intent); } } }
avlonitiss/methuselah_firebase_login
app/src/main/java/com/frontis/methuselah/methuselah_sdy51/login.java
1,330
// για νέο χρήστη εκκίνηση registration activity .
line_comment
el
package com.frontis.methuselah.methuselah_sdy51; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.shiva.try1.R; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; /** * Άρχικός κώδικας by shiva on 31-01-2018. * Τροποποιήθηκε από την ομάδα Αυλωνίτης - Ερενίδης Χαραλαμπόπουλος για την 5η ΓΕ της ΣΔΥ51 */ public class login extends AppCompatActivity { EditText Email, Password; Button LogInButton, RegisterButton; FirebaseAuth mAuth; FirebaseAuth.AuthStateListener mAuthListner; FirebaseUser mUser; String email, password; ProgressDialog dialog; public static final String userEmail=""; public static final String TAG="LOGIN"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LogInButton = (Button) findViewById(R.id.buttonLogin); RegisterButton = (Button) findViewById(R.id.buttonRegister); Email = (EditText) findViewById(R.id.editEmail); Password = (EditText) findViewById(R.id.editPassword); dialog = new ProgressDialog(this); mAuth = FirebaseAuth.getInstance(); mUser = FirebaseAuth.getInstance().getCurrentUser(); mAuthListner = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { if (mUser != null) { Intent intent = new Intent(login.this, DashboardActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else { Log.d(TAG,"AuthStateChanged:Logout"); } } }; LogInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Έλεγχος άδειου EditText. userSign(); } }); RegisterButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // για νέο<SUF> Intent intent = new Intent(login.this, Register.class); startActivity(intent); } }); } @Override protected void onStart() { super.onStart(); //τερματισμός του listener στο logout. mAuth.removeAuthStateListener(mAuthListner); } @Override protected void onStop() { super.onStop(); if (mAuthListner != null) { mAuth.removeAuthStateListener(mAuthListner); } } @Override public void onBackPressed() { login.super.finish(); } private void userSign() { email = Email.getText().toString().trim(); password = Password.getText().toString().trim(); if (TextUtils.isEmpty(email)) { Toast.makeText(login.this, "Γράψτε το σωστό Email", Toast.LENGTH_SHORT).show(); return; } else if (TextUtils.isEmpty(password)) { Toast.makeText(login.this, "Γράψτε το σωστό password", Toast.LENGTH_SHORT).show(); return; } dialog.setMessage("Συνδέεται..."); dialog.setIndeterminate(true); dialog.show(); mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (!task.isSuccessful()) { dialog.dismiss(); Toast.makeText(login.this, "Αποτυχία σύνδεσης", Toast.LENGTH_SHORT).show(); } else { dialog.dismiss(); checkIfEmailVerified(); } } }); } //Έλεγχος επιβεβαίωσης email. private void checkIfEmailVerified(){ FirebaseUser users=FirebaseAuth.getInstance().getCurrentUser(); boolean emailVerified=users.isEmailVerified(); if(!emailVerified){ Toast.makeText(this,"Επιβεβαίωση Email Id",Toast.LENGTH_SHORT).show(); mAuth.signOut(); finish(); } else { Email.getText().clear(); Password.getText().clear(); Intent intent = new Intent(login.this, DashboardActivity.class); // Αποστολή email. intent.putExtra(userEmail,email); startActivity(intent); } } }
33569_0
/* * INSECTFileDB.java * * Created on 27 Ιανουάριος 2006, 9:16 μμ * */ package gr.demokritos.iit.jinsect.storage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** A file database that uses a single file per stored object. * * @author PCKid */ public class INSECTFileDB<TObjectType extends Serializable> extends INSECTDB implements Serializable { private String Prefix; private String BaseDir; public INSECTFileDB() { this(null, null); } /** Creates a new instance of INSECTFileDB */ public INSECTFileDB(String sPrefix, String sBaseDir) { if (sPrefix == null) Prefix = ""; else Prefix = sPrefix; if (sBaseDir == null) BaseDir = "./"; else BaseDir = sBaseDir; } /** Returns the filename of the corresponding object of a given category. * * @param sObjectName The name of the object. * @param sObjectCategory The category of the object. * @return A string representing the filename of the object in the db. */ public String getFileName(String sObjectName, String sObjectCategory) { return BaseDir + System.getProperty("file.separator") + Prefix + String.valueOf((sObjectName).hashCode()) + '.' + sObjectCategory; } @Override public void saveObject(Serializable oObj, String sObjectName, String sObjectCategory) { try { FileOutputStream fsOut = new FileOutputStream(getFileName(sObjectName, sObjectCategory)); GZIPOutputStream gzout = new GZIPOutputStream(fsOut); ObjectOutputStream oOut = new ObjectOutputStream(gzout); oOut.writeObject(oObj); oOut.close(); // Complete the GZIP file gzout.finish(); fsOut.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public TObjectType loadObject(String sObjectName, String sObjectCategory) { FileInputStream fsIn = null; GZIPInputStream gzIn = null; ObjectInputStream iIn = null; try { fsIn = new FileInputStream(getFileName(sObjectName, sObjectCategory)); gzIn = new GZIPInputStream(fsIn); iIn = new ObjectInputStream(gzIn); } catch (Exception e) { e.printStackTrace(); return null; } Object oRes; try { oRes = iIn.readObject(); } catch (Exception e) { e.printStackTrace(); return null; } try { fsIn.close(); gzIn.close(); iIn.close(); } catch (IOException ex) { ex.printStackTrace(); } return (TObjectType)oRes; } @Override public void deleteObject(String sObjectName, String sObjectCategory) { if (existsObject(sObjectName, sObjectCategory)) { // Delete File File f = new File(getFileName(sObjectName, sObjectCategory)); f.delete(); // Might fail. No testing. } } @Override public boolean existsObject(String sObjectName, String sObjectCategory) { /* OBSOLETE: FileInputStream fi; try { fi = new FileInputStream(getFileName(sObjectName, sObjectCategory)); fi.close(); } catch (FileNotFoundException e) { return false; } catch (IOException ioe) { ioe.printStackTrace(); return false; } return true; */ return new File(getFileName(sObjectName, sObjectCategory)).exists(); } @Override public String[] getObjectList(String sObjectCategory) { File dDir = new File(BaseDir); ObjectTypeFileFilter f = new ObjectTypeFileFilter(sObjectCategory); String[] sFiles = dDir.list(f); for (int iCnt = 0; iCnt < sFiles.length; iCnt++) { // Remove category type suffix (.CATEGORYNAME) from name sFiles[iCnt] = sFiles[iCnt].substring(Prefix.length(), sFiles[iCnt].length() - (sObjectCategory.length() + 1)); } // Return actual object names return sFiles; } @Override public String getObjDataToString(Object oObject) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream os = new ObjectOutputStream(bos); os.writeObject(oObject); } catch (IOException e) { e.printStackTrace(); return null; // Failed } return bos.toString(); } @Override public TObjectType getStringToObjData(String sData) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream bos = new ObjectOutputStream(baos); bos.writeBytes(sData); } catch (IOException e) { e.printStackTrace(); return null; // Failed } ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois; Object oRes; try { ois = new ObjectInputStream(bin); oRes = ois.readObject(); } catch (IOException e) { e.printStackTrace(); return null; // Failed } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); return null; // Class not found } return (TObjectType)oRes; } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.defaultWriteObject(); } } class ObjectTypeFileFilter implements FilenameFilter { private String ObjectCategory; public ObjectTypeFileFilter(String sCategory) { ObjectCategory = sCategory; } @Override public boolean accept(File pathname, String sName) { return (sName.matches(".*\\Q." + ObjectCategory + "\\E")); } }
ayushoriginal/Ngram-Graphs
gr/demokritos/iit/jinsect/storage/INSECTFileDB.java
1,490
/* * INSECTFileDB.java * * Created on 27 Ιανουάριος 2006, 9:16 μμ * */
block_comment
el
/* * INSECTFileDB.java *<SUF>*/ package gr.demokritos.iit.jinsect.storage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** A file database that uses a single file per stored object. * * @author PCKid */ public class INSECTFileDB<TObjectType extends Serializable> extends INSECTDB implements Serializable { private String Prefix; private String BaseDir; public INSECTFileDB() { this(null, null); } /** Creates a new instance of INSECTFileDB */ public INSECTFileDB(String sPrefix, String sBaseDir) { if (sPrefix == null) Prefix = ""; else Prefix = sPrefix; if (sBaseDir == null) BaseDir = "./"; else BaseDir = sBaseDir; } /** Returns the filename of the corresponding object of a given category. * * @param sObjectName The name of the object. * @param sObjectCategory The category of the object. * @return A string representing the filename of the object in the db. */ public String getFileName(String sObjectName, String sObjectCategory) { return BaseDir + System.getProperty("file.separator") + Prefix + String.valueOf((sObjectName).hashCode()) + '.' + sObjectCategory; } @Override public void saveObject(Serializable oObj, String sObjectName, String sObjectCategory) { try { FileOutputStream fsOut = new FileOutputStream(getFileName(sObjectName, sObjectCategory)); GZIPOutputStream gzout = new GZIPOutputStream(fsOut); ObjectOutputStream oOut = new ObjectOutputStream(gzout); oOut.writeObject(oObj); oOut.close(); // Complete the GZIP file gzout.finish(); fsOut.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public TObjectType loadObject(String sObjectName, String sObjectCategory) { FileInputStream fsIn = null; GZIPInputStream gzIn = null; ObjectInputStream iIn = null; try { fsIn = new FileInputStream(getFileName(sObjectName, sObjectCategory)); gzIn = new GZIPInputStream(fsIn); iIn = new ObjectInputStream(gzIn); } catch (Exception e) { e.printStackTrace(); return null; } Object oRes; try { oRes = iIn.readObject(); } catch (Exception e) { e.printStackTrace(); return null; } try { fsIn.close(); gzIn.close(); iIn.close(); } catch (IOException ex) { ex.printStackTrace(); } return (TObjectType)oRes; } @Override public void deleteObject(String sObjectName, String sObjectCategory) { if (existsObject(sObjectName, sObjectCategory)) { // Delete File File f = new File(getFileName(sObjectName, sObjectCategory)); f.delete(); // Might fail. No testing. } } @Override public boolean existsObject(String sObjectName, String sObjectCategory) { /* OBSOLETE: FileInputStream fi; try { fi = new FileInputStream(getFileName(sObjectName, sObjectCategory)); fi.close(); } catch (FileNotFoundException e) { return false; } catch (IOException ioe) { ioe.printStackTrace(); return false; } return true; */ return new File(getFileName(sObjectName, sObjectCategory)).exists(); } @Override public String[] getObjectList(String sObjectCategory) { File dDir = new File(BaseDir); ObjectTypeFileFilter f = new ObjectTypeFileFilter(sObjectCategory); String[] sFiles = dDir.list(f); for (int iCnt = 0; iCnt < sFiles.length; iCnt++) { // Remove category type suffix (.CATEGORYNAME) from name sFiles[iCnt] = sFiles[iCnt].substring(Prefix.length(), sFiles[iCnt].length() - (sObjectCategory.length() + 1)); } // Return actual object names return sFiles; } @Override public String getObjDataToString(Object oObject) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream os = new ObjectOutputStream(bos); os.writeObject(oObject); } catch (IOException e) { e.printStackTrace(); return null; // Failed } return bos.toString(); } @Override public TObjectType getStringToObjData(String sData) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream bos = new ObjectOutputStream(baos); bos.writeBytes(sData); } catch (IOException e) { e.printStackTrace(); return null; // Failed } ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois; Object oRes; try { ois = new ObjectInputStream(bin); oRes = ois.readObject(); } catch (IOException e) { e.printStackTrace(); return null; // Failed } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); return null; // Class not found } return (TObjectType)oRes; } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.defaultWriteObject(); } } class ObjectTypeFileFilter implements FilenameFilter { private String ObjectCategory; public ObjectTypeFileFilter(String sCategory) { ObjectCategory = sCategory; } @Override public boolean accept(File pathname, String sName) { return (sName.matches(".*\\Q." + ObjectCategory + "\\E")); } }
1792_32
import java.util.*; public class Node { private LinkedList<Packet> queue; // the node's buffer private Set<Integer> T; // channels the node can transmit to private Set<Integer> R; // channels the node can receive from private ArrayList<ArrayList<Integer>> A; private ArrayList<ArrayList<Integer>> B; private Random rand; // random number generator private int bufferSize; // node's capacity of packets private double l; // packet generation probability private double[] d; // destination probabilities private int id; private int transmitted; private int buffered; private int slotsWaited; public Node(int id, int configuration, long seed){ queue = new LinkedList<>(); T = new HashSet<>(); R = new HashSet<>(); rand = new Random(seed); this.id = id; d = new double[Main.getNumberOfNodes()+1]; configure(id, configuration); } private void configure(int id, int configuration){ // Configure Node's transmission range and receivers. switch (configuration){ case 1: // system configuration 1 // each transmitter can be tuned to two wavelengths // each node has two receivers // configure the transmission range if (id==1 || id==2 || id==3){ T.add(1); T.add(2); } else if (id==4 || id==5 || id==6){ T.add(2); T.add(3); } else if (id==7 || id==8){ T.add(3); T.add(4); } // configure the receivers if (id==1){ R.add(2); R.add(3); } else if (id==2 || id==3 || id==5 || id==7){ R.add(2); R.add(4); } else if (id==4 || id==6 || id==8){ R.add(1); R.add(3); } break; case 2: // system configuration 2 // each transmitter can be tuned to one wavelength // each node has four receivers, one for each wavelength // configure the transmission range if (id==1 || id==2){ T.add(1); } else if (id==3 || id==4){ T.add(2); } else if (id==5 || id ==6){ T.add(3); } else if (id==7 || id==8){ T.add(4); } // configure the receivers R.add(1); R.add(2); R.add(3); R.add(4); break; case 3: // system configuration 3 // each transmitter can be tuned to all four wavelengths // each node has one receiver // configure the transmission range T.add(1); T.add(2); T.add(3); T.add(4); // configure the receivers if (id==1 || id==2){ R.add(1); } else if (id==3 || id==4){ R.add(2); } else if (id==5 || id==6){ R.add(3); } else if (id==7 || id==8){ R.add(4); } break; } } public void slotAction(int slot){ //////////////////// // PACKET ARRIVAL // //////////////////// boolean arrives = rand.nextDouble() < l; if (arrives && queue.size() < bufferSize){ int destination = findDestination(); if (destination==-1){ System.exit(5); } queue.add(new Packet(destination, slot)); } ////////////////////////// // Creating trans table // ////////////////////////// // Initialize the trans table int[] trans = new int[Main.getNumberOfNodes() + 1]; for (int i = 1; i <= Main.getNumberOfNodes(); i++) { trans[i] = 0; } // initialize channels ( Ω ) ArrayList<Integer> channels = new ArrayList<>(); for (int channel = 1; channel <= Main.getNumberOfChannels(); channel++) { channels.add(channel); } // get a copy of A ArrayList<ArrayList<Integer>> _A = new ArrayList<>(); for (int i = 0; i < A.size(); i++) { _A.add((ArrayList<Integer>) A.get(i).clone()); } // create trans table while (!channels.isEmpty()) { int k = channels.get(rand.nextInt(channels.size())); // get a random channel, say channel k int i = _A.get(k).get(rand.nextInt(_A.get(k).size())); // get a random node from _A[k], say node i trans[i] = k; // remove i from _A for (int j = 1; j < _A.size(); j++) { _A.get(j).remove((Integer) i); } // remove k from channels (Ω) channels.remove((Integer) k); } buffered += queue.size(); ////////////////// // TRANSMISSION // ////////////////// if (trans[id] != 0) { int channel = trans[id]; for (Packet packet : queue) { // αν ο κόμβος του destination του <packet> έχει receiver στο <channel> κάνε το transmission int destination = packet.destination; if (B.get(channel).contains(destination)){ // do the transmission slotsWaited += slot - packet.timeslot; queue.remove(packet); transmitted++; break; } } } } private int findDestination() { double p = Math.random(); double cumulativeProbability = 0.0; for (int m=0; m<d.length; m++){ cumulativeProbability += d[m]; if (p <= cumulativeProbability){ return m; } } return -1; } public void reset(double systemLoad){ // changes l, resets the counters, and clears the queue if (Main.getValidation()){ l = id * systemLoad / 36; } else { l = systemLoad / Main.getNumberOfNodes(); } transmitted = 0; buffered = 0; slotsWaited = 0; queue.clear(); } public void setD(boolean validation){ int N = Main.getNumberOfNodes(); if (validation){ for (int m=1; m<=N; m++){ if (m==id){ d[m] = 0; } else { d[m] = (double) m / (N*(N+1)/2 - id); } } } else { for (int m=1; m<=N; m++){ if (m==id){ d[m] = 0; } else { d[m] = (double) 1 / (N-1); } } } } public void setBufferSize(boolean validation){ if (validation){ bufferSize = id; } else { bufferSize = 4; } } public void setA(ArrayList<ArrayList<Integer>> A) { this.A = A; } public void setB(ArrayList<ArrayList<Integer>> B) { this.B = B; } public Set<Integer> getT() { return T; } public Set<Integer> getR() { return R; } public int getTransmitted(){ return transmitted; } public int getBuffered(){ return buffered; } public int getSlotsWaited(){ return slotsWaited; } }
b1ru/rtdma
src/Node.java
1,798
// αν ο κόμβος του destination του <packet> έχει receiver στο <channel> κάνε το transmission
line_comment
el
import java.util.*; public class Node { private LinkedList<Packet> queue; // the node's buffer private Set<Integer> T; // channels the node can transmit to private Set<Integer> R; // channels the node can receive from private ArrayList<ArrayList<Integer>> A; private ArrayList<ArrayList<Integer>> B; private Random rand; // random number generator private int bufferSize; // node's capacity of packets private double l; // packet generation probability private double[] d; // destination probabilities private int id; private int transmitted; private int buffered; private int slotsWaited; public Node(int id, int configuration, long seed){ queue = new LinkedList<>(); T = new HashSet<>(); R = new HashSet<>(); rand = new Random(seed); this.id = id; d = new double[Main.getNumberOfNodes()+1]; configure(id, configuration); } private void configure(int id, int configuration){ // Configure Node's transmission range and receivers. switch (configuration){ case 1: // system configuration 1 // each transmitter can be tuned to two wavelengths // each node has two receivers // configure the transmission range if (id==1 || id==2 || id==3){ T.add(1); T.add(2); } else if (id==4 || id==5 || id==6){ T.add(2); T.add(3); } else if (id==7 || id==8){ T.add(3); T.add(4); } // configure the receivers if (id==1){ R.add(2); R.add(3); } else if (id==2 || id==3 || id==5 || id==7){ R.add(2); R.add(4); } else if (id==4 || id==6 || id==8){ R.add(1); R.add(3); } break; case 2: // system configuration 2 // each transmitter can be tuned to one wavelength // each node has four receivers, one for each wavelength // configure the transmission range if (id==1 || id==2){ T.add(1); } else if (id==3 || id==4){ T.add(2); } else if (id==5 || id ==6){ T.add(3); } else if (id==7 || id==8){ T.add(4); } // configure the receivers R.add(1); R.add(2); R.add(3); R.add(4); break; case 3: // system configuration 3 // each transmitter can be tuned to all four wavelengths // each node has one receiver // configure the transmission range T.add(1); T.add(2); T.add(3); T.add(4); // configure the receivers if (id==1 || id==2){ R.add(1); } else if (id==3 || id==4){ R.add(2); } else if (id==5 || id==6){ R.add(3); } else if (id==7 || id==8){ R.add(4); } break; } } public void slotAction(int slot){ //////////////////// // PACKET ARRIVAL // //////////////////// boolean arrives = rand.nextDouble() < l; if (arrives && queue.size() < bufferSize){ int destination = findDestination(); if (destination==-1){ System.exit(5); } queue.add(new Packet(destination, slot)); } ////////////////////////// // Creating trans table // ////////////////////////// // Initialize the trans table int[] trans = new int[Main.getNumberOfNodes() + 1]; for (int i = 1; i <= Main.getNumberOfNodes(); i++) { trans[i] = 0; } // initialize channels ( Ω ) ArrayList<Integer> channels = new ArrayList<>(); for (int channel = 1; channel <= Main.getNumberOfChannels(); channel++) { channels.add(channel); } // get a copy of A ArrayList<ArrayList<Integer>> _A = new ArrayList<>(); for (int i = 0; i < A.size(); i++) { _A.add((ArrayList<Integer>) A.get(i).clone()); } // create trans table while (!channels.isEmpty()) { int k = channels.get(rand.nextInt(channels.size())); // get a random channel, say channel k int i = _A.get(k).get(rand.nextInt(_A.get(k).size())); // get a random node from _A[k], say node i trans[i] = k; // remove i from _A for (int j = 1; j < _A.size(); j++) { _A.get(j).remove((Integer) i); } // remove k from channels (Ω) channels.remove((Integer) k); } buffered += queue.size(); ////////////////// // TRANSMISSION // ////////////////// if (trans[id] != 0) { int channel = trans[id]; for (Packet packet : queue) { // αν ο<SUF> int destination = packet.destination; if (B.get(channel).contains(destination)){ // do the transmission slotsWaited += slot - packet.timeslot; queue.remove(packet); transmitted++; break; } } } } private int findDestination() { double p = Math.random(); double cumulativeProbability = 0.0; for (int m=0; m<d.length; m++){ cumulativeProbability += d[m]; if (p <= cumulativeProbability){ return m; } } return -1; } public void reset(double systemLoad){ // changes l, resets the counters, and clears the queue if (Main.getValidation()){ l = id * systemLoad / 36; } else { l = systemLoad / Main.getNumberOfNodes(); } transmitted = 0; buffered = 0; slotsWaited = 0; queue.clear(); } public void setD(boolean validation){ int N = Main.getNumberOfNodes(); if (validation){ for (int m=1; m<=N; m++){ if (m==id){ d[m] = 0; } else { d[m] = (double) m / (N*(N+1)/2 - id); } } } else { for (int m=1; m<=N; m++){ if (m==id){ d[m] = 0; } else { d[m] = (double) 1 / (N-1); } } } } public void setBufferSize(boolean validation){ if (validation){ bufferSize = id; } else { bufferSize = 4; } } public void setA(ArrayList<ArrayList<Integer>> A) { this.A = A; } public void setB(ArrayList<ArrayList<Integer>> B) { this.B = B; } public Set<Integer> getT() { return T; } public Set<Integer> getR() { return R; } public int getTransmitted(){ return transmitted; } public int getBuffered(){ return buffered; } public int getSlotsWaited(){ return slotsWaited; } }
24842_2
/* * 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 askisi2; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author Μπαλτατζίδης Χαράλαμπος */ public class StudentDao { public static Connection getConnection() { //method για συνδεση με ΒΔ Connection conn = null; try { Class.forName("org.mariadb.jdbc.Driver"); //χρησημοποιω JDBC Driver mariaDB v2.7.1 conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/askisi1_db", "baltatzidis", "1234"); } catch (ClassNotFoundException | SQLException ex) { } return conn; } public static Student getStudent(String lname) { //βρες student με αντισοιχο lname Student student = new Student(); Connection conn = StudentDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("SELECT * FROM students WHERE Lastname=?"); ps.setString(1, lname); ResultSet rs = ps.executeQuery(); if (rs.next()) { student.setFname(rs.getString(1)); student.setLname(rs.getString(2)); student.setSchool(rs.getString(3)); student.setSchool(rs.getString(4)); student.setSemester(rs.getInt(5)); student.setPassedSubj(rs.getInt(6)); } conn.close(); } catch (SQLException ex) { } return student; } public static int createStudent(Student student) { //δημιουργησε νεο entry στο database int status = 0; Connection conn = StudentDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("INSERT INTO students VALUES (?,?,?,?,?)"); ps.setString(1, student.getFname()); ps.setString(2, student.getLname()); ps.setString(3, student.getSchool()); ps.setInt(4, student.getSemester()); ps.setInt(5, student.getPassedSubj()); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } }
babis200/Askisi2-NetProg-UNIWA-Project-on-JAVA-Sockets
src/askisi2/StudentDao.java
619
//method για συνδεση με ΒΔ
line_comment
el
/* * 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 askisi2; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author Μπαλτατζίδης Χαράλαμπος */ public class StudentDao { public static Connection getConnection() { //method για<SUF> Connection conn = null; try { Class.forName("org.mariadb.jdbc.Driver"); //χρησημοποιω JDBC Driver mariaDB v2.7.1 conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/askisi1_db", "baltatzidis", "1234"); } catch (ClassNotFoundException | SQLException ex) { } return conn; } public static Student getStudent(String lname) { //βρες student με αντισοιχο lname Student student = new Student(); Connection conn = StudentDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("SELECT * FROM students WHERE Lastname=?"); ps.setString(1, lname); ResultSet rs = ps.executeQuery(); if (rs.next()) { student.setFname(rs.getString(1)); student.setLname(rs.getString(2)); student.setSchool(rs.getString(3)); student.setSchool(rs.getString(4)); student.setSemester(rs.getInt(5)); student.setPassedSubj(rs.getInt(6)); } conn.close(); } catch (SQLException ex) { } return student; } public static int createStudent(Student student) { //δημιουργησε νεο entry στο database int status = 0; Connection conn = StudentDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("INSERT INTO students VALUES (?,?,?,?,?)"); ps.setString(1, student.getFname()); ps.setString(2, student.getLname()); ps.setString(3, student.getSchool()); ps.setInt(4, student.getSemester()); ps.setInt(5, student.getPassedSubj()); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } }
24853_6
package gr.uniwa.bookshop.servlets; import gr.uniwa.bookshop.database.BookDao; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Μπαλτατζίδης Χαράλαμπος */ public class DeleteServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); String sid = request.getParameter("id"); int id = Integer.parseInt(sid); //δεχομαι id και το μετατρεπω απο String σε int int status = BookDao.deleteById(id); //delete το βιβλιο με αντισtοιχο id status==1 αν επιτυχω try (PrintWriter out = response.getWriter()) { //τυπωνω μυνημα για τα αποτελεσματα out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.print("<style>h1 {text-align: center;} .center { margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }</style>"); out.println("<title>Delete</title>"); out.println("</head>"); out.println("<body>"); out.print("<div class=\"center\">\n"); if (status != 0) { out.print("<h1>Book deleted<h1>"); } else { out.print("<h1>Delete Failed<h1>"); } out.println("<a href='index.html'>Main Menu</a>\n"); out.print("</div>"); out.println("</body>"); out.println("</html>"); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); String sid = request.getParameter("id"); int id = Integer.parseInt(sid); //δεχομαι id και το μετατρεπω απο String σε int int status = BookDao.deleteById(id); //delete το βιβλιο με αντισtοιχο id status==1 αν επιτυχω try (PrintWriter out = response.getWriter()) { //τυπωνω μυνημα για τα αποτελεσματα out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.print("<style>h1 {text-align: center;} .center { margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }</style>"); out.println("<title>Delete</title>"); out.println("</head>"); out.println("<body>"); out.print("<div class=\"center\">\n"); if (status != 0) { out.print("<h1>Book deleted<h1>"); } else { out.print("<h1>Delete Failed<h1>"); } out.println("<a href='index.html'>Main Menu</a>\n"); out.print("</div>"); out.println("</body>"); out.println("</html>"); } } @Override public String getServletInfo() { return "Short description"; } }
babis200/Bookshop
src/java/gr/uniwa/bookshop/servlets/DeleteServlet.java
958
//τυπωνω μυνημα για τα αποτελεσματα
line_comment
el
package gr.uniwa.bookshop.servlets; import gr.uniwa.bookshop.database.BookDao; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Μπαλτατζίδης Χαράλαμπος */ public class DeleteServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); String sid = request.getParameter("id"); int id = Integer.parseInt(sid); //δεχομαι id και το μετατρεπω απο String σε int int status = BookDao.deleteById(id); //delete το βιβλιο με αντισtοιχο id status==1 αν επιτυχω try (PrintWriter out = response.getWriter()) { //τυπωνω μυνημα για τα αποτελεσματα out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.print("<style>h1 {text-align: center;} .center { margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }</style>"); out.println("<title>Delete</title>"); out.println("</head>"); out.println("<body>"); out.print("<div class=\"center\">\n"); if (status != 0) { out.print("<h1>Book deleted<h1>"); } else { out.print("<h1>Delete Failed<h1>"); } out.println("<a href='index.html'>Main Menu</a>\n"); out.print("</div>"); out.println("</body>"); out.println("</html>"); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); String sid = request.getParameter("id"); int id = Integer.parseInt(sid); //δεχομαι id και το μετατρεπω απο String σε int int status = BookDao.deleteById(id); //delete το βιβλιο με αντισtοιχο id status==1 αν επιτυχω try (PrintWriter out = response.getWriter()) { //τυπωνω μυνημα<SUF> out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.print("<style>h1 {text-align: center;} .center { margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }</style>"); out.println("<title>Delete</title>"); out.println("</head>"); out.println("<body>"); out.print("<div class=\"center\">\n"); if (status != 0) { out.print("<h1>Book deleted<h1>"); } else { out.print("<h1>Delete Failed<h1>"); } out.println("<a href='index.html'>Main Menu</a>\n"); out.print("</div>"); out.println("</body>"); out.println("</html>"); } } @Override public String getServletInfo() { return "Short description"; } }
11998_0
package Controllers; import api.*; import java.io.*; import java.util.ArrayList; // Η κλάση αυτή έχει όλες τις λειτουργίες για τη διαχείριση των αρχείων του προγράμματος. // Εμπεριέχει τα ονόματα των αρχείων που αποθηκεύονται τα δεδομένα και όλες τις συναρτήσεις για γράψιμο/διάβασμα αυτών των δεδομένων. public class FileController { // File Variables private static final String moviesFilename = "movies.ser"; private static final String seriesFilename = "series.ser"; private static final String usersFilename = "users.ser"; // Function to write Movie objects to a file public static void writeMoviesToFile(ArrayList<Movie> movies) { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FileController.moviesFilename))) { oos.writeObject(movies); System.out.println("Movies have been written to " + FileController.moviesFilename); } catch (IOException ignored) { } } // Function to read Movie objects from a file and return as ArrayList<Movie> public static ArrayList<Movie> readMoviesFromFile() { ArrayList<Movie> movies = new ArrayList<>(); File file = new File(FileController.moviesFilename); if (file.exists()) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { movies = (ArrayList<Movie>) ois.readObject(); System.out.println("Movies have been read from " + FileController.moviesFilename); } catch (IOException ignored) { } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } else { System.out.println("File does not exist. Creating an empty file."); writeMoviesToFile(movies); } return movies; } // Function to write Series objects to a file public static void writeSeriesToFile(ArrayList<Series> seriesList) { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FileController.seriesFilename))) { oos.writeObject(seriesList); System.out.println("Series have been written to " + FileController.seriesFilename); } catch (IOException ignored) { } } // Function to read Series objects from a file and return as ArrayList<Series> public static ArrayList<Series> readSeriesFromFile() { ArrayList<Series> seriesList = new ArrayList<>(); File file = new File(seriesFilename); if (file.exists()) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { seriesList = (ArrayList<Series>) ois.readObject(); System.out.println("Series have been read from " + seriesFilename); } catch (IOException ignored) { } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } else { System.out.println("File does not exist. Creating an empty file."); writeSeriesToFile(seriesList); } return seriesList; } // Function to write User objects to a file public static void writeUsersToFile(ArrayList<User> userList) { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(usersFilename))) { oos.writeObject(userList); System.out.println("Users have been written to " + usersFilename); } catch (IOException ignored) { } } // Function to read User objects from a file and return as ArrayList<User> public static ArrayList<User> readUsersFromFile() { ArrayList<User> userList = new ArrayList<>(); File file = new File(usersFilename); if (file.exists()) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { userList = (ArrayList<User>) ois.readObject(); System.out.println("Users have been read from " + usersFilename); } catch (IOException | ClassNotFoundException ignored) { } } else { System.out.println("File does not exist. Creating an empty file."); writeUsersToFile(userList); } return userList; } public static void createDefaultValues(){ // Default Users Admin admin1 = new Admin("admin1", "admin1", "admin1", "12345678"); Admin admin2 = new Admin("admin2", "admin2", "admin2", "12345678"); User sub1 = new Sub("sub1", "sun1", "sub1", "12345678"); User sub2 = new Sub("sub2", "sun2", "sub2", "12345678"); // Default Movies Movie movie1 = new Movie(admin1, "Oppenheimer", "Desc", false, "Thriller", 2023, 180, "Cillian Murphy", 5.0); Movie movie2 = new Movie(admin2, "Barbie", "Desc 3", true, "Comedy", 2023, 120, "Margot Robbie", 4.0); // Default Seasons Season season1 = new Season("First Season", 5, 2023); season1.addEpisode(new Episode(20)); Season season2 = new Season("Second season", 10, 2024); season2.addEpisode(new Episode(30)); // Default Series Series series1 = new Series(admin2, "Big Bang Theory", "Desc2", true, "Sci=Fi", "Johnny Galerkin, ames Joseph Parsons", 5.0); series1.addSeason(season1); // ADD DEFAULT DATA ArrayList<Movie> movies = new ArrayList<>(); movies.add(movie1); movies.add(movie2); FileController.writeMoviesToFile(movies); ArrayList<User> users = new ArrayList<>(); users.add(admin1); users.add(admin2); users.add(sub1); users.add(sub2); FileController.writeUsersToFile(users); ArrayList<Series> series = new ArrayList<>(); series.add(series1); FileController.writeSeriesToFile(series); } }
billtsol/netflix-app
src/Controllers/FileController.java
1,555
// Η κλάση αυτή έχει όλες τις λειτουργίες για τη διαχείριση των αρχείων του προγράμματος.
line_comment
el
package Controllers; import api.*; import java.io.*; import java.util.ArrayList; // Η κλάση<SUF> // Εμπεριέχει τα ονόματα των αρχείων που αποθηκεύονται τα δεδομένα και όλες τις συναρτήσεις για γράψιμο/διάβασμα αυτών των δεδομένων. public class FileController { // File Variables private static final String moviesFilename = "movies.ser"; private static final String seriesFilename = "series.ser"; private static final String usersFilename = "users.ser"; // Function to write Movie objects to a file public static void writeMoviesToFile(ArrayList<Movie> movies) { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FileController.moviesFilename))) { oos.writeObject(movies); System.out.println("Movies have been written to " + FileController.moviesFilename); } catch (IOException ignored) { } } // Function to read Movie objects from a file and return as ArrayList<Movie> public static ArrayList<Movie> readMoviesFromFile() { ArrayList<Movie> movies = new ArrayList<>(); File file = new File(FileController.moviesFilename); if (file.exists()) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { movies = (ArrayList<Movie>) ois.readObject(); System.out.println("Movies have been read from " + FileController.moviesFilename); } catch (IOException ignored) { } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } else { System.out.println("File does not exist. Creating an empty file."); writeMoviesToFile(movies); } return movies; } // Function to write Series objects to a file public static void writeSeriesToFile(ArrayList<Series> seriesList) { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FileController.seriesFilename))) { oos.writeObject(seriesList); System.out.println("Series have been written to " + FileController.seriesFilename); } catch (IOException ignored) { } } // Function to read Series objects from a file and return as ArrayList<Series> public static ArrayList<Series> readSeriesFromFile() { ArrayList<Series> seriesList = new ArrayList<>(); File file = new File(seriesFilename); if (file.exists()) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { seriesList = (ArrayList<Series>) ois.readObject(); System.out.println("Series have been read from " + seriesFilename); } catch (IOException ignored) { } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } else { System.out.println("File does not exist. Creating an empty file."); writeSeriesToFile(seriesList); } return seriesList; } // Function to write User objects to a file public static void writeUsersToFile(ArrayList<User> userList) { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(usersFilename))) { oos.writeObject(userList); System.out.println("Users have been written to " + usersFilename); } catch (IOException ignored) { } } // Function to read User objects from a file and return as ArrayList<User> public static ArrayList<User> readUsersFromFile() { ArrayList<User> userList = new ArrayList<>(); File file = new File(usersFilename); if (file.exists()) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { userList = (ArrayList<User>) ois.readObject(); System.out.println("Users have been read from " + usersFilename); } catch (IOException | ClassNotFoundException ignored) { } } else { System.out.println("File does not exist. Creating an empty file."); writeUsersToFile(userList); } return userList; } public static void createDefaultValues(){ // Default Users Admin admin1 = new Admin("admin1", "admin1", "admin1", "12345678"); Admin admin2 = new Admin("admin2", "admin2", "admin2", "12345678"); User sub1 = new Sub("sub1", "sun1", "sub1", "12345678"); User sub2 = new Sub("sub2", "sun2", "sub2", "12345678"); // Default Movies Movie movie1 = new Movie(admin1, "Oppenheimer", "Desc", false, "Thriller", 2023, 180, "Cillian Murphy", 5.0); Movie movie2 = new Movie(admin2, "Barbie", "Desc 3", true, "Comedy", 2023, 120, "Margot Robbie", 4.0); // Default Seasons Season season1 = new Season("First Season", 5, 2023); season1.addEpisode(new Episode(20)); Season season2 = new Season("Second season", 10, 2024); season2.addEpisode(new Episode(30)); // Default Series Series series1 = new Series(admin2, "Big Bang Theory", "Desc2", true, "Sci=Fi", "Johnny Galerkin, ames Joseph Parsons", 5.0); series1.addSeason(season1); // ADD DEFAULT DATA ArrayList<Movie> movies = new ArrayList<>(); movies.add(movie1); movies.add(movie2); FileController.writeMoviesToFile(movies); ArrayList<User> users = new ArrayList<>(); users.add(admin1); users.add(admin2); users.add(sub1); users.add(sub2); FileController.writeUsersToFile(users); ArrayList<Series> series = new ArrayList<>(); series.add(series1); FileController.writeSeriesToFile(series); } }
470_1
class Donator extends User { private Offers offersList = new Offers(); public Donator(int id, String name, String phone){ setName(name); setPhone(phone); setID(id); } public void add(RequestDonation rd, Organization o){ offersList.add(rd, o); } public void remove(RequestDonation rd){ offersList.remove(rd); } public Offers getOffersList(){ return offersList; } //Η μέθοδος listOffers, μετά από έλεγχο για το αν η offersList είναι άδεια: //- Αν δεν είναι άδεια, εκτυπώνει τα περιεχόμενα του αντικειμένου offersList του Donator που την καλεί public boolean listOffers(){ if (offersList.getRdEntities().isEmpty()){ System.out.println("The offersList is empty"); return false; } for (RequestDonation rd : offersList.getRdEntities()){ System.out.println(String.format("ID: %d Name: %s Quantity: %.2f Type: %s", rd.getID(), rd.getName(), rd.getQuantity(), rd.getEntity().isService() ? "Service" : "Material")); } return true; } }
bioagg/DonationSystem
src/Donator.java
358
//- Αν δεν είναι άδεια, εκτυπώνει τα περιεχόμενα του αντικειμένου offersList του Donator που την καλεί
line_comment
el
class Donator extends User { private Offers offersList = new Offers(); public Donator(int id, String name, String phone){ setName(name); setPhone(phone); setID(id); } public void add(RequestDonation rd, Organization o){ offersList.add(rd, o); } public void remove(RequestDonation rd){ offersList.remove(rd); } public Offers getOffersList(){ return offersList; } //Η μέθοδος listOffers, μετά από έλεγχο για το αν η offersList είναι άδεια: //- Αν<SUF> public boolean listOffers(){ if (offersList.getRdEntities().isEmpty()){ System.out.println("The offersList is empty"); return false; } for (RequestDonation rd : offersList.getRdEntities()){ System.out.println(String.format("ID: %d Name: %s Quantity: %.2f Type: %s", rd.getID(), rd.getName(), rd.getQuantity(), rd.getEntity().isService() ? "Service" : "Material")); } return true; } }
1272_3
public class BinarySearchPlus { public static void main(String[] args) { int[] myArray = {8, 22, 90, 5, 15, 54, 3, 23, 7, 2}; int t = 3; bubbleSort (myArray); int thesi = binarySearch(myArray, t); if (thesi == -1) { System.out.println("το στοιχείο " + t + " δε βρέθηκε"); } else { System.out.println("το στοιχείο " + t + " βρέθηκε σστη θέση " + thesi); } } public static void bubbleSort (int[] pin) { int size = pin.length; int temp; boolean did_swap=false; for (int i=0; i<size; i++) { for (int j=1; j<(size-i); j++) { if (pin[j-1] > pin[j]) { temp = pin[j-1]; pin[j-1] = pin[j]; pin[j] = temp; did_swap = true; } } if (did_swap==false) break; } } public static int binarySearch(int[] A, int target) { int left = 0; int size = A.length; int right = size-1; int found = -1; int mid; while (found == -1 && left <= right) { // το while θα συνεχίζεται όσο δεν έχω βρει το στοιχείο που // ψαχνω (όσο το found είναι ίσο με -1)και όσο δεν μου έχουν // τελειώσει τα στοιχεία του πίνακα (δηλ το left δεν έχει γίνει // μεγαλύτερο από το right mid = (left + right) / 2; if (target < A[mid]) { right = mid - 1; } else if (target > A[mid]) { left = mid + 1; } else found = mid; } return found; } }
bourakis/Algorithms-Data-Structures
Algorithms/BinarySearchPlus.java
625
// μεγαλύτερο από το right
line_comment
el
public class BinarySearchPlus { public static void main(String[] args) { int[] myArray = {8, 22, 90, 5, 15, 54, 3, 23, 7, 2}; int t = 3; bubbleSort (myArray); int thesi = binarySearch(myArray, t); if (thesi == -1) { System.out.println("το στοιχείο " + t + " δε βρέθηκε"); } else { System.out.println("το στοιχείο " + t + " βρέθηκε σστη θέση " + thesi); } } public static void bubbleSort (int[] pin) { int size = pin.length; int temp; boolean did_swap=false; for (int i=0; i<size; i++) { for (int j=1; j<(size-i); j++) { if (pin[j-1] > pin[j]) { temp = pin[j-1]; pin[j-1] = pin[j]; pin[j] = temp; did_swap = true; } } if (did_swap==false) break; } } public static int binarySearch(int[] A, int target) { int left = 0; int size = A.length; int right = size-1; int found = -1; int mid; while (found == -1 && left <= right) { // το while θα συνεχίζεται όσο δεν έχω βρει το στοιχείο που // ψαχνω (όσο το found είναι ίσο με -1)και όσο δεν μου έχουν // τελειώσει τα στοιχεία του πίνακα (δηλ το left δεν έχει γίνει // μεγαλύτερο από<SUF> mid = (left + right) / 2; if (target < A[mid]) { right = mid - 1; } else if (target > A[mid]) { left = mid + 1; } else found = mid; } return found; } }
4258_0
/* Μέλη Ομάδας Λόκκας Ιωάννης ΑΜ: 3120095 Μπούζας Βασίλειος ΑΜ: 3120124 Τασσιάς Παναγιώτης ΑΜ: 3120181 */ // An about window that displays info about the Developers and the Game package Score4_GUI; public class about extends javax.swing.JDialog { public about(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { aboutLabel = new javax.swing.JLabel(); auebLogo = new javax.swing.JLabel(); aboutText = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("About Us"); setBackground(new java.awt.Color(255, 255, 255)); setLocation(new java.awt.Point(450, 200)); aboutLabel.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N aboutLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); aboutLabel.setText("About Us"); aboutLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); auebLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Assets/aueb_logo.jpeg"))); // NOI18N aboutText.setEditable(false); aboutText.setBackground(new java.awt.Color(204, 204, 204)); aboutText.setColumns(20); aboutText.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N aboutText.setRows(5); aboutText.setText("This application is based on the famous game Score4 (or Connect4).\n\nIt was developed for the purpose of Artificial Intelligence (AI) course of\nAthens University of Economics and Business (AUEB).\n\nThe Developers (by alphabetical order):\n-Bouzas Vasileios\n-Lokkas Ioannis\n-Tassias Panagiotis"); 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(135, 135, 135) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(auebLogo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(aboutLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(145, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(aboutText, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(aboutLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(auebLogo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(aboutText, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(15, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel aboutLabel; private javax.swing.JTextArea aboutText; private javax.swing.JLabel auebLogo; // End of variables declaration//GEN-END:variables }
bouzasvas/AI_Score4
AI_Score4/src/Score4_GUI/about.java
1,095
/* Μέλη Ομάδας Λόκκας Ιωάννης ΑΜ: 3120095 Μπούζας Βασίλειος ΑΜ: 3120124 Τασσιάς Παναγιώτης ΑΜ: 3120181 */
block_comment
el
/* Μέλη Ομάδας <SUF>*/ // An about window that displays info about the Developers and the Game package Score4_GUI; public class about extends javax.swing.JDialog { public about(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { aboutLabel = new javax.swing.JLabel(); auebLogo = new javax.swing.JLabel(); aboutText = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("About Us"); setBackground(new java.awt.Color(255, 255, 255)); setLocation(new java.awt.Point(450, 200)); aboutLabel.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N aboutLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); aboutLabel.setText("About Us"); aboutLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); auebLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Assets/aueb_logo.jpeg"))); // NOI18N aboutText.setEditable(false); aboutText.setBackground(new java.awt.Color(204, 204, 204)); aboutText.setColumns(20); aboutText.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N aboutText.setRows(5); aboutText.setText("This application is based on the famous game Score4 (or Connect4).\n\nIt was developed for the purpose of Artificial Intelligence (AI) course of\nAthens University of Economics and Business (AUEB).\n\nThe Developers (by alphabetical order):\n-Bouzas Vasileios\n-Lokkas Ioannis\n-Tassias Panagiotis"); 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(135, 135, 135) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(auebLogo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(aboutLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(145, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(aboutText, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(aboutLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(auebLogo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(aboutText, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(15, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel aboutLabel; private javax.swing.JTextArea aboutText; private javax.swing.JLabel auebLogo; // End of variables declaration//GEN-END:variables }
4254_1
/* Μέλη Ομάδας Λόκκας Ιωάννης ΑΜ: 3120095 Μπούζας Βασίλειος ΑΜ: 3120124 Τασσιάς Παναγιώτης ΑΜ: 3120181 */ package Horn_ForwardChaining; import Logic_AI.Literal; import java.util.ArrayList; /* -------------------------------------Αναπαριστά μία πρόταση Horn-------------------------------------- Αποτελείται από πολλές υπο-προτάσεις Horn (HornSubClause) δηλαδή προτάσεις της μορφής A^B=>C οι οποίες αποθηκεύονται σε μία ArrayList. */ public class HornClause { ArrayList<HornSubClause> KB; public HornClause() { KB = new ArrayList<HornSubClause>(); } public void addHornSubClause(HornSubClause subClause) { KB.add(subClause); } // Μέθοδος για να πάρουμε τα γεγονότα που έχουμε συμπεράνει από τη Βάση Γνώσης public ArrayList<Literal> getFacts() { ArrayList<Literal> trueSubClauses = new ArrayList<Literal>(); for (HornSubClause hsc : KB) { if (hsc.getClause() == null) { trueSubClauses.add(hsc.getInferrence()); } } return trueSubClauses; } public void print() { for (HornSubClause subClause : KB) { subClause.printSubClause(); } } public ArrayList<HornSubClause> getSubClauses() { return this.KB; } }
bouzasvas/Logic_AI
Logic_AI/src/Horn_ForwardChaining/HornClause.java
556
/* -------------------------------------Αναπαριστά μία πρόταση Horn-------------------------------------- Αποτελείται από πολλές υπο-προτάσεις Horn (HornSubClause) δηλαδή προτάσεις της μορφής A^B=>C οι οποίες αποθηκεύονται σε μία ArrayList. */
block_comment
el
/* Μέλη Ομάδας Λόκκας Ιωάννης ΑΜ: 3120095 Μπούζας Βασίλειος ΑΜ: 3120124 Τασσιάς Παναγιώτης ΑΜ: 3120181 */ package Horn_ForwardChaining; import Logic_AI.Literal; import java.util.ArrayList; /* -------------------------------------Αναπαριστά μία πρόταση<SUF>*/ public class HornClause { ArrayList<HornSubClause> KB; public HornClause() { KB = new ArrayList<HornSubClause>(); } public void addHornSubClause(HornSubClause subClause) { KB.add(subClause); } // Μέθοδος για να πάρουμε τα γεγονότα που έχουμε συμπεράνει από τη Βάση Γνώσης public ArrayList<Literal> getFacts() { ArrayList<Literal> trueSubClauses = new ArrayList<Literal>(); for (HornSubClause hsc : KB) { if (hsc.getClause() == null) { trueSubClauses.add(hsc.getInferrence()); } } return trueSubClauses; } public void print() { for (HornSubClause subClause : KB) { subClause.printSubClause(); } } public ArrayList<HornSubClause> getSubClauses() { return this.KB; } }
11555_0
package gr.aueb.dmst.monitor; import java.sql.Connection; import java.sql.DriverManager; public class Database { private static final String DATABASE_URL = "jdbc:postgresql://localhost:5432/container_instances_metrics"; private static final String USERNAME = "postgres"; private static final String PASSWORD = "mysecretpassword"; public Connection getConnection() { Connection conn = null; // Try statement για να πραγματοποιήσουμε σύνδεση με την Βάση Δεδομένων try { conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD); } catch (Exception e) { e.printStackTrace(); } return conn; } }
brikoumariaa/DOCKERDESKTOP
monitor/src/main/resources/Database.java
205
// Try statement για να πραγματοποιήσουμε σύνδεση με την Βάση Δεδομένων
line_comment
el
package gr.aueb.dmst.monitor; import java.sql.Connection; import java.sql.DriverManager; public class Database { private static final String DATABASE_URL = "jdbc:postgresql://localhost:5432/container_instances_metrics"; private static final String USERNAME = "postgres"; private static final String PASSWORD = "mysecretpassword"; public Connection getConnection() { Connection conn = null; // Try statement<SUF> try { conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD); } catch (Exception e) { e.printStackTrace(); } return conn; } }
2598_4
public class HashTable { int[] array; int size; int nItems; //(3 μον) οι μεταβλητές public HashTable() { // Κάνουμε πάντα κενό constructor ακόμα και αν δε ζητείται! (1 μον) array = new int[0]; size = 0; nItems = 0; } public HashTable(int n) { // (1 μον) array = new int[n]; size = n; nItems = 0; } public int size() { // (1 μον) return size; } public int numOfItems() { // Θα μπορούσαμε να μην έχουμε μεταβητή nItems. (3 μον) return nItems; } public boolean isEmpty() { // παλι θα μπορουσα να μην εχω nItems (3 μον) return nItems == 0; } public float tableFullness() { // (3 μον) return 100 * (float)nItems / (float)size; } public void hash(int k, int m) { // Το m είναι τυχαίο if (k <= 0 || m <= 0) { System.out.println("Λάθος Είσοδος"); return; // Invalid arguments } int index = k % m; while( array[index] != 0 ) { index = (index+1) % size; // Προσοχή στην υπερχείλιση } array[index] = k; nItems++; if (tableFullness() > 75) { int newSize = 2 * size; int[] newArray = new int[newSize]; for (int i = 0; i < size; i++ ) { newArray[i] = array[i]; } array = newArray; size = 2 * size; } } }
bugos/algo
AUTh Courses/Data Structures (Java)/Epanaliptiko Ergastirio/HashTable/src/HashTable.java
583
// Το m είναι τυχαίο
line_comment
el
public class HashTable { int[] array; int size; int nItems; //(3 μον) οι μεταβλητές public HashTable() { // Κάνουμε πάντα κενό constructor ακόμα και αν δε ζητείται! (1 μον) array = new int[0]; size = 0; nItems = 0; } public HashTable(int n) { // (1 μον) array = new int[n]; size = n; nItems = 0; } public int size() { // (1 μον) return size; } public int numOfItems() { // Θα μπορούσαμε να μην έχουμε μεταβητή nItems. (3 μον) return nItems; } public boolean isEmpty() { // παλι θα μπορουσα να μην εχω nItems (3 μον) return nItems == 0; } public float tableFullness() { // (3 μον) return 100 * (float)nItems / (float)size; } public void hash(int k, int m) { // Το m<SUF> if (k <= 0 || m <= 0) { System.out.println("Λάθος Είσοδος"); return; // Invalid arguments } int index = k % m; while( array[index] != 0 ) { index = (index+1) % size; // Προσοχή στην υπερχείλιση } array[index] = k; nItems++; if (tableFullness() > 75) { int newSize = 2 * size; int[] newArray = new int[newSize]; for (int i = 0; i < size; i++ ) { newArray[i] = array[i]; } array = newArray; size = 2 * size; } } }
2157_2
package gr.aueb.edtmgr.util; import java.time.LocalDate; /** * Βοηθητική κλάση για τη λήψη της ημερομηνίας του συστήματος. * Η κλάση επιτρέπει να υποκατασταθεί η ημερομηνία του συστήματος με μία * προκαθορισμένη ημερομηνία. Η δυνατότητα αυτή * είναι ιδιαίτερη χρήσιμη για την εκτέλεση αυτόματων ελέγχων. * @author Νίκος Διαμαντίδης * */ public class SystemDate { /** * Απαγορεύουμε τη δημιουργία αντικείμενων. */ protected SystemDate() { } private static LocalDate stub; /** * Θέτει μία συγκεκριμένη ημερομηνία ως την ημερομηνία του συστήματος. * Η ημερομηνία αυτή επιστρέφεται από την {@link SystemDate#now()}. * Εάν αντί για προκαθορισμένης ημερομηνίας τεθεί * {@code null} τότε επιστρέφεται * η πραγματική ημερομηνία του συστήματος * @param stubDate Η ημερομηνία η οποία θα επιστρέφεται * ως ημερομηνία του συστήματος ή {@code null} για * να επιστρέφει την πραγματική ημερομηνία */ protected static void setStub(LocalDate stubDate) { stub = stubDate; } /** * Απομακρύνει το στέλεχος. */ protected static void removeStub() { stub = null; } /** * Επιστρέφει την ημερομηνία του συστήματος ή μία * προκαθορισμένη ημερομηνία που έχει * τεθεί από την {@link SystemDate#setStub}. * @return Η ημερομηνία του συστήματος ή μία προκαθορισμένη ημερομηνία */ public static LocalDate now() { return stub == null ? LocalDate.now() : stub; } }
bzafiris/quarkus-editorial-manager
src/main/java/gr/aueb/edtmgr/util/SystemDate.java
918
/** * Θέτει μία συγκεκριμένη ημερομηνία ως την ημερομηνία του συστήματος. * Η ημερομηνία αυτή επιστρέφεται από την {@link SystemDate#now()}. * Εάν αντί για προκαθορισμένης ημερομηνίας τεθεί * {@code null} τότε επιστρέφεται * η πραγματική ημερομηνία του συστήματος * @param stubDate Η ημερομηνία η οποία θα επιστρέφεται * ως ημερομηνία του συστήματος ή {@code null} για * να επιστρέφει την πραγματική ημερομηνία */
block_comment
el
package gr.aueb.edtmgr.util; import java.time.LocalDate; /** * Βοηθητική κλάση για τη λήψη της ημερομηνίας του συστήματος. * Η κλάση επιτρέπει να υποκατασταθεί η ημερομηνία του συστήματος με μία * προκαθορισμένη ημερομηνία. Η δυνατότητα αυτή * είναι ιδιαίτερη χρήσιμη για την εκτέλεση αυτόματων ελέγχων. * @author Νίκος Διαμαντίδης * */ public class SystemDate { /** * Απαγορεύουμε τη δημιουργία αντικείμενων. */ protected SystemDate() { } private static LocalDate stub; /** * Θέτει μία συγκεκριμένη<SUF>*/ protected static void setStub(LocalDate stubDate) { stub = stubDate; } /** * Απομακρύνει το στέλεχος. */ protected static void removeStub() { stub = null; } /** * Επιστρέφει την ημερομηνία του συστήματος ή μία * προκαθορισμένη ημερομηνία που έχει * τεθεί από την {@link SystemDate#setStub}. * @return Η ημερομηνία του συστήματος ή μία προκαθορισμένη ημερομηνία */ public static LocalDate now() { return stub == null ? LocalDate.now() : stub; } }
2102_6
package edu.uoa.estia.repository; import org.geotools.geojson.geom.GeometryJSON; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.PrecisionModel; import edu.uoa.estia.domain.Akinita; import edu.uoa.estia.domain.Property; import edu.uoa.estia.domain.PropertyType; import edu.uoa.estia.domain.User; import edu.uoa.estia.utils.JTSGeomToGeoJSONSerializer; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration (locations = {"classpath:test-applicationContext-data.xml"}) //@Transactional public class PropertyRepositoryTest { @Autowired private PropertyRepository propertyRepository; @Autowired private PropertyTypeRepository propertyTypeRepository; @Autowired private UserRepository userRepository; @Value("${srid.projected}") int SRID; // This should come from the DB at init time /* @Test public void testFindByIdioktitis() { Akinita a = new Akinita(); Akinita ak = propertyRepository.findByIdioktitis("Alkionis ke Monterno Theatro"); Assert.assertNotNull(ak); Point topo = ak.getTopothesia(); Assert.assertNotNull(topo); } @Test public void testGeoJSON() { Akinita ak = propertyRepository.fin("Alkionis ke Monterno Theatro"); Assert.assertNotNull(ak); Point topo = ak.getTopothesia(); Assert.assertNotNull(topo); GeometryJSON gjson = new GeometryJSON(); String geojson = gjson.toString(topo); Assert.assertNotNull(geojson); JTSGeomToGeoJSONSerializer k = new JTSGeomToGeoJSONSerializer(); } */ //"Ioulianou 44, Athina 104 34, Greece";"{"type":"Point","coordinates":[2641419.82436124,4578259.15885338]}" //"Titanon 3, Athina, Greece";"{"type":"Point","coordinates":[2642762.00346173,4579075.19544573]}" //"Zakinthou, Athina, Greece";"{"type":"Point","coordinates":[2642719.03413828,4579300.36901176]}" //"3ης Σεπτεμβρίου 174, Αθήνα 112 51, Ελλάδα";"{"type":"Point","coordinates":[2641821.91036198,4579393.60416694]}" // μεγιστησ 14, αθηνα 113 61 "POINT(2642692.98537744 4579805.967893)" // σταυραετού 17, ζωγραφου 157 72 "POINT(2646046.70767657 4575998.40783071)" // δικεάρχου 156, Βύρωνας 116 32 "POINT(2643315.37265047 4573787.70722493)" // καλαμών 32 , Γαλάτσι 11 47 "POINT(2644211.27191237 4580756.62841776)" // σαμαρά 22, Ψυχικό 154 52 "POINT(2646365.86065667 4581635.59728266)" // καλλιγά 43, Φιλοθέη 152 37 "POINT(2647818.13473356 4582901.55092342)" // επιδάυρου 73, πολύδροσο 152 33 "POINT(2649920.18067821 4583479.6821374)" // κύπρου 26, βριλήσσια 152 35 "POINT(2653187.85301096 4584196.20829953)" // πίνδου 23, βριλήσσια 152 35 "POINT(2653101.91436406 4584611.87273375)" // Ηρακλειδών 56, Νέο Ηράκλειο 141 21 "POINT(2645930.49012818 4585427.56200019)" // Κολοκοτρώνη 93, Νεο ηράκλειο 141 21 "POINT(2646258.10338958 4586610.43270481)" // Διονύσου 15, Κηφισιά 145 62 "POINT(2650999.08918298 4590351.33142519)" // Αναξαγόρα 14, νέα ερυθραία 145 62 "POINT(2651539.21135231 4592224.55135272)" // Πλαπούτα 16-26, Μεταμόρφωση "POINT(2644449.49562266 4588387.11316268)" // Λυκούργου 3, Κορυδαλλός 181 20 "POINT(2632397.04567397 4576001.23222601)" // Κνωσού 25, Νίκαια 184 51 "POINT(2631616.02812656 4575077.97839304)" // Θράκης 76-84, Πετρούπολη "POINT(2636826.44821263 4585285.64921568)" // Πάρου 6, Περιστέρι 121 36 "POINT(2636583.32644474 4581291.40447833)" @Test public void testCreateProperty() { Property p = new Property(); GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING),SRID); Point topo = gf.createPoint(new Coordinate(2636583.32644474 , 4581291.40447833)); // in SRID:3857 User u = userRepository.findByUsername("owner"); PropertyType pt = propertyTypeRepository.findByType("Apartment"); p.setDieythinsi("Πάρου 6, Περιστέρι 121 36"); p.setUser(u); p.setType(pt); p.setCentralHeating(true); p.setConstructionYear(1997); p.setEmvadon(92f); p.setKoinoxrista(95d); p.setOrofos(1); p.setRenovationYear(2013); p.setPrice(360000d); p.setTopothesia(topo); propertyRepository.saveAndFlush(p); } @Test public void testUpdateProperty() { GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING),SRID); Property p = propertyRepository.findById(5); if(p.getConstructionYear()==1986) p.setTopothesia(gf.createPoint(new Coordinate(2642692.98537744 , 4579805.967893))); propertyRepository.saveAndFlush(p); } @Test public void testCreatePropertyType() { PropertyType p = new PropertyType(); p.setType("Penthouse"); p.setOnoma("Ρετιρέ"); propertyTypeRepository.saveAndFlush(p); } }
captain78/Estia
src/test/java/edu/uoa/estia/repository/PropertyRepositoryTest.java
2,602
// μεγιστησ 14, αθηνα 113 61 "POINT(2642692.98537744 4579805.967893)"
line_comment
el
package edu.uoa.estia.repository; import org.geotools.geojson.geom.GeometryJSON; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.PrecisionModel; import edu.uoa.estia.domain.Akinita; import edu.uoa.estia.domain.Property; import edu.uoa.estia.domain.PropertyType; import edu.uoa.estia.domain.User; import edu.uoa.estia.utils.JTSGeomToGeoJSONSerializer; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration (locations = {"classpath:test-applicationContext-data.xml"}) //@Transactional public class PropertyRepositoryTest { @Autowired private PropertyRepository propertyRepository; @Autowired private PropertyTypeRepository propertyTypeRepository; @Autowired private UserRepository userRepository; @Value("${srid.projected}") int SRID; // This should come from the DB at init time /* @Test public void testFindByIdioktitis() { Akinita a = new Akinita(); Akinita ak = propertyRepository.findByIdioktitis("Alkionis ke Monterno Theatro"); Assert.assertNotNull(ak); Point topo = ak.getTopothesia(); Assert.assertNotNull(topo); } @Test public void testGeoJSON() { Akinita ak = propertyRepository.fin("Alkionis ke Monterno Theatro"); Assert.assertNotNull(ak); Point topo = ak.getTopothesia(); Assert.assertNotNull(topo); GeometryJSON gjson = new GeometryJSON(); String geojson = gjson.toString(topo); Assert.assertNotNull(geojson); JTSGeomToGeoJSONSerializer k = new JTSGeomToGeoJSONSerializer(); } */ //"Ioulianou 44, Athina 104 34, Greece";"{"type":"Point","coordinates":[2641419.82436124,4578259.15885338]}" //"Titanon 3, Athina, Greece";"{"type":"Point","coordinates":[2642762.00346173,4579075.19544573]}" //"Zakinthou, Athina, Greece";"{"type":"Point","coordinates":[2642719.03413828,4579300.36901176]}" //"3ης Σεπτεμβρίου 174, Αθήνα 112 51, Ελλάδα";"{"type":"Point","coordinates":[2641821.91036198,4579393.60416694]}" // μεγιστησ 14,<SUF> // σταυραετού 17, ζωγραφου 157 72 "POINT(2646046.70767657 4575998.40783071)" // δικεάρχου 156, Βύρωνας 116 32 "POINT(2643315.37265047 4573787.70722493)" // καλαμών 32 , Γαλάτσι 11 47 "POINT(2644211.27191237 4580756.62841776)" // σαμαρά 22, Ψυχικό 154 52 "POINT(2646365.86065667 4581635.59728266)" // καλλιγά 43, Φιλοθέη 152 37 "POINT(2647818.13473356 4582901.55092342)" // επιδάυρου 73, πολύδροσο 152 33 "POINT(2649920.18067821 4583479.6821374)" // κύπρου 26, βριλήσσια 152 35 "POINT(2653187.85301096 4584196.20829953)" // πίνδου 23, βριλήσσια 152 35 "POINT(2653101.91436406 4584611.87273375)" // Ηρακλειδών 56, Νέο Ηράκλειο 141 21 "POINT(2645930.49012818 4585427.56200019)" // Κολοκοτρώνη 93, Νεο ηράκλειο 141 21 "POINT(2646258.10338958 4586610.43270481)" // Διονύσου 15, Κηφισιά 145 62 "POINT(2650999.08918298 4590351.33142519)" // Αναξαγόρα 14, νέα ερυθραία 145 62 "POINT(2651539.21135231 4592224.55135272)" // Πλαπούτα 16-26, Μεταμόρφωση "POINT(2644449.49562266 4588387.11316268)" // Λυκούργου 3, Κορυδαλλός 181 20 "POINT(2632397.04567397 4576001.23222601)" // Κνωσού 25, Νίκαια 184 51 "POINT(2631616.02812656 4575077.97839304)" // Θράκης 76-84, Πετρούπολη "POINT(2636826.44821263 4585285.64921568)" // Πάρου 6, Περιστέρι 121 36 "POINT(2636583.32644474 4581291.40447833)" @Test public void testCreateProperty() { Property p = new Property(); GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING),SRID); Point topo = gf.createPoint(new Coordinate(2636583.32644474 , 4581291.40447833)); // in SRID:3857 User u = userRepository.findByUsername("owner"); PropertyType pt = propertyTypeRepository.findByType("Apartment"); p.setDieythinsi("Πάρου 6, Περιστέρι 121 36"); p.setUser(u); p.setType(pt); p.setCentralHeating(true); p.setConstructionYear(1997); p.setEmvadon(92f); p.setKoinoxrista(95d); p.setOrofos(1); p.setRenovationYear(2013); p.setPrice(360000d); p.setTopothesia(topo); propertyRepository.saveAndFlush(p); } @Test public void testUpdateProperty() { GeometryFactory gf = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING),SRID); Property p = propertyRepository.findById(5); if(p.getConstructionYear()==1986) p.setTopothesia(gf.createPoint(new Coordinate(2642692.98537744 , 4579805.967893))); propertyRepository.saveAndFlush(p); } @Test public void testCreatePropertyType() { PropertyType p = new PropertyType(); p.setType("Penthouse"); p.setOnoma("Ρετιρέ"); propertyTypeRepository.saveAndFlush(p); } }
9715_7
package main.java.org.javafx.studentsmanagementsystem.controller; import org.apache.commons.codec.digest.DigestUtils; import com.jfoenix.controls.JFXRadioButton; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.util.Duration; import main.java.org.javafx.studentsmanagementsystem.application.Main; import main.java.org.javafx.studentsmanagementsystem.model.Professor; import main.java.org.javafx.studentsmanagementsystem.model.SQLiteJDBC; import main.java.org.javafx.studentsmanagementsystem.model.Student; import main.java.org.javafx.studentsmanagementsystem.tools.JavaFXTools; import main.java.org.javafx.studentsmanagementsystem.tools.NotificationType; public class MainController { @FXML private Button signIn; @FXML private TextField signMail; @FXML private PasswordField signPass; @FXML private ToggleGroup loginType; @FXML private TextField studName; @FXML private TextField studMail; @FXML private Button registerStud; @FXML private PasswordField studPass; @FXML private PasswordField studPass2; @FXML private TextField profName; @FXML private TextField profMail; @FXML private Button registerProf; @FXML private TextField profCourse; @FXML private PasswordField profPass; @FXML private PasswordField profPass2; //those that signed in succesfully public static Student stud; public static Professor prof; public void onClickSignIn(ActionEvent e) { try { //true == student if ("Student".equals( ( (JFXRadioButton) loginType.getSelectedToggle() ).getText())) { //search in the student table this.stud = SQLiteJDBC.findStud(addThingies(signMail.getText()), addThingies(DigestUtils.sha1Hex(signPass.getText()))); if (stud.getStudId().equals(-1)) { showAlert(Alert.AlertType.WARNING, "Student not found", "Please fill the fields again!"); blankSign(); return; } try { //--------------------Go to student home------------- FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(Main.FXMLS + "StudentController.fxml")); Parent root1 = (Parent) fxmlLoader.load(); Main.setContent(root1, "Student home"); } catch (Exception es) { es.printStackTrace(); } } else { //search in the prof table this.prof = SQLiteJDBC.findProf(addThingies(signMail.getText()), addThingies(DigestUtils.sha1Hex(signPass.getText()))); if (prof.getId().equals(-1)) { showAlert(Alert.AlertType.WARNING, "Professor not found", "Please fill the fields again!"); blankSign(); return; } try { //--------------------Go to professor home------------- FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(Main.FXMLS + "ProfessorController.fxml")); Parent root1 = (Parent) fxmlLoader.load(); Main.setContent(root1, "Professor Home"); } catch (Exception ep) { ep.printStackTrace(); } } } catch (Exception ex) { ex.printStackTrace(); } } public void onRegisterProf(ActionEvent e) { //runs insertProf String name = addThingies(profName.getText()); String mail = addThingies(profMail.getText()); String pass = profPass.getText(); String pass2 = profPass2.getText(); String course = addThingies(profCourse.getText()); //are all the fields filled? if (profName.getText().equals("") || profMail.getText().equals("") || profPass.getText().equals("") || profCourse.getText().equals("")) { showAlert(Alert.AlertType.WARNING, "You need to fill in all the fields!", "Try Again!"); profPass.setText(""); profPass2.setText(""); return; } if (!pass.equals(pass2)) { showAlert(Alert.AlertType.WARNING, "Passwords don't match!", "Try Again!"); profPass.setText(""); profPass2.setText(""); return; } //προσθέτουμε τα quotes ελέγχουμε γia sqli και περνάμε απο συνάρτηση σύνοψης. pass = addThingies(DigestUtils.sha1Hex(pass)); SQLiteJDBC.insertProf(name, mail, pass, course); blankProf(); } public static String addThingies(String s) { return "'" + mysql_real_escape_string(s) + "'"; } //SQLi protection public static String mysql_real_escape_string(String str) { if (str == null) { return null; } if (str.replaceAll("[a-zA-Z0-9_!@#$%^&*()-=+~.;:,\\Q[\\E\\Q]\\E<>{}\\/? ]", "").length() < 1) { return str; } String clean_string = str; clean_string = clean_string.replaceAll("\\\\", "\\\\\\\\"); clean_string = clean_string.replaceAll("\\n", "\\\\n"); clean_string = clean_string.replaceAll("\\r", "\\\\r"); clean_string = clean_string.replaceAll("\\t", "\\\\t"); clean_string = clean_string.replaceAll("\\00", "\\\\0"); clean_string = clean_string.replaceAll("'", "\\\\'"); clean_string = clean_string.replaceAll("\\\"", "\\\\\""); if (clean_string.replaceAll("[a-zA-Z0-9_!@#$%^&*()-=+~.;:,\\Q[\\E\\Q]\\E<>{}\\/?\\\\\"' ]", "").length() < 1) { return clean_string; } return str; } public void blankProf() { profPass.setText(""); profPass2.setText(""); profName.setText(""); profCourse.setText(""); profMail.setText(""); } public void blankStud() { studPass.setText(""); studPass2.setText(""); studName.setText(""); studMail.setText(""); } public void blankSign() { signMail.setText(""); signPass.setText(""); } public void onRegisterStud(ActionEvent e) { //runs insertStud String name = addThingies(studName.getText()); String mail = addThingies(studMail.getText()); String pass = studPass.getText(); String pass2 = studPass2.getText(); // are all the fields filled? if (studName.getText().equals("") || studMail.getText().equals("") || studPass.getText().equals("")) { showAlert(Alert.AlertType.WARNING, "You need to fill in all the fields!", "Try Again!"); profPass.setText(""); profPass2.setText(""); return; } //is the password correct? if (!pass.equals(pass2)) { showAlert(Alert.AlertType.WARNING, "Passwords don't match!", "Try Again!"); studPass.setText(""); studPass2.setText(""); return; } pass = addThingies(DigestUtils.sha1Hex(pass)); //in here we check if the email already exists SQLiteJDBC.insertStud(name, mail, pass); blankStud(); } public static void showAlert(Alert.AlertType a , String header , String body) { JavaFXTools.showNotification(header, body, Duration.seconds(5), NotificationType.INFORMATION); // Alert alert = new Alert(a); // if (a == Alert.AlertType.WARNING) { // alert.setTitle("Attention!"); // // } else if (a == Alert.AlertType.INFORMATION) { // alert.setTitle("Success"); // } // alert.setHeaderText(header); // alert.setContentText(body); // alert.showAndWait(); } }
catman85/JavaFX-Student-Management-System
src/main/java/org/javafx/studentsmanagementsystem/controller/MainController.java
2,150
//προσθέτουμε τα quotes ελέγχουμε γia sqli και περνάμε απο συνάρτηση σύνοψης.
line_comment
el
package main.java.org.javafx.studentsmanagementsystem.controller; import org.apache.commons.codec.digest.DigestUtils; import com.jfoenix.controls.JFXRadioButton; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.util.Duration; import main.java.org.javafx.studentsmanagementsystem.application.Main; import main.java.org.javafx.studentsmanagementsystem.model.Professor; import main.java.org.javafx.studentsmanagementsystem.model.SQLiteJDBC; import main.java.org.javafx.studentsmanagementsystem.model.Student; import main.java.org.javafx.studentsmanagementsystem.tools.JavaFXTools; import main.java.org.javafx.studentsmanagementsystem.tools.NotificationType; public class MainController { @FXML private Button signIn; @FXML private TextField signMail; @FXML private PasswordField signPass; @FXML private ToggleGroup loginType; @FXML private TextField studName; @FXML private TextField studMail; @FXML private Button registerStud; @FXML private PasswordField studPass; @FXML private PasswordField studPass2; @FXML private TextField profName; @FXML private TextField profMail; @FXML private Button registerProf; @FXML private TextField profCourse; @FXML private PasswordField profPass; @FXML private PasswordField profPass2; //those that signed in succesfully public static Student stud; public static Professor prof; public void onClickSignIn(ActionEvent e) { try { //true == student if ("Student".equals( ( (JFXRadioButton) loginType.getSelectedToggle() ).getText())) { //search in the student table this.stud = SQLiteJDBC.findStud(addThingies(signMail.getText()), addThingies(DigestUtils.sha1Hex(signPass.getText()))); if (stud.getStudId().equals(-1)) { showAlert(Alert.AlertType.WARNING, "Student not found", "Please fill the fields again!"); blankSign(); return; } try { //--------------------Go to student home------------- FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(Main.FXMLS + "StudentController.fxml")); Parent root1 = (Parent) fxmlLoader.load(); Main.setContent(root1, "Student home"); } catch (Exception es) { es.printStackTrace(); } } else { //search in the prof table this.prof = SQLiteJDBC.findProf(addThingies(signMail.getText()), addThingies(DigestUtils.sha1Hex(signPass.getText()))); if (prof.getId().equals(-1)) { showAlert(Alert.AlertType.WARNING, "Professor not found", "Please fill the fields again!"); blankSign(); return; } try { //--------------------Go to professor home------------- FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(Main.FXMLS + "ProfessorController.fxml")); Parent root1 = (Parent) fxmlLoader.load(); Main.setContent(root1, "Professor Home"); } catch (Exception ep) { ep.printStackTrace(); } } } catch (Exception ex) { ex.printStackTrace(); } } public void onRegisterProf(ActionEvent e) { //runs insertProf String name = addThingies(profName.getText()); String mail = addThingies(profMail.getText()); String pass = profPass.getText(); String pass2 = profPass2.getText(); String course = addThingies(profCourse.getText()); //are all the fields filled? if (profName.getText().equals("") || profMail.getText().equals("") || profPass.getText().equals("") || profCourse.getText().equals("")) { showAlert(Alert.AlertType.WARNING, "You need to fill in all the fields!", "Try Again!"); profPass.setText(""); profPass2.setText(""); return; } if (!pass.equals(pass2)) { showAlert(Alert.AlertType.WARNING, "Passwords don't match!", "Try Again!"); profPass.setText(""); profPass2.setText(""); return; } //προσθέτουμε τα<SUF> pass = addThingies(DigestUtils.sha1Hex(pass)); SQLiteJDBC.insertProf(name, mail, pass, course); blankProf(); } public static String addThingies(String s) { return "'" + mysql_real_escape_string(s) + "'"; } //SQLi protection public static String mysql_real_escape_string(String str) { if (str == null) { return null; } if (str.replaceAll("[a-zA-Z0-9_!@#$%^&*()-=+~.;:,\\Q[\\E\\Q]\\E<>{}\\/? ]", "").length() < 1) { return str; } String clean_string = str; clean_string = clean_string.replaceAll("\\\\", "\\\\\\\\"); clean_string = clean_string.replaceAll("\\n", "\\\\n"); clean_string = clean_string.replaceAll("\\r", "\\\\r"); clean_string = clean_string.replaceAll("\\t", "\\\\t"); clean_string = clean_string.replaceAll("\\00", "\\\\0"); clean_string = clean_string.replaceAll("'", "\\\\'"); clean_string = clean_string.replaceAll("\\\"", "\\\\\""); if (clean_string.replaceAll("[a-zA-Z0-9_!@#$%^&*()-=+~.;:,\\Q[\\E\\Q]\\E<>{}\\/?\\\\\"' ]", "").length() < 1) { return clean_string; } return str; } public void blankProf() { profPass.setText(""); profPass2.setText(""); profName.setText(""); profCourse.setText(""); profMail.setText(""); } public void blankStud() { studPass.setText(""); studPass2.setText(""); studName.setText(""); studMail.setText(""); } public void blankSign() { signMail.setText(""); signPass.setText(""); } public void onRegisterStud(ActionEvent e) { //runs insertStud String name = addThingies(studName.getText()); String mail = addThingies(studMail.getText()); String pass = studPass.getText(); String pass2 = studPass2.getText(); // are all the fields filled? if (studName.getText().equals("") || studMail.getText().equals("") || studPass.getText().equals("")) { showAlert(Alert.AlertType.WARNING, "You need to fill in all the fields!", "Try Again!"); profPass.setText(""); profPass2.setText(""); return; } //is the password correct? if (!pass.equals(pass2)) { showAlert(Alert.AlertType.WARNING, "Passwords don't match!", "Try Again!"); studPass.setText(""); studPass2.setText(""); return; } pass = addThingies(DigestUtils.sha1Hex(pass)); //in here we check if the email already exists SQLiteJDBC.insertStud(name, mail, pass); blankStud(); } public static void showAlert(Alert.AlertType a , String header , String body) { JavaFXTools.showNotification(header, body, Duration.seconds(5), NotificationType.INFORMATION); // Alert alert = new Alert(a); // if (a == Alert.AlertType.WARNING) { // alert.setTitle("Attention!"); // // } else if (a == Alert.AlertType.INFORMATION) { // alert.setTitle("Success"); // } // alert.setHeaderText(header); // alert.setContentText(body); // alert.showAndWait(); } }
6665_3
package com.example.oddkeys.cointoss; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.util.Locale; import java.util.Random; public class MainActivity extends AppCompatActivity { private static final String STREAK_KEY="STREAK"; private static final String CURRENTSCORE_KEY="CURRENT_SCORE"; private static final String HIGHSCORE_KEY="HIGHSCORE"; private static final String WINLOSS_KEY="WIN"; private static final String TEMP_HIGHSCORE_KEY="TEMP_HIGHSCORE"; private static final String OUTP_KEY="OUTP"; private static final String LANG="LANGUAGE"; private String streak=""; private int currentScore=0; private int highScore=0; private boolean win=false; private String msg=""; String current= Locale.getDefault().getLanguage(); String language= Locale.getDefault().getLanguage(); private String outp=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { streak = savedInstanceState.getString(STREAK_KEY); highScore = savedInstanceState.getInt(HIGHSCORE_KEY); currentScore = savedInstanceState.getInt(CURRENTSCORE_KEY); win=savedInstanceState.getBoolean(WINLOSS_KEY); outp=savedInstanceState.getString(OUTP_KEY); language=savedInstanceState.getString(LANG); current=Locale.getDefault().getLanguage(); if(win==true) currentScore-=1;//μη ξαναμετρησουμε το ++ στην updateScreen() if (!current.equals(language)) { if (current.equals("en")) changeStreak(streak,0); else if (current.equals("el")) changeStreak(streak,1); } updateScreen(); } } @Override protected void onSaveInstanceState(Bundle bundle) { super.onSaveInstanceState(bundle); bundle.putInt(HIGHSCORE_KEY,highScore); bundle.putString(STREAK_KEY,streak); bundle.putInt(CURRENTSCORE_KEY,currentScore); bundle.putBoolean(WINLOSS_KEY,win); bundle.putString(OUTP_KEY,outp); bundle.putString(LANG,language); // bundle.putInt(TEMP_HIGHSCORE_KEY,tempHighScore); } public void changeStreak(String streaksa,int a)//an exeis winstreak kai allakseis glwssa tote de swzetai swsta { int i; String newStreak; if (a==1) { if (!streaksa.isEmpty()) { newStreak=streaksa.replaceAll("H", "Κ"); newStreak=newStreak.replaceAll("T", "Γ"); streak=newStreak; } if(outp.equals("head")) outp="Κορώνα"; else if (outp.equals("tails")) outp="Γράμματα"; } else if (a==0) { if (!streaksa.isEmpty()) { newStreak=streaksa.replaceAll("Κ", "H"); newStreak=newStreak.replaceAll("Γ", "T"); streak=newStreak; } if(outp.equals("Κορώνα")) outp="head"; else if (outp.equals("Γράμματα")) outp="tails"; } } public void cointoss(View view) { Log.v("MainActivity",(String) current); //Log.v("MainActivity", "arxh coin toss"); String choice="heads"; //current=Locale.getDefault().getLanguage(); if (view.getId() == R.id.head) choice = "heads"; if(view.getId()== R.id.tails) choice="tails"; Log.v("MainActivity", "mesh coin toss"); Random rand=new Random(); int x=rand.nextInt(2); Log.v("MainActivity",Integer.toString(x)); if (x==0) { if (current.equals("el")) outp="Κορώνα"; else { if (current.equals("en")) outp = "head"; } if (choice.equals("heads")) { if (current.equals("en")) streak = streak + "H"; else { if (current.equals("el")) streak = streak + "Κ"; } win = true; updateScreen(); } else if (choice.equals("tails")) { win = false; updateScreen(); } } else if(x==1) { if (current.equals("el")) outp="Γράμματα"; else { if (current.equals("en")) outp = "tails"; } if (choice.equals("tails")) { if (current.equals("en")) streak = streak + "T"; else { if (language.equals("el")) streak = streak + "Γ"; } win = true; updateScreen(); } else if (choice.equals("heads")) { win = false; updateScreen(); } } } private void updateScreen() { Log.v("MainActivity", "arxh updatescreen me " +msg); TextView viewStreak=(TextView) findViewById(R.id.streak); TextView viewHighScore= (TextView) findViewById((R.id.highScore)); TextView viewCurrentScore = (TextView) findViewById(R.id.currentScore); TextView viewWinLoss = (TextView) findViewById(R.id.result); current = Locale.getDefault().getLanguage(); if (win) { if (current.equals("el")) msg="Κέρδισες"; else { if (current.equals("en")) msg = "won"; } currentScore++; if(currentScore>highScore)//το ισον το βαλαμε για να καλυπτει το highscore save Instance { highScore=currentScore; } } else {if (current.equals("el")) msg="Έχασες"; else { if (current.equals("en")) msg = "lost"; } currentScore=0; streak=""; } //current = Locale.getDefault().getLanguage(); if (current.equals("en")) viewWinLoss.setText("The result was " + outp + " and you "+msg); else { if (current.equals("el")) viewWinLoss.setText("Το αποτέλεσμα ήταν " + outp + " και " + msg); } language = Locale.getDefault().getLanguage(); viewStreak.setText(streak); viewCurrentScore.setText(Integer.toString(currentScore)); viewHighScore.setText(Integer.toString(highScore)); Log.v("MainActivity", "telos updatescreen"); } }
chatzikodd/androidCointoss
app/src/main/java/com/example/oddkeys/cointoss/MainActivity.java
1,737
//το ισον το βαλαμε για να καλυπτει το highscore save Instance
line_comment
el
package com.example.oddkeys.cointoss; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.util.Locale; import java.util.Random; public class MainActivity extends AppCompatActivity { private static final String STREAK_KEY="STREAK"; private static final String CURRENTSCORE_KEY="CURRENT_SCORE"; private static final String HIGHSCORE_KEY="HIGHSCORE"; private static final String WINLOSS_KEY="WIN"; private static final String TEMP_HIGHSCORE_KEY="TEMP_HIGHSCORE"; private static final String OUTP_KEY="OUTP"; private static final String LANG="LANGUAGE"; private String streak=""; private int currentScore=0; private int highScore=0; private boolean win=false; private String msg=""; String current= Locale.getDefault().getLanguage(); String language= Locale.getDefault().getLanguage(); private String outp=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { streak = savedInstanceState.getString(STREAK_KEY); highScore = savedInstanceState.getInt(HIGHSCORE_KEY); currentScore = savedInstanceState.getInt(CURRENTSCORE_KEY); win=savedInstanceState.getBoolean(WINLOSS_KEY); outp=savedInstanceState.getString(OUTP_KEY); language=savedInstanceState.getString(LANG); current=Locale.getDefault().getLanguage(); if(win==true) currentScore-=1;//μη ξαναμετρησουμε το ++ στην updateScreen() if (!current.equals(language)) { if (current.equals("en")) changeStreak(streak,0); else if (current.equals("el")) changeStreak(streak,1); } updateScreen(); } } @Override protected void onSaveInstanceState(Bundle bundle) { super.onSaveInstanceState(bundle); bundle.putInt(HIGHSCORE_KEY,highScore); bundle.putString(STREAK_KEY,streak); bundle.putInt(CURRENTSCORE_KEY,currentScore); bundle.putBoolean(WINLOSS_KEY,win); bundle.putString(OUTP_KEY,outp); bundle.putString(LANG,language); // bundle.putInt(TEMP_HIGHSCORE_KEY,tempHighScore); } public void changeStreak(String streaksa,int a)//an exeis winstreak kai allakseis glwssa tote de swzetai swsta { int i; String newStreak; if (a==1) { if (!streaksa.isEmpty()) { newStreak=streaksa.replaceAll("H", "Κ"); newStreak=newStreak.replaceAll("T", "Γ"); streak=newStreak; } if(outp.equals("head")) outp="Κορώνα"; else if (outp.equals("tails")) outp="Γράμματα"; } else if (a==0) { if (!streaksa.isEmpty()) { newStreak=streaksa.replaceAll("Κ", "H"); newStreak=newStreak.replaceAll("Γ", "T"); streak=newStreak; } if(outp.equals("Κορώνα")) outp="head"; else if (outp.equals("Γράμματα")) outp="tails"; } } public void cointoss(View view) { Log.v("MainActivity",(String) current); //Log.v("MainActivity", "arxh coin toss"); String choice="heads"; //current=Locale.getDefault().getLanguage(); if (view.getId() == R.id.head) choice = "heads"; if(view.getId()== R.id.tails) choice="tails"; Log.v("MainActivity", "mesh coin toss"); Random rand=new Random(); int x=rand.nextInt(2); Log.v("MainActivity",Integer.toString(x)); if (x==0) { if (current.equals("el")) outp="Κορώνα"; else { if (current.equals("en")) outp = "head"; } if (choice.equals("heads")) { if (current.equals("en")) streak = streak + "H"; else { if (current.equals("el")) streak = streak + "Κ"; } win = true; updateScreen(); } else if (choice.equals("tails")) { win = false; updateScreen(); } } else if(x==1) { if (current.equals("el")) outp="Γράμματα"; else { if (current.equals("en")) outp = "tails"; } if (choice.equals("tails")) { if (current.equals("en")) streak = streak + "T"; else { if (language.equals("el")) streak = streak + "Γ"; } win = true; updateScreen(); } else if (choice.equals("heads")) { win = false; updateScreen(); } } } private void updateScreen() { Log.v("MainActivity", "arxh updatescreen me " +msg); TextView viewStreak=(TextView) findViewById(R.id.streak); TextView viewHighScore= (TextView) findViewById((R.id.highScore)); TextView viewCurrentScore = (TextView) findViewById(R.id.currentScore); TextView viewWinLoss = (TextView) findViewById(R.id.result); current = Locale.getDefault().getLanguage(); if (win) { if (current.equals("el")) msg="Κέρδισες"; else { if (current.equals("en")) msg = "won"; } currentScore++; if(currentScore>highScore)//το ισον<SUF> { highScore=currentScore; } } else {if (current.equals("el")) msg="Έχασες"; else { if (current.equals("en")) msg = "lost"; } currentScore=0; streak=""; } //current = Locale.getDefault().getLanguage(); if (current.equals("en")) viewWinLoss.setText("The result was " + outp + " and you "+msg); else { if (current.equals("el")) viewWinLoss.setText("Το αποτέλεσμα ήταν " + outp + " και " + msg); } language = Locale.getDefault().getLanguage(); viewStreak.setText(streak); viewCurrentScore.setText(Integer.toString(currentScore)); viewHighScore.setText(Integer.toString(highScore)); Log.v("MainActivity", "telos updatescreen"); } }
248_1
import java.util.Random; public class CountSort01 { final static int N = 10_000; static int a[] = new int[N]; public static void main(String[] args) { Random random = new Random(); for (int i = 0; i < N; i++) { a[i] = random.nextInt(2); } // κώδικας που ζητείται να παραλληλοποιηθεί (αρχή) int c = 0; for (int i = 0; i < N; i++) if (a[i] == 0) c++; // κώδικας που ζητείται να παραλληλοποιηθεί (τέλος) for (int i = 0; i < N; i++) if (i < c) a[i] = 0; else a[i] = 1; System.out.printf("The last 0 is at position %d\n", c - 1); } } /* The last 0 is at position 5041 */
chgogos/ceteiep_pdc
archive/exams_preparation/CountSort01.java
303
// κώδικας που ζητείται να παραλληλοποιηθεί (τέλος)
line_comment
el
import java.util.Random; public class CountSort01 { final static int N = 10_000; static int a[] = new int[N]; public static void main(String[] args) { Random random = new Random(); for (int i = 0; i < N; i++) { a[i] = random.nextInt(2); } // κώδικας που ζητείται να παραλληλοποιηθεί (αρχή) int c = 0; for (int i = 0; i < N; i++) if (a[i] == 0) c++; // κώδικας που<SUF> for (int i = 0; i < N; i++) if (i < c) a[i] = 0; else a[i] = 1; System.out.printf("The last 0 is at position %d\n", c - 1); } } /* The last 0 is at position 5041 */
3580_1
public class Example1 { public static void foo(int x) { x++; } public static void bar(MyClass obj) { obj.a++; } public static void main(String[] args) { int x = 5; // μεταβίβαση κατά τιμή foo(x); System.out.println(x); MyClass obj = new MyClass(5); // προσομοίωση μεταβίβασης κατά αναφορά bar(obj); System.out.println(obj.a); } } class MyClass { public int a; public MyClass(int a) { this.a = a; } }
chgogos/dituoi_agp
pl/java/pass_by_value/Example1.java
188
// προσομοίωση μεταβίβασης κατά αναφορά
line_comment
el
public class Example1 { public static void foo(int x) { x++; } public static void bar(MyClass obj) { obj.a++; } public static void main(String[] args) { int x = 5; // μεταβίβαση κατά τιμή foo(x); System.out.println(x); MyClass obj = new MyClass(5); // προσομοίωση μεταβίβασης<SUF> bar(obj); System.out.println(obj.a); } } class MyClass { public int a; public MyClass(int a) { this.a = a; } }
3346_0
package threadsaxample; //δεν εκτελείται ο κώδικας τον καλούμε στο My_Thread public class ThreadRunnable implements Runnable { // Η μέθοδος run υλοποιεί τον κώδικα που θα εκτελεστεί από το νήμα public void run() { // Εκτύπωση μηνύματος όταν το νήμα ξεκινά την εκτέλεσή του System.out.println("Thread is under Running..."); // Βρόγχος που εκτελείται 100 φορές for (int i = 1; i <= 100; i++) { // Εκτύπωση τρέχοντος νήματος, της τιμής του i και της τρέχουσας επανάληψης System.out.println("Thread=" + Thread.currentThread().getName() + " i=" + i); } } }
chitiris/WebProgEce2023
JavaSockets/src/threadsaxample/ThreadRunnable.java
324
//δεν εκτελείται ο κώδικας τον καλούμε στο My_Thread
line_comment
el
package threadsaxample; //δεν εκτελείται<SUF> public class ThreadRunnable implements Runnable { // Η μέθοδος run υλοποιεί τον κώδικα που θα εκτελεστεί από το νήμα public void run() { // Εκτύπωση μηνύματος όταν το νήμα ξεκινά την εκτέλεσή του System.out.println("Thread is under Running..."); // Βρόγχος που εκτελείται 100 φορές for (int i = 1; i <= 100; i++) { // Εκτύπωση τρέχοντος νήματος, της τιμής του i και της τρέχουσας επανάληψης System.out.println("Thread=" + Thread.currentThread().getName() + " i=" + i); } } }
4113_9
import java.util.*; public class AlgorithmInsert { private static HashSet<Integer> levelOverflowStatus = new HashSet<>(/* number of levels of tree */); public static void insert(PointEntry entry) { boolean action = false; LeafNode N = (LeafNode) ChooseSubtree.chooseSubtree(Main.root, entry); if (N.getPointEntries().size() < Main.M) { N.addEntry(entry); return; } if (N.getPointEntries().size() == Main.M) { action = overflowTreatment(N.getLevel()); } if (action) { // if boolean var "action" is true, invoke reinsert reInsert(N, entry); } else { // else invoke split NoLeafNode returnable = AlgorithmSplit.split(N, entry); if (returnable != null) { Main.root = returnable; Main.root.setLevel(((NoLeafNode) Main.root).getRectangleEntries().get(0).getChild().getLevel() + 1); } } } /** * This method decides whether a reinsertion or a split will occur. If true is returned, a reinsertion must happen. * If false is returned, a split must be put into place. * * @param level The level of the node that is being inserted * @return True if reinsertion must be done, false if a split must be done. */ public static boolean overflowTreatment(int level) { // if this level has not been examined yet // hence a reinsertion must occur if (!levelOverflowStatus.contains(level)) { // OT1 levelOverflowStatus.add(level); return true; } return false; } public static void reInsert(Node N, PointEntry pointEntry) { int p = Math.round(0.3f * Main.M); if (N instanceof NoLeafNode currentNode) { LinkedList<RectangleEntryDoublePair> pairs = new LinkedList<>(); for (RectangleEntry entry : currentNode.getRectangleEntries()) { //RI1 double distance = entry.getRectangle().getCenter().distance(currentNode.getParent().getRectangle().getCenter()); RectangleEntryDoublePair pair = new RectangleEntryDoublePair(entry, distance); pairs.add(pair); } pairs.sort(new RectangleEntryDoublePairComparator()); // RI2 List<RectangleEntryDoublePair> trash; trash = pairs.subList(p, pairs.size()); HashSet<PointEntry> temp = new HashSet<>(); for (RectangleEntryDoublePair pair : trash) {// RI4 dfs(pair.getRectangleEntry().getChild(), temp); } for (PointEntry pe : temp) { insert(pe); } } else { // N instance of LeafNode LeafNode currentNode = (LeafNode) N; LinkedList<PointEntryDoublePair> pairs = new LinkedList<>(); for (PointEntry entry : currentNode.getPointEntries()) { //RI1 double distance = entry.getPoint().distance(currentNode.getParent().getRectangle().getCenter()); pairs.add(new PointEntryDoublePair(entry, distance)); } pairs.add(new PointEntryDoublePair(pointEntry, pointEntry.getPoint().distance(currentNode.getParent().getRectangle().getCenter()))); pairs.sort(new PointEntryDoublePairComparator()); //RI2 LinkedList<PointEntryDoublePair> trash = new LinkedList<>(); for (int i = 0; i < p; i++) { trash.add(pairs.pop()); } // Τα στοιχεία που θα μείνουν μέσα στον υπάρχοντα κόμβο LinkedList<PointEntry> pointEntriesTemp = new LinkedList<>(); for (PointEntryDoublePair pair : pairs) { pointEntriesTemp.add(pair.getPointEntry()); } currentNode.update(pointEntriesTemp); RectangleEntry tempRE; // Αν δεν είναι ρίζα, τότε πρέπει να προσαρμόσουμε και τα τετράγωνα των παραπάνων επιπέδων if (!currentNode.isRoot()) { NoLeafNode parentContainer = (NoLeafNode) currentNode.getParent().getContainer(); while (true) { // Φτιάχνουμε έναν εικονικό κόμβο για να υπολογίσουμε το νέο τετράγωνο NoLeafNode tempNode = new NoLeafNode(parentContainer.getRectangleEntries()); tempRE = new RectangleEntry(tempNode); // Προσαρμόζουμε το τετράγωνό του υπάρχοντα κόμβου parentContainer.getParent().getRectangle().setStartPoint(tempRE.getRectangle().getStartPoint()); parentContainer.getParent().getRectangle().setEndPoint(tempRE.getRectangle().getEndPoint()); if (parentContainer.isRoot()) { // Σταματάμε μόλις προσαρμόσουμε και την ρίζα break; } parentContainer = (NoLeafNode) parentContainer.getParent().getContainer(); } } // Call insert() to reinsert the p points into the tree for (PointEntryDoublePair pair : trash) { //RI4 insert(pair.getPointEntry()); } } } public static void dfs(Node root, HashSet<PointEntry> list) { if (!root.leaf) { LinkedList<RectangleEntry> rectangles = ((NoLeafNode) root).getRectangleEntries(); for (RectangleEntry rectangleEntry : rectangles) { dfs(rectangleEntry.getChild(), list); } } else { list.addAll(((LeafNode) root).getPointEntries()); } } private static class RectangleEntryDoublePairComparator implements Comparator<RectangleEntryDoublePair> { @Override public int compare(RectangleEntryDoublePair o, RectangleEntryDoublePair t1) { return Double.compare(o.getValue(), t1.getValue()); } } private static class RectangleEntryDoublePair { private RectangleEntry rectangleEntry; private Double value; // the value of some point public RectangleEntryDoublePair(RectangleEntry rectangleEntry, Double value) { this.rectangleEntry = rectangleEntry; this.value = value; } public RectangleEntry getRectangleEntry() { return rectangleEntry; } public Double getValue() { return value; } } private static class PointEntryDoublePairComparator implements Comparator<PointEntryDoublePair> { @Override public int compare(PointEntryDoublePair o, PointEntryDoublePair t1) { return Double.compare(o.getValue(), t1.getValue()); } } private static class PointEntryDoublePair { private PointEntry pointEntry; private Double value; // the value of some point public PointEntryDoublePair(PointEntry pointEntry, Double value) { this.pointEntry = pointEntry; this.value = value; } public PointEntry getPointEntry() { return pointEntry; } public Double getValue() { return value; } } }
chriszaro/R-star-tree
src/AlgorithmInsert.java
1,695
// Φτιάχνουμε έναν εικονικό κόμβο για να υπολογίσουμε το νέο τετράγωνο
line_comment
el
import java.util.*; public class AlgorithmInsert { private static HashSet<Integer> levelOverflowStatus = new HashSet<>(/* number of levels of tree */); public static void insert(PointEntry entry) { boolean action = false; LeafNode N = (LeafNode) ChooseSubtree.chooseSubtree(Main.root, entry); if (N.getPointEntries().size() < Main.M) { N.addEntry(entry); return; } if (N.getPointEntries().size() == Main.M) { action = overflowTreatment(N.getLevel()); } if (action) { // if boolean var "action" is true, invoke reinsert reInsert(N, entry); } else { // else invoke split NoLeafNode returnable = AlgorithmSplit.split(N, entry); if (returnable != null) { Main.root = returnable; Main.root.setLevel(((NoLeafNode) Main.root).getRectangleEntries().get(0).getChild().getLevel() + 1); } } } /** * This method decides whether a reinsertion or a split will occur. If true is returned, a reinsertion must happen. * If false is returned, a split must be put into place. * * @param level The level of the node that is being inserted * @return True if reinsertion must be done, false if a split must be done. */ public static boolean overflowTreatment(int level) { // if this level has not been examined yet // hence a reinsertion must occur if (!levelOverflowStatus.contains(level)) { // OT1 levelOverflowStatus.add(level); return true; } return false; } public static void reInsert(Node N, PointEntry pointEntry) { int p = Math.round(0.3f * Main.M); if (N instanceof NoLeafNode currentNode) { LinkedList<RectangleEntryDoublePair> pairs = new LinkedList<>(); for (RectangleEntry entry : currentNode.getRectangleEntries()) { //RI1 double distance = entry.getRectangle().getCenter().distance(currentNode.getParent().getRectangle().getCenter()); RectangleEntryDoublePair pair = new RectangleEntryDoublePair(entry, distance); pairs.add(pair); } pairs.sort(new RectangleEntryDoublePairComparator()); // RI2 List<RectangleEntryDoublePair> trash; trash = pairs.subList(p, pairs.size()); HashSet<PointEntry> temp = new HashSet<>(); for (RectangleEntryDoublePair pair : trash) {// RI4 dfs(pair.getRectangleEntry().getChild(), temp); } for (PointEntry pe : temp) { insert(pe); } } else { // N instance of LeafNode LeafNode currentNode = (LeafNode) N; LinkedList<PointEntryDoublePair> pairs = new LinkedList<>(); for (PointEntry entry : currentNode.getPointEntries()) { //RI1 double distance = entry.getPoint().distance(currentNode.getParent().getRectangle().getCenter()); pairs.add(new PointEntryDoublePair(entry, distance)); } pairs.add(new PointEntryDoublePair(pointEntry, pointEntry.getPoint().distance(currentNode.getParent().getRectangle().getCenter()))); pairs.sort(new PointEntryDoublePairComparator()); //RI2 LinkedList<PointEntryDoublePair> trash = new LinkedList<>(); for (int i = 0; i < p; i++) { trash.add(pairs.pop()); } // Τα στοιχεία που θα μείνουν μέσα στον υπάρχοντα κόμβο LinkedList<PointEntry> pointEntriesTemp = new LinkedList<>(); for (PointEntryDoublePair pair : pairs) { pointEntriesTemp.add(pair.getPointEntry()); } currentNode.update(pointEntriesTemp); RectangleEntry tempRE; // Αν δεν είναι ρίζα, τότε πρέπει να προσαρμόσουμε και τα τετράγωνα των παραπάνων επιπέδων if (!currentNode.isRoot()) { NoLeafNode parentContainer = (NoLeafNode) currentNode.getParent().getContainer(); while (true) { // Φτιάχνουμε έναν<SUF> NoLeafNode tempNode = new NoLeafNode(parentContainer.getRectangleEntries()); tempRE = new RectangleEntry(tempNode); // Προσαρμόζουμε το τετράγωνό του υπάρχοντα κόμβου parentContainer.getParent().getRectangle().setStartPoint(tempRE.getRectangle().getStartPoint()); parentContainer.getParent().getRectangle().setEndPoint(tempRE.getRectangle().getEndPoint()); if (parentContainer.isRoot()) { // Σταματάμε μόλις προσαρμόσουμε και την ρίζα break; } parentContainer = (NoLeafNode) parentContainer.getParent().getContainer(); } } // Call insert() to reinsert the p points into the tree for (PointEntryDoublePair pair : trash) { //RI4 insert(pair.getPointEntry()); } } } public static void dfs(Node root, HashSet<PointEntry> list) { if (!root.leaf) { LinkedList<RectangleEntry> rectangles = ((NoLeafNode) root).getRectangleEntries(); for (RectangleEntry rectangleEntry : rectangles) { dfs(rectangleEntry.getChild(), list); } } else { list.addAll(((LeafNode) root).getPointEntries()); } } private static class RectangleEntryDoublePairComparator implements Comparator<RectangleEntryDoublePair> { @Override public int compare(RectangleEntryDoublePair o, RectangleEntryDoublePair t1) { return Double.compare(o.getValue(), t1.getValue()); } } private static class RectangleEntryDoublePair { private RectangleEntry rectangleEntry; private Double value; // the value of some point public RectangleEntryDoublePair(RectangleEntry rectangleEntry, Double value) { this.rectangleEntry = rectangleEntry; this.value = value; } public RectangleEntry getRectangleEntry() { return rectangleEntry; } public Double getValue() { return value; } } private static class PointEntryDoublePairComparator implements Comparator<PointEntryDoublePair> { @Override public int compare(PointEntryDoublePair o, PointEntryDoublePair t1) { return Double.compare(o.getValue(), t1.getValue()); } } private static class PointEntryDoublePair { private PointEntry pointEntry; private Double value; // the value of some point public PointEntryDoublePair(PointEntry pointEntry, Double value) { this.pointEntry = pointEntry; this.value = value; } public PointEntry getPointEntry() { return pointEntry; } public Double getValue() { return value; } } }
1943_22
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.codingelab.validation.languages; import com.codingelab.validation.errors.Error; import com.codingelab.validation.errors.ErrorType; /** * @author Τρύφων Θεοδώρου * @author Abdulrahman Abdulhamid Alsaedi * @since 1.0.1 */ class Greek implements Language{ @Override public String getVariable() { return "Στο πεδίο εισαγωγής"; } @Override public String translate(Error error) { int number=error.getErrorNumber(); switch (number) { /*Length Errors(from 0 to 255)*/ case 1://Length not equal int num=(int)error.get(); String digit=num>1?"χαρακτήρες":"χαρακτήρας"; return getVariable()+" το μήκος πρέπει να είναι ίσο με "+num+" "+digit; case 2://Length below minimum limit int limit=(int)error.get(); digit=limit>1?"χαρακτήρες":"χαρακτήρας"; return getVariable()+" το μήκος δεν μπορεί να είναι μικρότερο από "+limit+" "+digit; case 3://Length above maximum limit limit=(int)error.get(); digit=limit>1?"χαρακτήρες":"χαρακτήρας"; return getVariable()+" το μήκος δεν μπορεί να είναι μεγαλύτερο από "+limit+" "+digit; case 4://length not between int [] between=(int [])error.get(); return getVariable()+ " το μήκος πρέπει να είναι μεταξύ των ορίων από: " +between[0]+" έως "+between[1]+" χαρακτήρες"; case 5://length between between=(int [])error.get(); return getVariable()+ " το μήκος πρέπει να είναι εκτός των ορίων από: " +between[0]+" έως "+between[1]+" χαρακτήρες"; case 6://length not equal to one of int [] allLengths=(int [])error.get(); String numbers=Integer.toString(allLengths[0]); if(allLengths.length==2) numbers+=" ή "+allLengths[1]; else if(allLengths.length>2){ for(int i=1;i<allLengths.length-1;i++) numbers+=", "+allLengths[i]; numbers+=" ή "+allLengths[allLengths.length-1]; } if(allLengths.length==1) return getVariable()+" το μήκος πρέπει να είναι ίσο με "+numbers; return getVariable()+" το μήκος πρέπει να είναι ίσο με ένα από τα παρακάτω νούμερα: "+numbers; /*Main Errors(from 256 to 1024)*/ case 256://Empty input return getVariable()+" δεν επιτρέπεται να είναι κενό"; case 257://Has letters return getVariable()+" δεν επιτρέπεται να περιέχει γράμματα"; case 258://Has letters in range String range=(String)error.get(); return getVariable()+" δεν επιτρέπεται να περιέχει γράμματα στην περιοχή: "+range; case 259://Has letters out range range=(String)error.get(); return getVariable()+" δεν επιτρέπεται να περιέχει γράμματα έξω από την περιοχή: "+range; case 260://Required more letters num=(int)error.get(); digit=num>1?"χαρακτήρες":"χαρακτήρας"; return getVariable()+" απαιτούνται τουλάχιστον "+num+" "+digit; case 261://Has numbers return getVariable()+" δεν επιτρέπονται αριθμοί"; case 262://Has numbers in range range=(String)error.get(); return getVariable()+" δεν επιτρέπονται αριθμοί στην περιοχή: "+range; case 263://Has numbers out range range=(String)error.get(); return getVariable()+" δεν επιτρέπονται αριθμοί έξω από την περιοχή: "+range; case 264://Required more numbers num=(int)error.get(); digit=num>1?"αριθμοί":"αριθμός"; return getVariable()+" απαιτούνται τουλάχιστον"+num+" "+digit; case 265://Has special characters return getVariable()+" δεν επιτρέπονται ειδικοί χαρακτήρες"; case 266://Has special characters in range range=(String)error.get(); return getVariable()+" δεν επιτρέπονται ειδικοί χαρακτήρες την περιοχή: "+range; case 267://Has special characters out range range=(String)error.get(); return getVariable()+" δεν επιτρέπονται ειδικοί χαρακτήρες έξω από την περιοχή: "+range; case 268://Required more special characters num=(int)error.get(); digit=num>1?"ειδικοί χαρακτήρες":"ειδικός χαρακτήρας"; return getVariable()+" απαιτούνται "+num+" "+digit; case 269://Has white spaces return getVariable()+" δεν επιτρέπονται κενά (white spaces)"; case 270://Has white spaces out range return getVariable()+" επιτρέπεται μόνο ένα από τα (white spaces)"; case 301:return "Άκυρη διεύθυνση ηλεκτρονικού ταχυδρομείου"; case 302:return "Ο πρώτος χαρακτήρας πρέπει να είναι είτε γράμμα ή αριθμός"; case 303:return "Κάθε email έχει ένα όνομα. Όπως: example@"; case 304:return "Το email δεν μπορεί να τελειώνει με τελεία(.)"; case 305:return "Διαδοχική τελείες δεν επιτρέπονται"; case 306:return "Κάθε email έχει ένα @ symbol"; case 307:return "Κάθε email έχει μόνο ένα @ symbol"; case 308:return "Κάθε email έχει ένα όνομα τομέα. π.χ. \"@gmail\""; case 309:return "Το όνομα τομέα αποτελείται από γράμματα και αριθμούς μόνο. π.χ. \"@gmail\""; case 310:return "Κάθε email έχει ένα Top Level τομέα. π.χ. \".com\""; // case 311:return "Άκυρο όνομα Top Level τομέα. Έγκυρο π.χ. \".com\""; // case 312:return "Άκυρο όνομα Sup-Level τομέα. Έγκυρο π.χ. \".com.gr\""; case 313:return "Άκυρο όνομα Top Level τομέα. Για παράδειγμα \".com.gr\""; } return ""; } }
codingelab/codingelab-validation
src/main/java/com/codingelab/validation/languages/Greek.java
2,707
// case 312:return "Άκυρο όνομα Sup-Level τομέα. Έγκυρο π.χ. \".com.gr\"";
line_comment
el
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.codingelab.validation.languages; import com.codingelab.validation.errors.Error; import com.codingelab.validation.errors.ErrorType; /** * @author Τρύφων Θεοδώρου * @author Abdulrahman Abdulhamid Alsaedi * @since 1.0.1 */ class Greek implements Language{ @Override public String getVariable() { return "Στο πεδίο εισαγωγής"; } @Override public String translate(Error error) { int number=error.getErrorNumber(); switch (number) { /*Length Errors(from 0 to 255)*/ case 1://Length not equal int num=(int)error.get(); String digit=num>1?"χαρακτήρες":"χαρακτήρας"; return getVariable()+" το μήκος πρέπει να είναι ίσο με "+num+" "+digit; case 2://Length below minimum limit int limit=(int)error.get(); digit=limit>1?"χαρακτήρες":"χαρακτήρας"; return getVariable()+" το μήκος δεν μπορεί να είναι μικρότερο από "+limit+" "+digit; case 3://Length above maximum limit limit=(int)error.get(); digit=limit>1?"χαρακτήρες":"χαρακτήρας"; return getVariable()+" το μήκος δεν μπορεί να είναι μεγαλύτερο από "+limit+" "+digit; case 4://length not between int [] between=(int [])error.get(); return getVariable()+ " το μήκος πρέπει να είναι μεταξύ των ορίων από: " +between[0]+" έως "+between[1]+" χαρακτήρες"; case 5://length between between=(int [])error.get(); return getVariable()+ " το μήκος πρέπει να είναι εκτός των ορίων από: " +between[0]+" έως "+between[1]+" χαρακτήρες"; case 6://length not equal to one of int [] allLengths=(int [])error.get(); String numbers=Integer.toString(allLengths[0]); if(allLengths.length==2) numbers+=" ή "+allLengths[1]; else if(allLengths.length>2){ for(int i=1;i<allLengths.length-1;i++) numbers+=", "+allLengths[i]; numbers+=" ή "+allLengths[allLengths.length-1]; } if(allLengths.length==1) return getVariable()+" το μήκος πρέπει να είναι ίσο με "+numbers; return getVariable()+" το μήκος πρέπει να είναι ίσο με ένα από τα παρακάτω νούμερα: "+numbers; /*Main Errors(from 256 to 1024)*/ case 256://Empty input return getVariable()+" δεν επιτρέπεται να είναι κενό"; case 257://Has letters return getVariable()+" δεν επιτρέπεται να περιέχει γράμματα"; case 258://Has letters in range String range=(String)error.get(); return getVariable()+" δεν επιτρέπεται να περιέχει γράμματα στην περιοχή: "+range; case 259://Has letters out range range=(String)error.get(); return getVariable()+" δεν επιτρέπεται να περιέχει γράμματα έξω από την περιοχή: "+range; case 260://Required more letters num=(int)error.get(); digit=num>1?"χαρακτήρες":"χαρακτήρας"; return getVariable()+" απαιτούνται τουλάχιστον "+num+" "+digit; case 261://Has numbers return getVariable()+" δεν επιτρέπονται αριθμοί"; case 262://Has numbers in range range=(String)error.get(); return getVariable()+" δεν επιτρέπονται αριθμοί στην περιοχή: "+range; case 263://Has numbers out range range=(String)error.get(); return getVariable()+" δεν επιτρέπονται αριθμοί έξω από την περιοχή: "+range; case 264://Required more numbers num=(int)error.get(); digit=num>1?"αριθμοί":"αριθμός"; return getVariable()+" απαιτούνται τουλάχιστον"+num+" "+digit; case 265://Has special characters return getVariable()+" δεν επιτρέπονται ειδικοί χαρακτήρες"; case 266://Has special characters in range range=(String)error.get(); return getVariable()+" δεν επιτρέπονται ειδικοί χαρακτήρες την περιοχή: "+range; case 267://Has special characters out range range=(String)error.get(); return getVariable()+" δεν επιτρέπονται ειδικοί χαρακτήρες έξω από την περιοχή: "+range; case 268://Required more special characters num=(int)error.get(); digit=num>1?"ειδικοί χαρακτήρες":"ειδικός χαρακτήρας"; return getVariable()+" απαιτούνται "+num+" "+digit; case 269://Has white spaces return getVariable()+" δεν επιτρέπονται κενά (white spaces)"; case 270://Has white spaces out range return getVariable()+" επιτρέπεται μόνο ένα από τα (white spaces)"; case 301:return "Άκυρη διεύθυνση ηλεκτρονικού ταχυδρομείου"; case 302:return "Ο πρώτος χαρακτήρας πρέπει να είναι είτε γράμμα ή αριθμός"; case 303:return "Κάθε email έχει ένα όνομα. Όπως: example@"; case 304:return "Το email δεν μπορεί να τελειώνει με τελεία(.)"; case 305:return "Διαδοχική τελείες δεν επιτρέπονται"; case 306:return "Κάθε email έχει ένα @ symbol"; case 307:return "Κάθε email έχει μόνο ένα @ symbol"; case 308:return "Κάθε email έχει ένα όνομα τομέα. π.χ. \"@gmail\""; case 309:return "Το όνομα τομέα αποτελείται από γράμματα και αριθμούς μόνο. π.χ. \"@gmail\""; case 310:return "Κάθε email έχει ένα Top Level τομέα. π.χ. \".com\""; // case 311:return "Άκυρο όνομα Top Level τομέα. Έγκυρο π.χ. \".com\""; // case 312:return<SUF> case 313:return "Άκυρο όνομα Top Level τομέα. Για παράδειγμα \".com.gr\""; } return ""; } }
24875_23
package com.java.main.i_tefteri; import android.accounts.Account; import android.app.Activity; import android.app.LauncherActivity; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteTableLockedException; import android.icu.util.Currency; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.RadioButton; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class AccountActivity extends AppCompatActivity { private List<MyAccounts> Accounts=new ArrayList<>(); private ListView AccountList; private CheckBox My_Check; int SelectedItem=-1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_account); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); AccountList = (ListView) findViewById(R.id.AccountList); FillAccount2List(); Button AccountButton = (Button) findViewById(R.id.Account_button); AccountButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mySelectAccount(); } }); Accounts.add(new MyAccounts("1111111111111",100.10)); Accounts.add(new MyAccounts("2222222222222",200.20)); // ArrayAdapter<MyAccounts> AccountsAdapter = new ArrayAdapter<MyAccounts>( // this, // android.R.layout.simple_list_item_checked, // Accounts); ListAdapter AccountsAdapter = new ListAdapter(this, android.R.layout.simple_list_item_1, Accounts); AccountList.setItemsCanFocus(false); AccountList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); AccountList.setAdapter(AccountsAdapter); AccountList.setItemsCanFocus(false); AccountList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // AccountList.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if(SelectedItem!=-1){ // My_Check.setChecked(false); // // CheckBox My1=(CheckBox) AccountList.getItemAtPosition(SelectedItem); // // My1.setChecked(true); // } // } // }); // MyCheck.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() { // @Override // public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // //// buttonView.setChecked(isChecked); // } // // // }); } // @Override // public void onClick(View v) { // /* this returns the checked item positions in the listview*/ // //ArrayList<MyAccounts> itempositions=.getcheckeditemcount(); // if(SelectedItem!=-1){ // My_Check.setChecked(false); // // CheckBox My1=(CheckBox) AccountList.getItemAtPosition(SelectedItem); // // My1.setChecked(true); // } // for(long i:AccountList.getCheckItemIds()) // { // /* This is the main part...u can retrieve the object in the listview which is checked and do further calculations with it*/ // AccountList.getId(i) // // } // private void CheckTheCorrect(){ // ((CheckBox) findViewById(R.id.Check)).setChecked(false); // for(int i=0; i<=((CheckBox) findViewById(R.id.Check)).length();i++) // if(i==SelectedItem){ // ((CheckBox) findViewById(R.id.Check)).setChecked(true); // } // // } private void FillAccount2List(){ // // Toast.makeText(this, AccountList.getChoiceMode(), // Toast.LENGTH_LONG).show(); } private void mySelectAccount(){ if(SelectedItem==-1){ Toast.makeText(getApplicationContext(),"Θα πρέπει πρώτα να διαλέξετε ένα Λογαριασμό", Toast.LENGTH_SHORT).show(); } else{ MyAccounts SelectedAccount=(MyAccounts)AccountList.getAdapter().getItem(SelectedItem); //Toast.makeText(getApplicationContext(), SelectedAccount.GetAccount_no(), Toast.LENGTH_SHORT).show(); Intent mainIntent = new Intent(this,MainActivity.class); startActivity(mainIntent); AccountActivity.this.finish(); } // //RadioButton Account1=(RadioButton) findViewById(R.id.radio0); // //RadioButton Account2=(RadioButton) findViewById(R.id.radio1); // String MyAccount_No=""; // SparseBooleanArray checked = AccountList.getCheckedItemPositions(); // for (int i = 0; i < AccountList.getAdapter().getCount(); i++) { // TableRow MyRow=(TableRow) AccountList.getChildAt(i); // CheckBox Check=(CheckBox) MyRow.getChildAt(0); // if (Check.isChecked()) { // MyAccounts tag = (MyAccounts) AccountList.getItemAtPosition(i); // // String selectedName=tag.GetAccount_no(); // Toast.makeText(getApplicationContext(), selectedName, Toast.LENGTH_SHORT).show(); // } // } //Toast.makeText(this, MyAccount_No,Toast.LENGTH_LONG).show(); // if(Account1.isChecked()==false && Account2.isChecked()==false){ // Toast.makeText(this, "Θα πρέπει πρώτα να διαλέξετε ένα Λογαριασμό", // Toast.LENGTH_LONG).show(); // } // else{ // Intent MainIntent = new Intent(this,MainActivity.class); // startActivity(MainIntent); // AccountActivity.this.finish(); // } } public class ListAdapter extends ArrayAdapter<MyAccounts> { Context MyContext; public ListAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } public ListAdapter(Context context, int resource, List<MyAccounts> items) { super(context, resource, items); MyContext=context; } // @Override // public View getBind() @Override public View getView(final int position, View convertView, ViewGroup parent) { String euro = "\u20ac"; final int pos=position; View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.contentaccount, null); } MyAccounts p = getItem(position); if (p != null) { final CheckBox MyCheck=(CheckBox) v.findViewById(R.id.Check); TextView tt1 = (TextView) v.findViewById(R.id.Account_no); TextView tt2 = (TextView) v.findViewById(R.id.Balance); // TextView tt3 = (TextView) v.findViewById(R.id.description); //MyCheck.setChecked(false); MyCheck.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TableLayout tblGrid = new TableLayout(getBaseContext()); //MyCheck.setChecked(false); SelectedItem=position; CheckBox Check2; // for(int i=0;i<=AccountList.getCount()-1;i++){ // if(i!=position) { // Check2 = (CheckBox) AccountList.getChildAt(i).findViewById(R.id.Check); // Check2.setChecked(false); // Check2 = null; // } // } //MyCheck.setChecked(false); //for(int i=0;i<=AccountList.getCount()-1;i++){ //if(i==position) { //Check2 = (CheckBox) AccountList.getChildAt(0).findViewById(R.id.Check); //Check2.setChecked(false); //Check2 = null; //} //} //CheckBox Check1 =(CheckBox) AccountList.getChildAt(position).findViewById(R.id.Check); //Check1.setChecked(true); //CheckBox chbSeleccion = new CheckBox(getBaseContext()); //chbSeleccion.setChecked(false); //for(int i=0;i<=AccountList.getCount();i++){ // CheckBox m1=(CheckBox) MyRow.getChildAt(i).findViewById(R.id.Check); // m1.setChecked(false); //} } }); // MyCheck.setOnClickListener(new CheckBox.setOnClickListener() { // // // // // MyCheck.setChecked(false); // // CheckBox My1=(CheckBox) AccountList.getItemAtPosition(SelectedItem); // // My1.setChecked(true); // // );); //MyCheck // if(SelectedItem!=-1) // MyNotify(SelectedItem); // for (int i = 0; i < AccountList.getAdapter().getCount(); i++) { // AccountList.getAdapter().getItem(0); // // } if (tt1 != null) { tt1.setText(p.GetAccount_no()); } if (tt2 != null) { tt2.setText(String.valueOf(p.GetAccount_balance())+ euro); } // if (tt3 != null) { // tt3.setText(p.getDescription()); // } } // TableRow MyTable=(TableRow) v.findViewById(R.id.TableRow01); // MyCheck.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // //MyCheck.setChecked(false); // for(int i=0; i < AccountList.getCount(); i++){ //// if(SelectedItem==i) //// AccountList.setItemChecked(i, true); //// else // AccountList.setItemChecked(i, false); // } //// CheckBox myCheck=(CheckBox) AccountList.getSelectedItem(); //// //// myCheck.setChecked(true); // //SelectedItem = pos; // // } // // // }); // AccountList.setOnItemClickListener(new AdapterView.OnItemClickListener() { // @Override // public void onItemClick(AdapterView<?> arg0, View v, int position, // long id) { // for(int i=0; i < AccountList.getCount(); i++){ //// if(SelectedItem==i) //// AccountList.setItemChecked(i, true); //// else // AccountList.setItemChecked(i, false); // } // } // }); TableLayout MyTable=(TableLayout) v.findViewById(R.id.MyTable); TableRow MyRow1; //for(int i=0;i<=MyTable.getChildCount();i++){ MyRow1=(TableRow) MyTable.getChildAt(0); MyRow1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBox Check1=(CheckBox) v; Check1.setChecked(false); } }); //} TableRow MyRow2; //for(int i=0;i<=MyTable.getChildCount();i++){ MyRow2=(TableRow) MyTable.getChildAt(0); MyRow2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBox Check1=(CheckBox) v; Check1.setChecked(false); } }); //} //MyTable.setClickable(true); // MyTable.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // for(int i=0;i<= MyTable.getChildCount();i++) { // TableRow MyRow = (TableRow) MyTable.getChildAt(i); // CheckBox Check1 = (CheckBox) MyRow.getChildAt(0); // Check1.setChecked(false); // //TableRow t = (TableRow) View; // //CheckBox Check1=(CheckBox) t.getChildAt(0); // //Check1.setChecked(false); // //TextView firstTextView = (TextView) t.getChildAt(0); // //TextView secondTextView = (TextView) t.getChildAt(1); // //String firstText = firstTextView.getText().toString(); // //String secondText = secondTextView.getText().toString(); // } // } // }); return v; //final CheckBox MyCheck=(CheckBox) findViewById(R.id.Check); } } private class MyAccounts{ private String _Account_no; private double _Account_balance; public MyAccounts(String AccNo,double Balance){ _Account_no=AccNo; _Account_balance=Balance; } public String GetAccount_no(){ return _Account_no; } public void SetAccount_no(String value){ _Account_no=value; } public double GetAccount_balance(){ return _Account_balance; } public void SetAccount_no(double value){ _Account_balance=value; } } }
crowdhackathon-fintech2/I-TEFTERI
Android_App/i_Tefteri/i_Tefteri/app/src/main/java/com/java/main/i_tefteri/AccountActivity.java
3,385
// Toast.makeText(this, "Θα πρέπει πρώτα να διαλέξετε ένα Λογαριασμό",
line_comment
el
package com.java.main.i_tefteri; import android.accounts.Account; import android.app.Activity; import android.app.LauncherActivity; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteTableLockedException; import android.icu.util.Currency; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.RadioButton; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class AccountActivity extends AppCompatActivity { private List<MyAccounts> Accounts=new ArrayList<>(); private ListView AccountList; private CheckBox My_Check; int SelectedItem=-1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_account); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); AccountList = (ListView) findViewById(R.id.AccountList); FillAccount2List(); Button AccountButton = (Button) findViewById(R.id.Account_button); AccountButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mySelectAccount(); } }); Accounts.add(new MyAccounts("1111111111111",100.10)); Accounts.add(new MyAccounts("2222222222222",200.20)); // ArrayAdapter<MyAccounts> AccountsAdapter = new ArrayAdapter<MyAccounts>( // this, // android.R.layout.simple_list_item_checked, // Accounts); ListAdapter AccountsAdapter = new ListAdapter(this, android.R.layout.simple_list_item_1, Accounts); AccountList.setItemsCanFocus(false); AccountList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); AccountList.setAdapter(AccountsAdapter); AccountList.setItemsCanFocus(false); AccountList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // AccountList.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if(SelectedItem!=-1){ // My_Check.setChecked(false); // // CheckBox My1=(CheckBox) AccountList.getItemAtPosition(SelectedItem); // // My1.setChecked(true); // } // } // }); // MyCheck.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() { // @Override // public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // //// buttonView.setChecked(isChecked); // } // // // }); } // @Override // public void onClick(View v) { // /* this returns the checked item positions in the listview*/ // //ArrayList<MyAccounts> itempositions=.getcheckeditemcount(); // if(SelectedItem!=-1){ // My_Check.setChecked(false); // // CheckBox My1=(CheckBox) AccountList.getItemAtPosition(SelectedItem); // // My1.setChecked(true); // } // for(long i:AccountList.getCheckItemIds()) // { // /* This is the main part...u can retrieve the object in the listview which is checked and do further calculations with it*/ // AccountList.getId(i) // // } // private void CheckTheCorrect(){ // ((CheckBox) findViewById(R.id.Check)).setChecked(false); // for(int i=0; i<=((CheckBox) findViewById(R.id.Check)).length();i++) // if(i==SelectedItem){ // ((CheckBox) findViewById(R.id.Check)).setChecked(true); // } // // } private void FillAccount2List(){ // // Toast.makeText(this, AccountList.getChoiceMode(), // Toast.LENGTH_LONG).show(); } private void mySelectAccount(){ if(SelectedItem==-1){ Toast.makeText(getApplicationContext(),"Θα πρέπει πρώτα να διαλέξετε ένα Λογαριασμό", Toast.LENGTH_SHORT).show(); } else{ MyAccounts SelectedAccount=(MyAccounts)AccountList.getAdapter().getItem(SelectedItem); //Toast.makeText(getApplicationContext(), SelectedAccount.GetAccount_no(), Toast.LENGTH_SHORT).show(); Intent mainIntent = new Intent(this,MainActivity.class); startActivity(mainIntent); AccountActivity.this.finish(); } // //RadioButton Account1=(RadioButton) findViewById(R.id.radio0); // //RadioButton Account2=(RadioButton) findViewById(R.id.radio1); // String MyAccount_No=""; // SparseBooleanArray checked = AccountList.getCheckedItemPositions(); // for (int i = 0; i < AccountList.getAdapter().getCount(); i++) { // TableRow MyRow=(TableRow) AccountList.getChildAt(i); // CheckBox Check=(CheckBox) MyRow.getChildAt(0); // if (Check.isChecked()) { // MyAccounts tag = (MyAccounts) AccountList.getItemAtPosition(i); // // String selectedName=tag.GetAccount_no(); // Toast.makeText(getApplicationContext(), selectedName, Toast.LENGTH_SHORT).show(); // } // } //Toast.makeText(this, MyAccount_No,Toast.LENGTH_LONG).show(); // if(Account1.isChecked()==false && Account2.isChecked()==false){ // Toast.makeText(this, "Θα<SUF> // Toast.LENGTH_LONG).show(); // } // else{ // Intent MainIntent = new Intent(this,MainActivity.class); // startActivity(MainIntent); // AccountActivity.this.finish(); // } } public class ListAdapter extends ArrayAdapter<MyAccounts> { Context MyContext; public ListAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } public ListAdapter(Context context, int resource, List<MyAccounts> items) { super(context, resource, items); MyContext=context; } // @Override // public View getBind() @Override public View getView(final int position, View convertView, ViewGroup parent) { String euro = "\u20ac"; final int pos=position; View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.contentaccount, null); } MyAccounts p = getItem(position); if (p != null) { final CheckBox MyCheck=(CheckBox) v.findViewById(R.id.Check); TextView tt1 = (TextView) v.findViewById(R.id.Account_no); TextView tt2 = (TextView) v.findViewById(R.id.Balance); // TextView tt3 = (TextView) v.findViewById(R.id.description); //MyCheck.setChecked(false); MyCheck.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TableLayout tblGrid = new TableLayout(getBaseContext()); //MyCheck.setChecked(false); SelectedItem=position; CheckBox Check2; // for(int i=0;i<=AccountList.getCount()-1;i++){ // if(i!=position) { // Check2 = (CheckBox) AccountList.getChildAt(i).findViewById(R.id.Check); // Check2.setChecked(false); // Check2 = null; // } // } //MyCheck.setChecked(false); //for(int i=0;i<=AccountList.getCount()-1;i++){ //if(i==position) { //Check2 = (CheckBox) AccountList.getChildAt(0).findViewById(R.id.Check); //Check2.setChecked(false); //Check2 = null; //} //} //CheckBox Check1 =(CheckBox) AccountList.getChildAt(position).findViewById(R.id.Check); //Check1.setChecked(true); //CheckBox chbSeleccion = new CheckBox(getBaseContext()); //chbSeleccion.setChecked(false); //for(int i=0;i<=AccountList.getCount();i++){ // CheckBox m1=(CheckBox) MyRow.getChildAt(i).findViewById(R.id.Check); // m1.setChecked(false); //} } }); // MyCheck.setOnClickListener(new CheckBox.setOnClickListener() { // // // // // MyCheck.setChecked(false); // // CheckBox My1=(CheckBox) AccountList.getItemAtPosition(SelectedItem); // // My1.setChecked(true); // // );); //MyCheck // if(SelectedItem!=-1) // MyNotify(SelectedItem); // for (int i = 0; i < AccountList.getAdapter().getCount(); i++) { // AccountList.getAdapter().getItem(0); // // } if (tt1 != null) { tt1.setText(p.GetAccount_no()); } if (tt2 != null) { tt2.setText(String.valueOf(p.GetAccount_balance())+ euro); } // if (tt3 != null) { // tt3.setText(p.getDescription()); // } } // TableRow MyTable=(TableRow) v.findViewById(R.id.TableRow01); // MyCheck.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // //MyCheck.setChecked(false); // for(int i=0; i < AccountList.getCount(); i++){ //// if(SelectedItem==i) //// AccountList.setItemChecked(i, true); //// else // AccountList.setItemChecked(i, false); // } //// CheckBox myCheck=(CheckBox) AccountList.getSelectedItem(); //// //// myCheck.setChecked(true); // //SelectedItem = pos; // // } // // // }); // AccountList.setOnItemClickListener(new AdapterView.OnItemClickListener() { // @Override // public void onItemClick(AdapterView<?> arg0, View v, int position, // long id) { // for(int i=0; i < AccountList.getCount(); i++){ //// if(SelectedItem==i) //// AccountList.setItemChecked(i, true); //// else // AccountList.setItemChecked(i, false); // } // } // }); TableLayout MyTable=(TableLayout) v.findViewById(R.id.MyTable); TableRow MyRow1; //for(int i=0;i<=MyTable.getChildCount();i++){ MyRow1=(TableRow) MyTable.getChildAt(0); MyRow1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBox Check1=(CheckBox) v; Check1.setChecked(false); } }); //} TableRow MyRow2; //for(int i=0;i<=MyTable.getChildCount();i++){ MyRow2=(TableRow) MyTable.getChildAt(0); MyRow2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBox Check1=(CheckBox) v; Check1.setChecked(false); } }); //} //MyTable.setClickable(true); // MyTable.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // for(int i=0;i<= MyTable.getChildCount();i++) { // TableRow MyRow = (TableRow) MyTable.getChildAt(i); // CheckBox Check1 = (CheckBox) MyRow.getChildAt(0); // Check1.setChecked(false); // //TableRow t = (TableRow) View; // //CheckBox Check1=(CheckBox) t.getChildAt(0); // //Check1.setChecked(false); // //TextView firstTextView = (TextView) t.getChildAt(0); // //TextView secondTextView = (TextView) t.getChildAt(1); // //String firstText = firstTextView.getText().toString(); // //String secondText = secondTextView.getText().toString(); // } // } // }); return v; //final CheckBox MyCheck=(CheckBox) findViewById(R.id.Check); } } private class MyAccounts{ private String _Account_no; private double _Account_balance; public MyAccounts(String AccNo,double Balance){ _Account_no=AccNo; _Account_balance=Balance; } public String GetAccount_no(){ return _Account_no; } public void SetAccount_no(String value){ _Account_no=value; } public double GetAccount_balance(){ return _Account_balance; } public void SetAccount_no(double value){ _Account_balance=value; } } }
27459_36
package com.example.kostis.spaceprk; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Handler; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import com.facebook.login.LoginBehavior; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.intertech.customviews.MotoSelector; import com.intertech.customviews.ValueSelector; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends AppCompatActivity { CallbackManager callbackManager; MainActivity ctx=this; User user; int small_Vehicles=0,big_Vehicles=0,medium_Vehicles=0; ViewDialog alert; ValueSelector valueSelector; MotoSelector motoSelector; public int carNum=0 ,motoNum=0,temp=0; public String carN,motoN; public static final String PREFS_NAME = "MyPrefsFile"; public static final String PREFS_NAME2 = "MyPrefsFile2"; public static final String DEFAULT="N/A"; String savedname, savedsmall,savedlastname,savedemail, savedmedium, savedbig,savedpay,savedfree; private static final int PERMISSION_ACCESS_COARSE_LOCATION = 1; private static final int PERMISSION_ACCESS_FINE_LOCATION = 1; public String ename,eemail,epassword; EditText etName,etPassword,etMail; //-------------------On Create @Override protected void onCreate(final Bundle savedInstanceState) { FacebookSdk.sdkInitialize(getApplicationContext()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //check if the user loged in before and saved prefereces................................. savedpay="no"; savedfree="free"; //loadData(); //ελεγχος αν έχει χρησιμοποιηση ξανα ο χρηστης και αποθυκευτικαν τα στοιχεια του ///Request permissio for API 24 and higher/////////// if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_ACCESS_COARSE_LOCATION); } if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_ACCESS_FINE_LOCATION); } /////End ask permission///////////////////////// alert = new ViewDialog(); valueSelector = (ValueSelector) findViewById(R.id.valueSelector); valueSelector.setMinValue(0); valueSelector.setMaxValue(10); motoSelector = (MotoSelector) findViewById(R.id.motoSelector); motoSelector.setMinValue(0); motoSelector.setMaxValue(10); //get a reference to the textview on the log.xml file. ImageView email= (ImageView)findViewById(R.id.email_image); email.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(ctx, "Πατησες medium", Toast.LENGTH_SHORT).show(); if(small_Vehicles!=0||medium_Vehicles!=0||big_Vehicles!=0){ alert.EmailDialog(MainActivity.this, "Sign up"); Log.e("response111: ", savedname+ ""); Log.e("response111: ", savedsmall+ ""); }else{ dialogBox2(); } } }); ////////////////// ///FB LOGin////////////////////////////////////////////// LoginButton fbloginButton = (LoginButton) findViewById(R.id.login_button); fbloginButton.setBackgroundResource(R.drawable.login); // fbloginButton.setReadPermissions("public_profile", "email","user_friends"); fbloginButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); fbloginButton.setLoginBehavior(LoginBehavior.NATIVE_WITH_FALLBACK); callbackManager = CallbackManager.Factory.create(); //fbloginButton.registerCallback(callbackManager, mCallBack); fbloginButton.registerCallback(callbackManager, null); // fbloginButton.registerCallback(callbackManager,null); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted( JSONObject object, GraphResponse response) { Log.e("response111: ", response + ""); try { user = new User(); ///o user me atrributes name,lastname,fbID,email String mystring =object.getString("name").toString(); String firstName = mystring.split(" ",2)[0].replaceAll("'", " ");//first fb name // Log.i("FACEBOOK NAME 11isssss", "[" + firstName+ "]++++++++++++++"); String lastName = mystring.split(" ",2)[1].replaceAll("'", " ");// second fb name user.NAME =firstName.replaceAll("'", " "); user.LAST_NAME=lastName.replaceAll("'", " "); // user.facebookID = object.getString("id").toString(); user.EMAIL = object.getString("email").toString(); // user.GENDER = object.getString("gender").toString(); if(small_Vehicles!=0||medium_Vehicles!=0||big_Vehicles!=0){ String sC= String.valueOf(small_Vehicles); String mC= String.valueOf(medium_Vehicles); String bC= String.valueOf(big_Vehicles); saveData(user.NAME,user.LAST_NAME,user.EMAIL,sC,mC,bC,savedfree,savedpay); BackGround b = new BackGround(); b.execute(user.NAME, user.LAST_NAME, user.EMAIL); }else{ dialogBox2(); } }catch (Exception e){ e.printStackTrace(); } //Toast.makeText(RegisterActivity.this,"welcome "+user.name+"", Toast.LENGTH_SHORT).show(); //finish(); } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name,email,gender, birthday"); request.setParameters(parameters); request.executeAsync(); } @Override public void onCancel() { // App code } @Override public void onError(FacebookException exception) { // App code } }); //.........................................END LOG IN VIA FACEBOOK....................................... } @Override public boolean dispatchTouchEvent(MotionEvent ev) { // Your code here final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { //Do something after 100ms carN (); } }, 400); return super.dispatchTouchEvent(ev); } public void register_register(View v) { //name = etName.getText().toString().replaceAll("'", " "); //last_name = etLastName.getText().toString(); //email = etMail.getText().toString(); // password = etPasswordLog.getText().toString(); //rep_password = etConfPassword.getText().toString(); BackGround b = new BackGround(); /* if (name !=null && !name.isEmpty()) { // if (last_name != null && !last_name.isEmpty()) { if (isEmailValid(email)) { ///καλει την μέθοδο isEmailValid και αν true τοτε εκτελει την μεθοδο b if (password !=null && !password.isEmpty()) { if (password.equals(rep_password)) { NAME=name.replaceAll("'", " "); LAST_NAME=last_name.replaceAll("'", " "); EMAIL=email; PASSWORD=password; b.execute(NAME, LAST_NAME, EMAIL, PASSWORD, rep_password); } else { Toast.makeText(ctx, "Προσοχή Οι κωδικοί δεν ταυτίζονται! ", Toast.LENGTH_LONG).show(); } }else { Toast.makeText(ctx, "Έισάγεται τον κωδικό σας", Toast.LENGTH_LONG).show(); } } else { dialogBox(); //καλει την μεθοδο dialogBox εφόσων η μέθοδος is EmailValid είναι false } } else { Toast.makeText(ctx, "Συμπληρώστε το Όνομα Χρήστη σας", Toast.LENGTH_LONG).show(); } */ } class BackGround extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { String name = params[0]; String last_name= params[1]; String email = params[2]; String data = ""; int tmp; try { HttpURLConnection urlConnection = null; JSONObject object = null; InputStream inStream = null; URL url = new URL("aaaaaaaaaaaa.php"); try { url = new URL(url.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.connect(); inStream = urlConnection.getInputStream(); BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream)); String temp, response = ""; while ((temp = bReader.readLine()) != null) { response += temp; } object = (JSONObject) new JSONTokener(response).nextValue(); // Log.i("Json isssss", "[" + object + "]}}}}}}}}}}}}}}}}}}}}}}}}}}}}{{{{{{{{{{{{{{}}}"); JSONArray resultTable = null; resultTable = object.getJSONArray("results of php file"); for (int i = 0; i < resultTable.length(); i++) { // Storing  JSON item in a Variable JSONObject place = resultTable.getJSONObject(i); //PER_NAME = place.getString("name"); // ADDRESS = place.getString("vicinity"); //LAT = place.getJSONObject("geometry").getJSONObject("location").getString("lat"); // LNG = place.getJSONObject("geometry").getJSONObject("location").getString("lng"); //ID = place.getString("place_id"); } /* Intent intent = new Intent(MainActivity.this, UserActivity.class); intent.putExtra("vehicles", total_vehicles); intent.putExtra("size", car_size); startActivity(intent); */ } catch (Exception e) { } finally { if (inStream != null) { try { // this will close the bReader as well inStream.close(); } catch (IOException ignored) { } } if (urlConnection != null) { urlConnection.disconnect(); } } } catch (MalformedURLException e) { e.printStackTrace(); return "Exception: " + e.getMessage(); } return data; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } ///-------------------------------------------------------------Dialog boxes public class ViewDialog { public void showDialog(Activity activity, String msg){ final Dialog dialog = new Dialog(activity); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(false); dialog.setContentView(R.layout.cars_size); // final RelativeLayout timoni = (RelativeLayout) findViewById(R.id.relative); //final LinearLayout timoni = (LinearLayout) findViewById(R.id.linear); final Button small = (Button) dialog.findViewById(R.id.small); Button medium = (Button) dialog.findViewById(R.id.medium); Button big = (Button) dialog.findViewById(R.id.big); small.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { small_Vehicles=small_Vehicles+1; Toast.makeText(ctx, "Πατησες small", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }); medium.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(ctx, "Πατησες medium", Toast.LENGTH_SHORT).show(); medium_Vehicles=medium_Vehicles+1; dialog.dismiss(); } }); big.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(ctx, "Πατησες big", Toast.LENGTH_SHORT).show(); big_Vehicles=big_Vehicles+1; dialog.dismiss(); } }); dialog.show(); } public void EmailDialog(Activity activity, String msg){ final Dialog emailDialog = new Dialog(activity); emailDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); emailDialog.setCancelable(false); emailDialog.setContentView(R.layout.email_box); // final RelativeLayout timoni = (RelativeLayout) findViewById(R.id.relative); //final LinearLayout timoni = (LinearLayout) findViewById(R.id.linear); final Button sign_up = (Button) emailDialog.findViewById(R.id.sign_up); final ImageView sign_in = (ImageView) emailDialog.findViewById(R.id.sign_in); final ImageView x_button = (ImageView) emailDialog.findViewById(R.id.x_image); etName = (EditText) emailDialog.findViewById(R.id.etUserName); etPassword = (EditText) emailDialog.findViewById(R.id.etPasswordLog); etMail = (EditText) emailDialog.findViewById(R.id.etMail); sign_up.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ename = etName.getText().toString().replaceAll("'", " "); eemail = etMail.getText().toString(); epassword = etPassword.getText().toString(); String sC2= String.valueOf(small_Vehicles); String mC2= String.valueOf(medium_Vehicles); String bC2= String.valueOf(big_Vehicles); if (ename !=null && !ename.isEmpty()) { // if (last_name != null && !last_name.isEmpty()) { if (isEmailValid(eemail)) { ///καλει την μέθοδο isEmailValid και αν true τοτε εκτελει την μεθοδο b if (epassword !=null && !epassword.isEmpty()) { saveData(ename,eemail,epassword,sC2,mC2,bC2,savedfree,savedpay); Intent intent = new Intent(MainActivity.this,UserActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainActivity.this.startActivity(intent); emailDialog.dismiss(); }else { Toast.makeText(ctx, "Enter your password", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(ctx, "This email is invalid, please enter a new one", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(ctx, "Enter your Username", Toast.LENGTH_SHORT).show(); } Toast.makeText(ctx, "Welcome to SPACERPK "+ename, Toast.LENGTH_SHORT).show(); //Intent intent = new Intent(MainActivity.this,UserActivity.class); //pername ta stoixeia to xrhsth sthn main activity // MainActivity.this.startActivity(intent); // overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up ); } }); sign_in.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(ctx, "Πατησες medium", Toast.LENGTH_SHORT).show(); emailDialog.dismiss(); } }); x_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(ctx, "Πατησες medium", Toast.LENGTH_SHORT).show(); emailDialog.dismiss(); } }); emailDialog.show(); } } //----------------------------------end of Dialog boxes boolean isEmailValid(CharSequence email) { return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches(); } ///---------------------------------κλάση που δημιουργείτε ο Χρήστης public class User { public String NAME; public String LAST_NAME; public String EMAIL; } ////μεθοδος για τον υπολογισμο των συνολικων αυτοκινητων που θα επιλέξει ο χρήστης public void carN () { carN = valueSelector.getValue(); motoN = motoSelector.getValue(); String str = carN.replaceAll("\\D+",""); String strM = motoN.replaceAll("\\D+",""); carNum=Integer.valueOf(str); motoNum=Integer.valueOf(strM); if (carNum!=temp && carNum>temp){ alert.showDialog(MainActivity.this, "Pick your Car"); temp=carNum; }else{ temp=carNum; } Log.e("CARnum: ", carNum + ""); Log.e("response111: ", motoN + ""); } public void saveData(String name, String last_name, String email, String smallV, String mediumV, String bigV,String freeP,String payP) { getSharedPreferences(PREFS_NAME,MODE_PRIVATE) .edit() .putString("NAME", name) .putString("LAST_NAME",last_name) .putString("EMAIL",email) .putString("FREE",freeP) .putString("PAYMENT",payP) .commit(); getSharedPreferences(PREFS_NAME2,MODE_PRIVATE) .edit() .putString("SMALL", smallV) .putString("MEDIUM", mediumV) .putString("BIG", bigV) .commit(); } public void loadData() { SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); savedname = pref.getString("NAME", DEFAULT); savedemail=pref.getString("EMAIL",DEFAULT); savedlastname=pref.getString("LAST_NAME",DEFAULT); savedfree=pref.getString("FREE",DEFAULT); savedpay=pref.getString("PAYMENT",DEFAULT); SharedPreferences pref2 = getSharedPreferences(PREFS_NAME2, MODE_PRIVATE); savedsmall = pref2.getString("SMALL", DEFAULT); savedmedium = pref2.getString("MEDIUM", DEFAULT); savedbig = pref2.getString("BIG", DEFAULT); } public void dialogBox2() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setIcon(R.drawable.ic_locked); alertDialogBuilder.setTitle("Login Failed"); alertDialogBuilder.setMessage("You have to choose your type of Vehicle"); alertDialogBuilder.setNegativeButton("Try Again", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { LoginManager.getInstance().logOut(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); alertDialog.getWindow().setBackgroundDrawableResource(R.color.colorBackround); } public void dialogBox() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setIcon(R.drawable.ic_alert); alertDialogBuilder.setTitle("Προσοχή!"); alertDialogBuilder.setMessage(" Το e-mail δεν είναι έγκυρο!"); alertDialogBuilder.setNegativeButton("Επαναληψη e-mail", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); alertDialog.getWindow().setBackgroundDrawableResource(R.color.white); } }
crowdhackathon-smartcity/Spaceprk
SpacePrk/app/src/main/java/com/example/kostis/spaceprk/MainActivity.java
5,294
///καλει την μέθοδο isEmailValid και αν true τοτε εκτελει την μεθοδο b
line_comment
el
package com.example.kostis.spaceprk; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Handler; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import com.facebook.login.LoginBehavior; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.intertech.customviews.MotoSelector; import com.intertech.customviews.ValueSelector; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends AppCompatActivity { CallbackManager callbackManager; MainActivity ctx=this; User user; int small_Vehicles=0,big_Vehicles=0,medium_Vehicles=0; ViewDialog alert; ValueSelector valueSelector; MotoSelector motoSelector; public int carNum=0 ,motoNum=0,temp=0; public String carN,motoN; public static final String PREFS_NAME = "MyPrefsFile"; public static final String PREFS_NAME2 = "MyPrefsFile2"; public static final String DEFAULT="N/A"; String savedname, savedsmall,savedlastname,savedemail, savedmedium, savedbig,savedpay,savedfree; private static final int PERMISSION_ACCESS_COARSE_LOCATION = 1; private static final int PERMISSION_ACCESS_FINE_LOCATION = 1; public String ename,eemail,epassword; EditText etName,etPassword,etMail; //-------------------On Create @Override protected void onCreate(final Bundle savedInstanceState) { FacebookSdk.sdkInitialize(getApplicationContext()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //check if the user loged in before and saved prefereces................................. savedpay="no"; savedfree="free"; //loadData(); //ελεγχος αν έχει χρησιμοποιηση ξανα ο χρηστης και αποθυκευτικαν τα στοιχεια του ///Request permissio for API 24 and higher/////////// if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_ACCESS_COARSE_LOCATION); } if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_ACCESS_FINE_LOCATION); } /////End ask permission///////////////////////// alert = new ViewDialog(); valueSelector = (ValueSelector) findViewById(R.id.valueSelector); valueSelector.setMinValue(0); valueSelector.setMaxValue(10); motoSelector = (MotoSelector) findViewById(R.id.motoSelector); motoSelector.setMinValue(0); motoSelector.setMaxValue(10); //get a reference to the textview on the log.xml file. ImageView email= (ImageView)findViewById(R.id.email_image); email.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(ctx, "Πατησες medium", Toast.LENGTH_SHORT).show(); if(small_Vehicles!=0||medium_Vehicles!=0||big_Vehicles!=0){ alert.EmailDialog(MainActivity.this, "Sign up"); Log.e("response111: ", savedname+ ""); Log.e("response111: ", savedsmall+ ""); }else{ dialogBox2(); } } }); ////////////////// ///FB LOGin////////////////////////////////////////////// LoginButton fbloginButton = (LoginButton) findViewById(R.id.login_button); fbloginButton.setBackgroundResource(R.drawable.login); // fbloginButton.setReadPermissions("public_profile", "email","user_friends"); fbloginButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); fbloginButton.setLoginBehavior(LoginBehavior.NATIVE_WITH_FALLBACK); callbackManager = CallbackManager.Factory.create(); //fbloginButton.registerCallback(callbackManager, mCallBack); fbloginButton.registerCallback(callbackManager, null); // fbloginButton.registerCallback(callbackManager,null); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted( JSONObject object, GraphResponse response) { Log.e("response111: ", response + ""); try { user = new User(); ///o user me atrributes name,lastname,fbID,email String mystring =object.getString("name").toString(); String firstName = mystring.split(" ",2)[0].replaceAll("'", " ");//first fb name // Log.i("FACEBOOK NAME 11isssss", "[" + firstName+ "]++++++++++++++"); String lastName = mystring.split(" ",2)[1].replaceAll("'", " ");// second fb name user.NAME =firstName.replaceAll("'", " "); user.LAST_NAME=lastName.replaceAll("'", " "); // user.facebookID = object.getString("id").toString(); user.EMAIL = object.getString("email").toString(); // user.GENDER = object.getString("gender").toString(); if(small_Vehicles!=0||medium_Vehicles!=0||big_Vehicles!=0){ String sC= String.valueOf(small_Vehicles); String mC= String.valueOf(medium_Vehicles); String bC= String.valueOf(big_Vehicles); saveData(user.NAME,user.LAST_NAME,user.EMAIL,sC,mC,bC,savedfree,savedpay); BackGround b = new BackGround(); b.execute(user.NAME, user.LAST_NAME, user.EMAIL); }else{ dialogBox2(); } }catch (Exception e){ e.printStackTrace(); } //Toast.makeText(RegisterActivity.this,"welcome "+user.name+"", Toast.LENGTH_SHORT).show(); //finish(); } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name,email,gender, birthday"); request.setParameters(parameters); request.executeAsync(); } @Override public void onCancel() { // App code } @Override public void onError(FacebookException exception) { // App code } }); //.........................................END LOG IN VIA FACEBOOK....................................... } @Override public boolean dispatchTouchEvent(MotionEvent ev) { // Your code here final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { //Do something after 100ms carN (); } }, 400); return super.dispatchTouchEvent(ev); } public void register_register(View v) { //name = etName.getText().toString().replaceAll("'", " "); //last_name = etLastName.getText().toString(); //email = etMail.getText().toString(); // password = etPasswordLog.getText().toString(); //rep_password = etConfPassword.getText().toString(); BackGround b = new BackGround(); /* if (name !=null && !name.isEmpty()) { // if (last_name != null && !last_name.isEmpty()) { if (isEmailValid(email)) { ///καλει την μέθοδο isEmailValid και αν true τοτε εκτελει την μεθοδο b if (password !=null && !password.isEmpty()) { if (password.equals(rep_password)) { NAME=name.replaceAll("'", " "); LAST_NAME=last_name.replaceAll("'", " "); EMAIL=email; PASSWORD=password; b.execute(NAME, LAST_NAME, EMAIL, PASSWORD, rep_password); } else { Toast.makeText(ctx, "Προσοχή Οι κωδικοί δεν ταυτίζονται! ", Toast.LENGTH_LONG).show(); } }else { Toast.makeText(ctx, "Έισάγεται τον κωδικό σας", Toast.LENGTH_LONG).show(); } } else { dialogBox(); //καλει την μεθοδο dialogBox εφόσων η μέθοδος is EmailValid είναι false } } else { Toast.makeText(ctx, "Συμπληρώστε το Όνομα Χρήστη σας", Toast.LENGTH_LONG).show(); } */ } class BackGround extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { String name = params[0]; String last_name= params[1]; String email = params[2]; String data = ""; int tmp; try { HttpURLConnection urlConnection = null; JSONObject object = null; InputStream inStream = null; URL url = new URL("aaaaaaaaaaaa.php"); try { url = new URL(url.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.connect(); inStream = urlConnection.getInputStream(); BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream)); String temp, response = ""; while ((temp = bReader.readLine()) != null) { response += temp; } object = (JSONObject) new JSONTokener(response).nextValue(); // Log.i("Json isssss", "[" + object + "]}}}}}}}}}}}}}}}}}}}}}}}}}}}}{{{{{{{{{{{{{{}}}"); JSONArray resultTable = null; resultTable = object.getJSONArray("results of php file"); for (int i = 0; i < resultTable.length(); i++) { // Storing  JSON item in a Variable JSONObject place = resultTable.getJSONObject(i); //PER_NAME = place.getString("name"); // ADDRESS = place.getString("vicinity"); //LAT = place.getJSONObject("geometry").getJSONObject("location").getString("lat"); // LNG = place.getJSONObject("geometry").getJSONObject("location").getString("lng"); //ID = place.getString("place_id"); } /* Intent intent = new Intent(MainActivity.this, UserActivity.class); intent.putExtra("vehicles", total_vehicles); intent.putExtra("size", car_size); startActivity(intent); */ } catch (Exception e) { } finally { if (inStream != null) { try { // this will close the bReader as well inStream.close(); } catch (IOException ignored) { } } if (urlConnection != null) { urlConnection.disconnect(); } } } catch (MalformedURLException e) { e.printStackTrace(); return "Exception: " + e.getMessage(); } return data; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } ///-------------------------------------------------------------Dialog boxes public class ViewDialog { public void showDialog(Activity activity, String msg){ final Dialog dialog = new Dialog(activity); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(false); dialog.setContentView(R.layout.cars_size); // final RelativeLayout timoni = (RelativeLayout) findViewById(R.id.relative); //final LinearLayout timoni = (LinearLayout) findViewById(R.id.linear); final Button small = (Button) dialog.findViewById(R.id.small); Button medium = (Button) dialog.findViewById(R.id.medium); Button big = (Button) dialog.findViewById(R.id.big); small.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { small_Vehicles=small_Vehicles+1; Toast.makeText(ctx, "Πατησες small", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }); medium.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(ctx, "Πατησες medium", Toast.LENGTH_SHORT).show(); medium_Vehicles=medium_Vehicles+1; dialog.dismiss(); } }); big.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(ctx, "Πατησες big", Toast.LENGTH_SHORT).show(); big_Vehicles=big_Vehicles+1; dialog.dismiss(); } }); dialog.show(); } public void EmailDialog(Activity activity, String msg){ final Dialog emailDialog = new Dialog(activity); emailDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); emailDialog.setCancelable(false); emailDialog.setContentView(R.layout.email_box); // final RelativeLayout timoni = (RelativeLayout) findViewById(R.id.relative); //final LinearLayout timoni = (LinearLayout) findViewById(R.id.linear); final Button sign_up = (Button) emailDialog.findViewById(R.id.sign_up); final ImageView sign_in = (ImageView) emailDialog.findViewById(R.id.sign_in); final ImageView x_button = (ImageView) emailDialog.findViewById(R.id.x_image); etName = (EditText) emailDialog.findViewById(R.id.etUserName); etPassword = (EditText) emailDialog.findViewById(R.id.etPasswordLog); etMail = (EditText) emailDialog.findViewById(R.id.etMail); sign_up.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ename = etName.getText().toString().replaceAll("'", " "); eemail = etMail.getText().toString(); epassword = etPassword.getText().toString(); String sC2= String.valueOf(small_Vehicles); String mC2= String.valueOf(medium_Vehicles); String bC2= String.valueOf(big_Vehicles); if (ename !=null && !ename.isEmpty()) { // if (last_name != null && !last_name.isEmpty()) { if (isEmailValid(eemail)) { ///καλει την<SUF> if (epassword !=null && !epassword.isEmpty()) { saveData(ename,eemail,epassword,sC2,mC2,bC2,savedfree,savedpay); Intent intent = new Intent(MainActivity.this,UserActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainActivity.this.startActivity(intent); emailDialog.dismiss(); }else { Toast.makeText(ctx, "Enter your password", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(ctx, "This email is invalid, please enter a new one", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(ctx, "Enter your Username", Toast.LENGTH_SHORT).show(); } Toast.makeText(ctx, "Welcome to SPACERPK "+ename, Toast.LENGTH_SHORT).show(); //Intent intent = new Intent(MainActivity.this,UserActivity.class); //pername ta stoixeia to xrhsth sthn main activity // MainActivity.this.startActivity(intent); // overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up ); } }); sign_in.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(ctx, "Πατησες medium", Toast.LENGTH_SHORT).show(); emailDialog.dismiss(); } }); x_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(ctx, "Πατησες medium", Toast.LENGTH_SHORT).show(); emailDialog.dismiss(); } }); emailDialog.show(); } } //----------------------------------end of Dialog boxes boolean isEmailValid(CharSequence email) { return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches(); } ///---------------------------------κλάση που δημιουργείτε ο Χρήστης public class User { public String NAME; public String LAST_NAME; public String EMAIL; } ////μεθοδος για τον υπολογισμο των συνολικων αυτοκινητων που θα επιλέξει ο χρήστης public void carN () { carN = valueSelector.getValue(); motoN = motoSelector.getValue(); String str = carN.replaceAll("\\D+",""); String strM = motoN.replaceAll("\\D+",""); carNum=Integer.valueOf(str); motoNum=Integer.valueOf(strM); if (carNum!=temp && carNum>temp){ alert.showDialog(MainActivity.this, "Pick your Car"); temp=carNum; }else{ temp=carNum; } Log.e("CARnum: ", carNum + ""); Log.e("response111: ", motoN + ""); } public void saveData(String name, String last_name, String email, String smallV, String mediumV, String bigV,String freeP,String payP) { getSharedPreferences(PREFS_NAME,MODE_PRIVATE) .edit() .putString("NAME", name) .putString("LAST_NAME",last_name) .putString("EMAIL",email) .putString("FREE",freeP) .putString("PAYMENT",payP) .commit(); getSharedPreferences(PREFS_NAME2,MODE_PRIVATE) .edit() .putString("SMALL", smallV) .putString("MEDIUM", mediumV) .putString("BIG", bigV) .commit(); } public void loadData() { SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); savedname = pref.getString("NAME", DEFAULT); savedemail=pref.getString("EMAIL",DEFAULT); savedlastname=pref.getString("LAST_NAME",DEFAULT); savedfree=pref.getString("FREE",DEFAULT); savedpay=pref.getString("PAYMENT",DEFAULT); SharedPreferences pref2 = getSharedPreferences(PREFS_NAME2, MODE_PRIVATE); savedsmall = pref2.getString("SMALL", DEFAULT); savedmedium = pref2.getString("MEDIUM", DEFAULT); savedbig = pref2.getString("BIG", DEFAULT); } public void dialogBox2() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setIcon(R.drawable.ic_locked); alertDialogBuilder.setTitle("Login Failed"); alertDialogBuilder.setMessage("You have to choose your type of Vehicle"); alertDialogBuilder.setNegativeButton("Try Again", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { LoginManager.getInstance().logOut(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); alertDialog.getWindow().setBackgroundDrawableResource(R.color.colorBackround); } public void dialogBox() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setIcon(R.drawable.ic_alert); alertDialogBuilder.setTitle("Προσοχή!"); alertDialogBuilder.setMessage(" Το e-mail δεν είναι έγκυρο!"); alertDialogBuilder.setNegativeButton("Επαναληψη e-mail", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); alertDialog.getWindow().setBackgroundDrawableResource(R.color.white); } }
31180_1
/* * Copyright 2009 Georgios "cyberpython" Migdos [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License * at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * EditorView.java * * Created on 21 Δεκέμβριος 2008, 7:50 μμ */ package glossaeditor.ui.components.editor; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Properties; import javax.swing.JEditorPane; import javax.swing.JPopupMenu; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter; import javax.swing.text.EditorKit; import javax.swing.text.Highlighter; import jsyntaxpane.DefaultSyntaxKit; import jsyntaxpane.SyntaxDocument; import jsyntaxpane.SyntaxStyles; import jsyntaxpane.TokenType; import jsyntaxpane.lexers.GlossaLexer; import jsyntaxpane.syntaxkits.GlossaSyntaxKit; /** * * @author cyberpython */ public class EditorView extends javax.swing.JPanel implements DocumentListener, CaretListener, UndoableEditListener { private boolean newFile; private boolean modified; private String title; private File storage; private SyntaxDocument document; private EditorViewContainer container; private String UNTITLED; private JPopupMenu popupMenu; private List searchHighlights; private LinkedList<Point> searchResults; private String lastSearch; private HashMap<String, String> searchedFor; private HashMap<String, String> replacedWith; /** Creates new form EditorView */ public EditorView() { preInit(null, 0, null); initComponents(); postInit(); } /** Creates new form EditorView */ public EditorView(EditorViewContainer container) { preInit(null, 0, container); initComponents(); postInit(); } public EditorView(int documentCount, EditorViewContainer container) { preInit(null, documentCount, container); initComponents(); postInit(); } public EditorView(File input, EditorViewContainer container) { preInit(input, -1, container); initComponents(); postInit(input); } private void preInit(File input, int documentCount, EditorViewContainer container) { UNTITLED = "Ανώνυμο"; this.container = container; this.storage = input; if (storage == null) { newFile = true; title = UNTITLED;// + "-" + String.valueOf(documentCount); } else { newFile = false; title = storage.getName(); } modified = false; this.searchHighlights = new ArrayList(); this.searchResults = new LinkedList<Point>(); this.lastSearch = null; this.searchedFor = new HashMap<String, String>(); this.replacedWith = new HashMap<String, String>(); } private void postInit() { if (container != null) { String hint = null; if (this.storage != null) { try { hint = this.storage.getCanonicalPath(); } catch (IOException ioe) { } } container.notifyDocumentModified(getTitleWithModificationIndicator(), hint, modified); } } private void postInit(File f) { this.storage = f; this.title = storage.getName(); this.newFile = false; if (container != null) { String hint = null; if (this.storage != null) { try { hint = this.storage.getCanonicalPath(); } catch (IOException ioe) { } } container.notifyDocumentModified(getTitleWithModificationIndicator(), hint, modified); } } public void initEditor(JPopupMenu popupmenu, Font f, String[] colors, Charset c) { //jEditorPane1.setTransferHandler(null); this.popupMenu = popupmenu; DefaultSyntaxKit.initKit(); jEditorPane1.setContentType("text/glossa"); jEditorPane1.setFont(f); if (this.isNewFile()) { createEmptyFile(); } else { boolean openedSuccessfully = loadFile(this.storage, c); if (!openedSuccessfully) { this.storage = null; newFile = true; title = UNTITLED; container.notifyDocumentModified(getTitleWithModificationIndicator(), null, false); } } this.setEditorColors(colors); jEditorPane1.getDocument().addDocumentListener(this); jEditorPane1.addCaretListener(this); this.document.setUndoLimit(-1);//unlimited undo actions jEditorPane1.getDocument().addUndoableEditListener(this); container.notifyCaretChanged(null); jEditorPane1.invalidate(); } public void insertText(String text) { this.jEditorPane1.replaceSelection(text); } public Font getEditorFont() { return jEditorPane1.getFont(); } public JEditorPane getEditorPane() { return this.jEditorPane1; } public SyntaxDocument getDocument() { return this.document; } public void requestFocusOnEditor() { this.jEditorPane1.requestFocus(); } public void clearHighlights() { this.jEditorPane1.getHighlighter().removeAllHighlights(); } public void highlightCurrentLine(Color highlightColor) { int position = jEditorPane1.getCaretPosition(); int lineStart = document.getLineStartOffset(position); int lineEnd = document.getLineEndOffset(position); DefaultHighlightPainter redPainter = new DefaultHighlighter.DefaultHighlightPainter(highlightColor); try { this.jEditorPane1.getHighlighter().addHighlight(lineStart, lineEnd, redPainter); } catch (BadLocationException ble) { } } public Object highlight(int start, int end, Color highlightColor) { DefaultHighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(highlightColor); try { Object o = this.jEditorPane1.getHighlighter().addHighlight(start, end, painter); this.jEditorPane1.repaint(); return o; } catch (BadLocationException ble) { return null; } } public void clearSearchHighlights() { Highlighter h = this.getEditorPane().getHighlighter(); for (int i = 0; i < searchHighlights.size(); i++) { h.removeHighlight(searchHighlights.get(i)); } searchHighlights.clear(); } public void clearSearchResults() { this.searchResults.clear(); } public String putSearchedForItem(String key, String object) { return this.searchedFor.put(key, object); } public String putReplacedWithItem(String key, String object) { return this.replacedWith.put(key, object); } public void findNext(boolean matchCase, boolean cycle) { search(this.lastSearch, cycle, matchCase); } public long search(String pattern, boolean cycle, boolean caseSensitive) { long totalFound = 0; if ((pattern == null) || (pattern.equals(""))) { return 0; } JEditorPane pane = this.getEditorPane(); searchResults.clear(); String text = null; if (caseSensitive) { text = pane.getText(); } else { pattern = pattern.toLowerCase(); text = pane.getText().toLowerCase(); } lastSearch = pattern; int pos = this.getSelectionStart(); if ((lastSearch != null) && (lastSearch.equals(pattern))) { pos = pos + 1; } int initialPos = pos; int a = 0; int b = 0; int l = pattern.length(); int end = text.length(); boolean found = false; while (pos < end) { a = text.indexOf(pattern, pos); if (a != -1) { b = a + l; pos = b; found = true; searchResults.addLast(new Point(a, b)); totalFound++; } else { pos = end; } } pos = 0; while (pos < initialPos) { a = text.indexOf(pattern, pos); if (a != -1) { b = a + l; pos = b; searchResults.addLast(new Point(a, b)); totalFound++; if (cycle) { found = true; } } else { pos = initialPos; } } highlightSearch(found); return totalFound; } public void highlightSearch(boolean found) { clearSearchHighlights(); JEditorPane pane = this.getEditorPane(); Point p; if (searchResults.size() > 0) { p = searchResults.get(0); if (found) { pane.setCaretPosition(p.y); pane.setSelectionStart(p.x); pane.setSelectionEnd(p.y); } else { searchHighlights.add(this.highlight(p.x, p.y, Color.yellow)); } } for (int i = 1; i < searchResults.size(); i++) { p = searchResults.get(i); searchHighlights.add(this.highlight(p.x, p.y, Color.yellow)); } } public long simplifiedSearch(String pattern) { if ((pattern == null) || (pattern.trim().equals(""))) { return 0; } return search(pattern, true, false); } public Color getKeywordColor() { try { return SyntaxStyles.getInstance().getStyle(TokenType.KEYWORD).getColor(); } catch (Exception e) { return Color.BLACK; } } public void setEditorColors(String[] colors) { if (colors.length >= 9) { GlossaSyntaxKit kit = (GlossaSyntaxKit)jEditorPane1.getEditorKit(); Properties newStyles = new Properties(); newStyles.setProperty("Style.KEYWORD", colors[0] + ", 1"); newStyles.setProperty("Style.KEYWORD2", colors[0] + ", 1"); newStyles.setProperty("Style.NUMBER", colors[1] + ", 0"); newStyles.setProperty("Style.STRING", colors[2] + ", 0"); newStyles.setProperty("Style.STRING2", colors[2] + ", 0"); newStyles.setProperty("Style.OPERATOR", colors[3] + ", 0"); newStyles.setProperty("Style.COMMENT", colors[4] + ", 2"); newStyles.setProperty("Style.COMMENT2", colors[4] + ", 2"); newStyles.setProperty("Style.TYPE", colors[5] + ", 1"); newStyles.setProperty("Style.TYPE2", colors[5] + ", 1"); newStyles.setProperty("Style.TYPE3", colors[5] + ", 1"); newStyles.setProperty("Style.IDENTIFIER", colors[6] + ", 0"); newStyles.setProperty("Style.DELIMITER", colors[7] + ", 1"); newStyles.setProperty("Style.DEFAULT", colors[7] + ", 0"); kit.setConfig(newStyles); jEditorPane1.updateUI(); this.jEditorPane1.setBackground(Color.decode(colors[8])); } } private String colorToHex(Color c) { int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); String R = Integer.toHexString(r); String G = Integer.toHexString(g); String B = Integer.toHexString(b); if (R.length() == 1) { R = "0" + R; } if (G.length() == 1) { G = "0" + G; } if (B.length() == 1) { B = "0" + B; } return "0x" + R + G + B; } public void setEditorFont(Font font) { jEditorPane1.setFont(font); } public boolean isModified() { return this.modified; } public void setModified(boolean modified) { this.modified = modified; if (container != null) { String hint = null; if (this.storage != null) { try { hint = this.storage.getCanonicalPath(); } catch (IOException ioe) { } } container.notifyDocumentModified(getTitleWithModificationIndicator(), hint, modified); } } public boolean isNewFile() { return this.newFile; } public File getFile() { return this.storage; } public String getTitle() { return this.title; } public String getTitleWithModificationIndicator() { String s = this.title; if (this.modified) { s = s + "*"; } return s; } public String getSelectedText() { return this.jEditorPane1.getSelectedText(); } public Point getCaretPosition() { int absoluteOffset = jEditorPane1.getCaretPosition(); int y = document.getLineNumberAt(absoluteOffset); int x = absoluteOffset - document.getLineStartOffset(absoluteOffset); return new Point(x, y); } public int getSelectionStart() { return jEditorPane1.getSelectionStart(); } public void reset(int documentCount) { this.jEditorPane1.setText(""); this.storage = null; this.title = UNTITLED + "-" + documentCount; this.newFile = true; setModified(false); } private void createEmptyFile() { this.document = new SyntaxDocument(new GlossaLexer()); jEditorPane1.setDocument(this.document); jEditorPane1.setCaretPosition(0); setModified(false); this.document.clearUndos(); } private boolean loadFile(File f, Charset charset) { try { this.document = new SyntaxDocument(new GlossaLexer()); jEditorPane1.setDocument(this.document); EditorKit kit = jEditorPane1.getEditorKit(); /*CharsetDetector cd = new CharsetDetector(); String[] charsetsToBeTested = {"UTF-8", "windows-1253"}; Charset charset = cd.detectCharset(f, charsetsToBeTested);*/ if (charset == null) { charset = Charset.forName("UTF-8"); } if (charset != null) { kit.read(new InputStreamReader(new FileInputStream(f), charset), this.document, 0); } else { return false; } jEditorPane1.setCaretPosition(0); setModified(false); this.document.clearUndos(); return true; } catch (FileNotFoundException fnfe) { return false; } catch (IOException ioe) { return false; } catch (Exception e) { e.printStackTrace(System.err); return false; } } public boolean saveFile(File f) { try { OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(f), "UTF-8"); BufferedWriter bw = new BufferedWriter(w); bw.write(jEditorPane1.getText()); bw.flush(); bw.close(); w.close(); this.storage = f; this.newFile = false; this.title = storage.getName(); setModified(false); return true; } catch (IOException ioe) { return false; } } public void undo() { this.document.doUndo(); if (!this.document.canUndo()) { this.setModified(false); } } public void redo() { this.document.doRedo(); } public boolean canUndo() { return this.document.canUndo(); } public boolean canRedo() { return this.document.canRedo(); } public void cut() { this.jEditorPane1.cut(); } public void copy() { this.jEditorPane1.copy(); } public void paste() { this.jEditorPane1.paste(); } public void deleteSelection() { this.jEditorPane1.replaceSelection(""); } public void selectAll() { this.jEditorPane1.selectAll(); } // <editor-fold defaultstate="expanded" desc="DocumentListener implementation"> /* IMPLEMENTATION OF THE DOCUMENTLISTENER INTERFACE : */ public void insertUpdate(DocumentEvent e) { setModified(true); } public void removeUpdate(DocumentEvent e) { setModified(true); } public void changedUpdate(DocumentEvent e) { setModified(true); } /* ----------------------------------------------------- */ // </editor-fold> // <editor-fold defaultstate="expanded" desc="CaretListener implementation"> public void caretUpdate(CaretEvent e) { this.container.notifyCaretChanged(e); } /* ----------------------------------------------------- */ // </editor-fold> // <editor-fold defaultstate="expanded" desc="UndoableEditListener implementation"> public void undoableEditHappened(UndoableEditEvent evt) { if (evt.getEdit().isSignificant()) { if (!canUndo()) { container.notifyFirstUndoableEditHappened(evt); } } } /* ----------------------------------------------------- */ // </editor-fold> /** 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("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jEditorPane1 = new javax.swing.JEditorPane(); setName("Form"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(glossaeditor.Slang.class).getContext().getResourceMap(EditorView.class); jEditorPane1.setBackground(resourceMap.getColor("jEditorPane1.background")); // NOI18N jEditorPane1.setName("jEditorPane1"); // NOI18N jEditorPane1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jEditorPane1MouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { jEditorPane1MousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { jEditorPane1MouseReleased(evt); } }); jScrollPane1.setViewportView(jEditorPane1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents private void jEditorPane1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jEditorPane1MouseClicked }//GEN-LAST:event_jEditorPane1MouseClicked private void jEditorPane1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jEditorPane1MousePressed if (evt.isPopupTrigger()) { this.popupMenu.show(evt.getComponent(), evt.getX(), evt.getY()); } }//GEN-LAST:event_jEditorPane1MousePressed private void jEditorPane1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jEditorPane1MouseReleased if (evt.isPopupTrigger()) { this.popupMenu.show(evt.getComponent(), evt.getX(), evt.getY()); } }//GEN-LAST:event_jEditorPane1MouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JEditorPane jEditorPane1; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }
cyberpython/Slang
src/glossaeditor/ui/components/editor/EditorView.java
5,102
/* * EditorView.java * * Created on 21 Δεκέμβριος 2008, 7:50 μμ */
block_comment
el
/* * Copyright 2009 Georgios "cyberpython" Migdos [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License * at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * EditorView.java *<SUF>*/ package glossaeditor.ui.components.editor; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Properties; import javax.swing.JEditorPane; import javax.swing.JPopupMenu; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter; import javax.swing.text.EditorKit; import javax.swing.text.Highlighter; import jsyntaxpane.DefaultSyntaxKit; import jsyntaxpane.SyntaxDocument; import jsyntaxpane.SyntaxStyles; import jsyntaxpane.TokenType; import jsyntaxpane.lexers.GlossaLexer; import jsyntaxpane.syntaxkits.GlossaSyntaxKit; /** * * @author cyberpython */ public class EditorView extends javax.swing.JPanel implements DocumentListener, CaretListener, UndoableEditListener { private boolean newFile; private boolean modified; private String title; private File storage; private SyntaxDocument document; private EditorViewContainer container; private String UNTITLED; private JPopupMenu popupMenu; private List searchHighlights; private LinkedList<Point> searchResults; private String lastSearch; private HashMap<String, String> searchedFor; private HashMap<String, String> replacedWith; /** Creates new form EditorView */ public EditorView() { preInit(null, 0, null); initComponents(); postInit(); } /** Creates new form EditorView */ public EditorView(EditorViewContainer container) { preInit(null, 0, container); initComponents(); postInit(); } public EditorView(int documentCount, EditorViewContainer container) { preInit(null, documentCount, container); initComponents(); postInit(); } public EditorView(File input, EditorViewContainer container) { preInit(input, -1, container); initComponents(); postInit(input); } private void preInit(File input, int documentCount, EditorViewContainer container) { UNTITLED = "Ανώνυμο"; this.container = container; this.storage = input; if (storage == null) { newFile = true; title = UNTITLED;// + "-" + String.valueOf(documentCount); } else { newFile = false; title = storage.getName(); } modified = false; this.searchHighlights = new ArrayList(); this.searchResults = new LinkedList<Point>(); this.lastSearch = null; this.searchedFor = new HashMap<String, String>(); this.replacedWith = new HashMap<String, String>(); } private void postInit() { if (container != null) { String hint = null; if (this.storage != null) { try { hint = this.storage.getCanonicalPath(); } catch (IOException ioe) { } } container.notifyDocumentModified(getTitleWithModificationIndicator(), hint, modified); } } private void postInit(File f) { this.storage = f; this.title = storage.getName(); this.newFile = false; if (container != null) { String hint = null; if (this.storage != null) { try { hint = this.storage.getCanonicalPath(); } catch (IOException ioe) { } } container.notifyDocumentModified(getTitleWithModificationIndicator(), hint, modified); } } public void initEditor(JPopupMenu popupmenu, Font f, String[] colors, Charset c) { //jEditorPane1.setTransferHandler(null); this.popupMenu = popupmenu; DefaultSyntaxKit.initKit(); jEditorPane1.setContentType("text/glossa"); jEditorPane1.setFont(f); if (this.isNewFile()) { createEmptyFile(); } else { boolean openedSuccessfully = loadFile(this.storage, c); if (!openedSuccessfully) { this.storage = null; newFile = true; title = UNTITLED; container.notifyDocumentModified(getTitleWithModificationIndicator(), null, false); } } this.setEditorColors(colors); jEditorPane1.getDocument().addDocumentListener(this); jEditorPane1.addCaretListener(this); this.document.setUndoLimit(-1);//unlimited undo actions jEditorPane1.getDocument().addUndoableEditListener(this); container.notifyCaretChanged(null); jEditorPane1.invalidate(); } public void insertText(String text) { this.jEditorPane1.replaceSelection(text); } public Font getEditorFont() { return jEditorPane1.getFont(); } public JEditorPane getEditorPane() { return this.jEditorPane1; } public SyntaxDocument getDocument() { return this.document; } public void requestFocusOnEditor() { this.jEditorPane1.requestFocus(); } public void clearHighlights() { this.jEditorPane1.getHighlighter().removeAllHighlights(); } public void highlightCurrentLine(Color highlightColor) { int position = jEditorPane1.getCaretPosition(); int lineStart = document.getLineStartOffset(position); int lineEnd = document.getLineEndOffset(position); DefaultHighlightPainter redPainter = new DefaultHighlighter.DefaultHighlightPainter(highlightColor); try { this.jEditorPane1.getHighlighter().addHighlight(lineStart, lineEnd, redPainter); } catch (BadLocationException ble) { } } public Object highlight(int start, int end, Color highlightColor) { DefaultHighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(highlightColor); try { Object o = this.jEditorPane1.getHighlighter().addHighlight(start, end, painter); this.jEditorPane1.repaint(); return o; } catch (BadLocationException ble) { return null; } } public void clearSearchHighlights() { Highlighter h = this.getEditorPane().getHighlighter(); for (int i = 0; i < searchHighlights.size(); i++) { h.removeHighlight(searchHighlights.get(i)); } searchHighlights.clear(); } public void clearSearchResults() { this.searchResults.clear(); } public String putSearchedForItem(String key, String object) { return this.searchedFor.put(key, object); } public String putReplacedWithItem(String key, String object) { return this.replacedWith.put(key, object); } public void findNext(boolean matchCase, boolean cycle) { search(this.lastSearch, cycle, matchCase); } public long search(String pattern, boolean cycle, boolean caseSensitive) { long totalFound = 0; if ((pattern == null) || (pattern.equals(""))) { return 0; } JEditorPane pane = this.getEditorPane(); searchResults.clear(); String text = null; if (caseSensitive) { text = pane.getText(); } else { pattern = pattern.toLowerCase(); text = pane.getText().toLowerCase(); } lastSearch = pattern; int pos = this.getSelectionStart(); if ((lastSearch != null) && (lastSearch.equals(pattern))) { pos = pos + 1; } int initialPos = pos; int a = 0; int b = 0; int l = pattern.length(); int end = text.length(); boolean found = false; while (pos < end) { a = text.indexOf(pattern, pos); if (a != -1) { b = a + l; pos = b; found = true; searchResults.addLast(new Point(a, b)); totalFound++; } else { pos = end; } } pos = 0; while (pos < initialPos) { a = text.indexOf(pattern, pos); if (a != -1) { b = a + l; pos = b; searchResults.addLast(new Point(a, b)); totalFound++; if (cycle) { found = true; } } else { pos = initialPos; } } highlightSearch(found); return totalFound; } public void highlightSearch(boolean found) { clearSearchHighlights(); JEditorPane pane = this.getEditorPane(); Point p; if (searchResults.size() > 0) { p = searchResults.get(0); if (found) { pane.setCaretPosition(p.y); pane.setSelectionStart(p.x); pane.setSelectionEnd(p.y); } else { searchHighlights.add(this.highlight(p.x, p.y, Color.yellow)); } } for (int i = 1; i < searchResults.size(); i++) { p = searchResults.get(i); searchHighlights.add(this.highlight(p.x, p.y, Color.yellow)); } } public long simplifiedSearch(String pattern) { if ((pattern == null) || (pattern.trim().equals(""))) { return 0; } return search(pattern, true, false); } public Color getKeywordColor() { try { return SyntaxStyles.getInstance().getStyle(TokenType.KEYWORD).getColor(); } catch (Exception e) { return Color.BLACK; } } public void setEditorColors(String[] colors) { if (colors.length >= 9) { GlossaSyntaxKit kit = (GlossaSyntaxKit)jEditorPane1.getEditorKit(); Properties newStyles = new Properties(); newStyles.setProperty("Style.KEYWORD", colors[0] + ", 1"); newStyles.setProperty("Style.KEYWORD2", colors[0] + ", 1"); newStyles.setProperty("Style.NUMBER", colors[1] + ", 0"); newStyles.setProperty("Style.STRING", colors[2] + ", 0"); newStyles.setProperty("Style.STRING2", colors[2] + ", 0"); newStyles.setProperty("Style.OPERATOR", colors[3] + ", 0"); newStyles.setProperty("Style.COMMENT", colors[4] + ", 2"); newStyles.setProperty("Style.COMMENT2", colors[4] + ", 2"); newStyles.setProperty("Style.TYPE", colors[5] + ", 1"); newStyles.setProperty("Style.TYPE2", colors[5] + ", 1"); newStyles.setProperty("Style.TYPE3", colors[5] + ", 1"); newStyles.setProperty("Style.IDENTIFIER", colors[6] + ", 0"); newStyles.setProperty("Style.DELIMITER", colors[7] + ", 1"); newStyles.setProperty("Style.DEFAULT", colors[7] + ", 0"); kit.setConfig(newStyles); jEditorPane1.updateUI(); this.jEditorPane1.setBackground(Color.decode(colors[8])); } } private String colorToHex(Color c) { int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); String R = Integer.toHexString(r); String G = Integer.toHexString(g); String B = Integer.toHexString(b); if (R.length() == 1) { R = "0" + R; } if (G.length() == 1) { G = "0" + G; } if (B.length() == 1) { B = "0" + B; } return "0x" + R + G + B; } public void setEditorFont(Font font) { jEditorPane1.setFont(font); } public boolean isModified() { return this.modified; } public void setModified(boolean modified) { this.modified = modified; if (container != null) { String hint = null; if (this.storage != null) { try { hint = this.storage.getCanonicalPath(); } catch (IOException ioe) { } } container.notifyDocumentModified(getTitleWithModificationIndicator(), hint, modified); } } public boolean isNewFile() { return this.newFile; } public File getFile() { return this.storage; } public String getTitle() { return this.title; } public String getTitleWithModificationIndicator() { String s = this.title; if (this.modified) { s = s + "*"; } return s; } public String getSelectedText() { return this.jEditorPane1.getSelectedText(); } public Point getCaretPosition() { int absoluteOffset = jEditorPane1.getCaretPosition(); int y = document.getLineNumberAt(absoluteOffset); int x = absoluteOffset - document.getLineStartOffset(absoluteOffset); return new Point(x, y); } public int getSelectionStart() { return jEditorPane1.getSelectionStart(); } public void reset(int documentCount) { this.jEditorPane1.setText(""); this.storage = null; this.title = UNTITLED + "-" + documentCount; this.newFile = true; setModified(false); } private void createEmptyFile() { this.document = new SyntaxDocument(new GlossaLexer()); jEditorPane1.setDocument(this.document); jEditorPane1.setCaretPosition(0); setModified(false); this.document.clearUndos(); } private boolean loadFile(File f, Charset charset) { try { this.document = new SyntaxDocument(new GlossaLexer()); jEditorPane1.setDocument(this.document); EditorKit kit = jEditorPane1.getEditorKit(); /*CharsetDetector cd = new CharsetDetector(); String[] charsetsToBeTested = {"UTF-8", "windows-1253"}; Charset charset = cd.detectCharset(f, charsetsToBeTested);*/ if (charset == null) { charset = Charset.forName("UTF-8"); } if (charset != null) { kit.read(new InputStreamReader(new FileInputStream(f), charset), this.document, 0); } else { return false; } jEditorPane1.setCaretPosition(0); setModified(false); this.document.clearUndos(); return true; } catch (FileNotFoundException fnfe) { return false; } catch (IOException ioe) { return false; } catch (Exception e) { e.printStackTrace(System.err); return false; } } public boolean saveFile(File f) { try { OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(f), "UTF-8"); BufferedWriter bw = new BufferedWriter(w); bw.write(jEditorPane1.getText()); bw.flush(); bw.close(); w.close(); this.storage = f; this.newFile = false; this.title = storage.getName(); setModified(false); return true; } catch (IOException ioe) { return false; } } public void undo() { this.document.doUndo(); if (!this.document.canUndo()) { this.setModified(false); } } public void redo() { this.document.doRedo(); } public boolean canUndo() { return this.document.canUndo(); } public boolean canRedo() { return this.document.canRedo(); } public void cut() { this.jEditorPane1.cut(); } public void copy() { this.jEditorPane1.copy(); } public void paste() { this.jEditorPane1.paste(); } public void deleteSelection() { this.jEditorPane1.replaceSelection(""); } public void selectAll() { this.jEditorPane1.selectAll(); } // <editor-fold defaultstate="expanded" desc="DocumentListener implementation"> /* IMPLEMENTATION OF THE DOCUMENTLISTENER INTERFACE : */ public void insertUpdate(DocumentEvent e) { setModified(true); } public void removeUpdate(DocumentEvent e) { setModified(true); } public void changedUpdate(DocumentEvent e) { setModified(true); } /* ----------------------------------------------------- */ // </editor-fold> // <editor-fold defaultstate="expanded" desc="CaretListener implementation"> public void caretUpdate(CaretEvent e) { this.container.notifyCaretChanged(e); } /* ----------------------------------------------------- */ // </editor-fold> // <editor-fold defaultstate="expanded" desc="UndoableEditListener implementation"> public void undoableEditHappened(UndoableEditEvent evt) { if (evt.getEdit().isSignificant()) { if (!canUndo()) { container.notifyFirstUndoableEditHappened(evt); } } } /* ----------------------------------------------------- */ // </editor-fold> /** 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("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jEditorPane1 = new javax.swing.JEditorPane(); setName("Form"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(glossaeditor.Slang.class).getContext().getResourceMap(EditorView.class); jEditorPane1.setBackground(resourceMap.getColor("jEditorPane1.background")); // NOI18N jEditorPane1.setName("jEditorPane1"); // NOI18N jEditorPane1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jEditorPane1MouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { jEditorPane1MousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { jEditorPane1MouseReleased(evt); } }); jScrollPane1.setViewportView(jEditorPane1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents private void jEditorPane1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jEditorPane1MouseClicked }//GEN-LAST:event_jEditorPane1MouseClicked private void jEditorPane1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jEditorPane1MousePressed if (evt.isPopupTrigger()) { this.popupMenu.show(evt.getComponent(), evt.getX(), evt.getY()); } }//GEN-LAST:event_jEditorPane1MousePressed private void jEditorPane1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jEditorPane1MouseReleased if (evt.isPopupTrigger()) { this.popupMenu.show(evt.getComponent(), evt.getX(), evt.getY()); } }//GEN-LAST:event_jEditorPane1MouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JEditorPane jEditorPane1; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }
5303_10
package api; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; /** * Αυτή η κλάση αναπαριστά ένα κατάλυμα με τα εξής χαρακτηριστικά:το όνομα, τον τύπο του καταλύματος, την τοποθεσία του, την περιγραφή και τις παροχές του. * @author Γεώργιος Δάλλας * @author Χρήστος Θεοφυλακτίδης */ public class Accommodation implements Serializable { private String owner; private String name; private String type; private String address,city,postalCode; private String description; private ArrayList<String> listOfAmenities; /** * Κατασκευαστής που παίρνει ως παράμετρο το username του παρόχου,το όνομα, τον τύπο, την τοποθεσία,μια περιγραφή του καταλύματος και μια λίστα με διάφορα είδη παροχών του για παραμέτρους. * Το κατάλυμα στη συνέχεια αποθηκεύεται στο αρχείο με τα καταλύματα. * @param owner Το username του παρόχου του καταλύματος. * @param name Το όνομα του καταλύματος ή κάποια σύντομη περιγραφή που θα ορίζει ο πάροχος ως όνομα. * @param type Ο τύπος του καταλύματος (πχ ξενοδοχείο, διαμέρισμα, μεζονέτα). * @param address Η τοποθεσία του καταλύματος που απαρτίζεται από τη διεύθυνση, την πόλη και τον ταχυδρομικό κώδικα του. * @param city Η πόλη στην οποία βρίσκεται το κατάλυμα. * @param postalCode Ο ταχυδρομικός κώδικας της περιοχής στην οποία βρίσκεται το κατάλυμα. * @param description Η περιγραφή, στην οποία παρουσιάζονται διάφορα στοιχεία σχετικά με το κατάλυμα. * @param listOfAmenities Μια λίστα με παροχές. */ public Accommodation(String owner, String name, String type, String address, String city, String postalCode, String description, ArrayList<String> listOfAmenities) { this.owner = owner; this.name = name; this.type = type; this.address = address; this.city = city; this.postalCode = postalCode; this.description = description; this.listOfAmenities = listOfAmenities; ArrayList<Accommodation> AccommodationsDB = (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); AccommodationsDB.add(this); FileInteractions.saveToBinaryFile("src/files/accommodations.bin",AccommodationsDB); } /** * Κατασκευαστής που παίρνει ως παράμετρο το username του παρόχου,το όνομα, τον τύπο, την τοποθεσία,μια περιγραφή του καταλύματος. * Το κατάλυμα στη συνέχεια αποθηκεύεται στο αρχείο με τα καταλύματα. * @param owner Το username του παρόχου του καταλύματος. * @param name Το όνομα του καταλύματος ή κάποια σύντομη περιγραφή που θα ορίζει ο πάροχος ως όνομα. * @param type Ο τύπος του καταλύματος (πχ ξενοδοχείο, διαμέρισμα, μεζονέτα). * @param address Η τοποθεσία του καταλύματος που απαρτίζεται από τη διεύθυνση, την πόλη και τον ταχυδρομικό κώδικα του. * @param city Η πόλη στην οποία βρίσκεται το κατάλυμα. * @param postalCode Ο ταχυδρομικός κώδικας της περιοχής στην οποία βρίσκεται το κατάλυμα. * @param description Η περιγραφή, στην οποία παρουσιάζονται διάφορα στοιχεία σχετικά με το κατάλυμα. */ public Accommodation(String owner,String name, String type, String address, String city, String postalCode, String description) { this.owner = owner; this.name = name; this.type = type; this.address = address; this.city = city; this.postalCode = postalCode; this.description = description; this.listOfAmenities = new ArrayList<>(); ArrayList<Accommodation> AccommodationsDB = (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); AccommodationsDB.add(this); FileInteractions.saveToBinaryFile("src/files/accommodations.bin",AccommodationsDB); } /** * Αυτή η μέθοδος δέχεται ως παράμετρο ένα όνομα και το αναθέτει ως όνομα του καταλύματος στο οποίο καλείται. * @param name Το όνομα του καταλύματος. */ public void setName(String name) { this.name = name; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο το είδος καταλύματος και το αναθέτει ως είδος του συγκεκριμένου καταλύματος στο οποίο θα κληθεί. * @param type Τον τύπο του καταλύματος. */ public void setType(String type) { this.type = type; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο την περιγραφή ενός καταλύματος και την αναθέτει ως περιγραφή * στο συγκεκριμένο κατάλυμα όπου και καλείται. * @param description Την περιγραφή του καταλύματος. */ public void setDescription(String description) { this.description = description; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο μια λίστα με παροχές ενός καταλύματος και την αναθέτει * στο συγκεκριμένο κατάλυμα όπου και καλείται. * @param listOfAmenities Τη λίστα με παροχές που προσφέρει του κατάλυμα. */ public void setListOfAmenities(ArrayList<String> listOfAmenities) { this.listOfAmenities = listOfAmenities; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο μια διεύθυνση * και την αναθέτει ως διεύθυνση στο κατάλυμα όπου καλείται. * @param address Τη διεύθυνση του καταλύματος. */ public void setAddress(String address) { this.address = address; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο την πόλη στην οποία βρίσκεται ένα κατάλυμα η και την αναθέτει ως πόλη στην οποία βρίσκεται το κατάλυμα για το οποίο καλείται. * @param city Την πόλη στην οποία βρίσκεται το κατάλυμα. */ public void setCity(String city) { this.city = city; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο τον ταχυδρομικό κώδικα ενός * καταλύματος η και την αναθέτει ως ταχυδρομικό κώδικα στο κατάλυμα που καλείται. * @param postalCode Τον ταχυδρομικό κώδικα του καταλύματος. */ public void setPostalCode(String postalCode) { this.postalCode = postalCode; } /** * Μέθοδος για την επιστροφή του username του παρόχου ενός καταλύματος. * @return το username του παρόχου. */ public String getOwner() { return owner; } /** * Μέθοδος για την επιστροφή του ονόματος ενός καταλύματος. * @return το όνομα του καταλύματος. */ public String getName() { return name; } /** * Μέθοδος για την επιστροφή της περιγραφής ενός καταλύματος. * @return την περιγραφή, στην οποία παρουσιάζονται διάφορα στοιχεία σχετικά με το κατάλυμα. */ public String getDescription() { return description; } /** * Μέθοδος για την επιστροφή του τύπου του καταλύματος (πχ ξενοδοχείο, διαμέρισμα, μεζονέτα). * @return τον τύπο του καταλύματος (πχ ξενοδοχείο). */ public String getType() { return type; } /** * Μέθοδος για την επιστροφή της διεύθυνσης του καταλύματος. * @return τη διεύθυνση του καταλύματος. */ public String getAddress() { return address; } /** * Μέθοδος για την επιστροφή της πόλης στην οποία βρίσκεται το κατάλυμα. * @return τημ πόλη που βρίσκεται το κατάλυμα. */ public String getCity() { return city; } /** * Μέθοδος για την επιστροφή του ταχυδρομικού κώδικα του καταλύματος. * @return τον ταχυδρομικό κώδικα του καταλύματος. */ public String getPostalCode() { return postalCode; } /** * Μέθοδος για την επιστροφή της λίστας με είδη παροχών του καταλύματος. * @return λίστα με είδη παροχών που προσφέρει το κατάλυμα. */ public ArrayList<String> getListOfAmenities() { return listOfAmenities; } /** * Μέθοδος που προσθέτει μία νέα παροχή στη λίστα με τις παροχές του καταλύματος. * @param amenity παροχή του καταλύματος */ public void addAmenity(String amenity){ listOfAmenities.add(amenity); } /** * Αυτή η μέθοδος τροποποιεί ένα κατάλυμα. * @param name το όνομα του καταλύματος * @param type το είδος του καταλύματος * @param address η διεύθυνση του καταλύματος * @param city η πόλη στην οποία βρίσκεται το κατάλυμα * @param postalCode ο ταχυδρομικός κώδικας του καταλύματος * @param description Η περιγραφή του καταλύματος * @param listOfAmenities Η λίστα με τα είδη παροχών τα οποία προσφέρει το κατάλυμα */ public void editAccommodation(String name, String type, String address, String city, String postalCode, String description, ArrayList<String> listOfAmenities){ delete(); setName(name); setType(type); setAddress(address); setCity(city); setPostalCode(postalCode); setDescription(description); setListOfAmenities(listOfAmenities); ArrayList<Accommodation> AccommodationsDB = (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); AccommodationsDB.add(this); FileInteractions.saveToBinaryFile("src/files/accommodations.bin",AccommodationsDB); } /** * Μέθοδος όπου δέχεται μια λίστα με όλες τις αξιολογήσεις και επιστρέφει μια νεα λίστα με όλες τις * αξιολογήσεις ενός συγκεκριμένου καταλύματος * @return Μια λίστα με όλες τις αξιολογήσεις του συγκεκριμένου καταλύματος για το οποίο καλείται. */ public ArrayList<Review> getListOfReviews(){ ArrayList<Review> reviewsDB= (ArrayList<Review>) FileInteractions.loadFromBinaryFile("src/files/reviews.bin"); ArrayList<Review> list = new ArrayList<>(); for (Review r : reviewsDB){ if (r.getAccommodationReviewed().equals(this)){ list.add(r); } } return list; } /** * Μέθοδος επιστροφής του αριθμού αξιολογήσεων ενός καταλύματος. * @return τον αριθμό αξιολογήσεων του καταλύματος. */ public int getNumberOfReviews(){ return getListOfReviews().size(); } /** * Μέθοδος επιστροφής της μέσης βαθμολογίας ενός καταλύματος με βάση τις αξιολογήσεις του. * @return τημ μέση βαθμολογίας ενός καταλύματος. */ public float getAverageRating(){ int sum=0; if(getNumberOfReviews()==0){ return 0; } for(Review r:getListOfReviews()){ sum+=r.getReviewStars(); } return (float) (sum/(float)getNumberOfReviews()); } /** * Μέθοδος διαγραφής του καταλύματος για το οποίο καλείται από το αρχείο με τη λίστα καταλυμάτων. * Η μέθοδος επίσης διαγράφει όλες τις αξιολογήσεις απο το αρχείο με τις αξιολογήσεις που σχετίζονται με το συγκεκριμένο * κατάλυμα */ public void delete(){ ArrayList<Accommodation> AccommodationsDB = (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); ArrayList<Review> ReviewsDB = (ArrayList<Review>) FileInteractions.loadFromBinaryFile("src/files/reviews.bin"); Iterator itr = ReviewsDB.iterator(); while (itr.hasNext()) { Review r = (Review)itr.next(); if(r.getAccommodationReviewed().equals(this)){ itr.remove(); } } Iterator itr2 = AccommodationsDB.iterator(); while (itr2.hasNext()) { Accommodation accom = (Accommodation) itr2.next(); if(accom.equals(this)){ itr2.remove(); } } FileInteractions.saveToBinaryFile("src/files/accommodations.bin",AccommodationsDB); FileInteractions.saveToBinaryFile("src/files/reviews.bin",ReviewsDB); } /** * Μέθοδος που συγκρίνει το όνομα, τον τύπο, την τοποθεσία, την περιγραφή, και την λίστα με παροχές ενός καταλύματος * με ένα άλλο. * @param a το κατάλυμα με το οποίο γίνεται η σύγκριση * @return Επιστρέφει true αν όλες οι προαναφερθέντες τιμές είναι ίσες, αλλιώς επιστρέφει false. */ public boolean equals(Accommodation a){ return this.getAddress().equals(a.getAddress()) && this.getCity().equals(a.getCity()) && this.getPostalCode().equals(a.getPostalCode()) && this.getDescription().equals(a.getDescription()) && this.getListOfAmenities().equals(a.getListOfAmenities()) && this.getName().equals(a.getName()) && this.getType().equals(a.getType()); } }
dallasGeorge/reviewsApp
src/api/Accommodation.java
6,080
/** * Μέθοδος για την επιστροφή του username του παρόχου ενός καταλύματος. * @return το username του παρόχου. */
block_comment
el
package api; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; /** * Αυτή η κλάση αναπαριστά ένα κατάλυμα με τα εξής χαρακτηριστικά:το όνομα, τον τύπο του καταλύματος, την τοποθεσία του, την περιγραφή και τις παροχές του. * @author Γεώργιος Δάλλας * @author Χρήστος Θεοφυλακτίδης */ public class Accommodation implements Serializable { private String owner; private String name; private String type; private String address,city,postalCode; private String description; private ArrayList<String> listOfAmenities; /** * Κατασκευαστής που παίρνει ως παράμετρο το username του παρόχου,το όνομα, τον τύπο, την τοποθεσία,μια περιγραφή του καταλύματος και μια λίστα με διάφορα είδη παροχών του για παραμέτρους. * Το κατάλυμα στη συνέχεια αποθηκεύεται στο αρχείο με τα καταλύματα. * @param owner Το username του παρόχου του καταλύματος. * @param name Το όνομα του καταλύματος ή κάποια σύντομη περιγραφή που θα ορίζει ο πάροχος ως όνομα. * @param type Ο τύπος του καταλύματος (πχ ξενοδοχείο, διαμέρισμα, μεζονέτα). * @param address Η τοποθεσία του καταλύματος που απαρτίζεται από τη διεύθυνση, την πόλη και τον ταχυδρομικό κώδικα του. * @param city Η πόλη στην οποία βρίσκεται το κατάλυμα. * @param postalCode Ο ταχυδρομικός κώδικας της περιοχής στην οποία βρίσκεται το κατάλυμα. * @param description Η περιγραφή, στην οποία παρουσιάζονται διάφορα στοιχεία σχετικά με το κατάλυμα. * @param listOfAmenities Μια λίστα με παροχές. */ public Accommodation(String owner, String name, String type, String address, String city, String postalCode, String description, ArrayList<String> listOfAmenities) { this.owner = owner; this.name = name; this.type = type; this.address = address; this.city = city; this.postalCode = postalCode; this.description = description; this.listOfAmenities = listOfAmenities; ArrayList<Accommodation> AccommodationsDB = (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); AccommodationsDB.add(this); FileInteractions.saveToBinaryFile("src/files/accommodations.bin",AccommodationsDB); } /** * Κατασκευαστής που παίρνει ως παράμετρο το username του παρόχου,το όνομα, τον τύπο, την τοποθεσία,μια περιγραφή του καταλύματος. * Το κατάλυμα στη συνέχεια αποθηκεύεται στο αρχείο με τα καταλύματα. * @param owner Το username του παρόχου του καταλύματος. * @param name Το όνομα του καταλύματος ή κάποια σύντομη περιγραφή που θα ορίζει ο πάροχος ως όνομα. * @param type Ο τύπος του καταλύματος (πχ ξενοδοχείο, διαμέρισμα, μεζονέτα). * @param address Η τοποθεσία του καταλύματος που απαρτίζεται από τη διεύθυνση, την πόλη και τον ταχυδρομικό κώδικα του. * @param city Η πόλη στην οποία βρίσκεται το κατάλυμα. * @param postalCode Ο ταχυδρομικός κώδικας της περιοχής στην οποία βρίσκεται το κατάλυμα. * @param description Η περιγραφή, στην οποία παρουσιάζονται διάφορα στοιχεία σχετικά με το κατάλυμα. */ public Accommodation(String owner,String name, String type, String address, String city, String postalCode, String description) { this.owner = owner; this.name = name; this.type = type; this.address = address; this.city = city; this.postalCode = postalCode; this.description = description; this.listOfAmenities = new ArrayList<>(); ArrayList<Accommodation> AccommodationsDB = (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); AccommodationsDB.add(this); FileInteractions.saveToBinaryFile("src/files/accommodations.bin",AccommodationsDB); } /** * Αυτή η μέθοδος δέχεται ως παράμετρο ένα όνομα και το αναθέτει ως όνομα του καταλύματος στο οποίο καλείται. * @param name Το όνομα του καταλύματος. */ public void setName(String name) { this.name = name; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο το είδος καταλύματος και το αναθέτει ως είδος του συγκεκριμένου καταλύματος στο οποίο θα κληθεί. * @param type Τον τύπο του καταλύματος. */ public void setType(String type) { this.type = type; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο την περιγραφή ενός καταλύματος και την αναθέτει ως περιγραφή * στο συγκεκριμένο κατάλυμα όπου και καλείται. * @param description Την περιγραφή του καταλύματος. */ public void setDescription(String description) { this.description = description; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο μια λίστα με παροχές ενός καταλύματος και την αναθέτει * στο συγκεκριμένο κατάλυμα όπου και καλείται. * @param listOfAmenities Τη λίστα με παροχές που προσφέρει του κατάλυμα. */ public void setListOfAmenities(ArrayList<String> listOfAmenities) { this.listOfAmenities = listOfAmenities; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο μια διεύθυνση * και την αναθέτει ως διεύθυνση στο κατάλυμα όπου καλείται. * @param address Τη διεύθυνση του καταλύματος. */ public void setAddress(String address) { this.address = address; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο την πόλη στην οποία βρίσκεται ένα κατάλυμα η και την αναθέτει ως πόλη στην οποία βρίσκεται το κατάλυμα για το οποίο καλείται. * @param city Την πόλη στην οποία βρίσκεται το κατάλυμα. */ public void setCity(String city) { this.city = city; } /** * Αυτή η μέθοδος δέχεται ως παράμετρο τον ταχυδρομικό κώδικα ενός * καταλύματος η και την αναθέτει ως ταχυδρομικό κώδικα στο κατάλυμα που καλείται. * @param postalCode Τον ταχυδρομικό κώδικα του καταλύματος. */ public void setPostalCode(String postalCode) { this.postalCode = postalCode; } /** * Μέθοδος για την<SUF>*/ public String getOwner() { return owner; } /** * Μέθοδος για την επιστροφή του ονόματος ενός καταλύματος. * @return το όνομα του καταλύματος. */ public String getName() { return name; } /** * Μέθοδος για την επιστροφή της περιγραφής ενός καταλύματος. * @return την περιγραφή, στην οποία παρουσιάζονται διάφορα στοιχεία σχετικά με το κατάλυμα. */ public String getDescription() { return description; } /** * Μέθοδος για την επιστροφή του τύπου του καταλύματος (πχ ξενοδοχείο, διαμέρισμα, μεζονέτα). * @return τον τύπο του καταλύματος (πχ ξενοδοχείο). */ public String getType() { return type; } /** * Μέθοδος για την επιστροφή της διεύθυνσης του καταλύματος. * @return τη διεύθυνση του καταλύματος. */ public String getAddress() { return address; } /** * Μέθοδος για την επιστροφή της πόλης στην οποία βρίσκεται το κατάλυμα. * @return τημ πόλη που βρίσκεται το κατάλυμα. */ public String getCity() { return city; } /** * Μέθοδος για την επιστροφή του ταχυδρομικού κώδικα του καταλύματος. * @return τον ταχυδρομικό κώδικα του καταλύματος. */ public String getPostalCode() { return postalCode; } /** * Μέθοδος για την επιστροφή της λίστας με είδη παροχών του καταλύματος. * @return λίστα με είδη παροχών που προσφέρει το κατάλυμα. */ public ArrayList<String> getListOfAmenities() { return listOfAmenities; } /** * Μέθοδος που προσθέτει μία νέα παροχή στη λίστα με τις παροχές του καταλύματος. * @param amenity παροχή του καταλύματος */ public void addAmenity(String amenity){ listOfAmenities.add(amenity); } /** * Αυτή η μέθοδος τροποποιεί ένα κατάλυμα. * @param name το όνομα του καταλύματος * @param type το είδος του καταλύματος * @param address η διεύθυνση του καταλύματος * @param city η πόλη στην οποία βρίσκεται το κατάλυμα * @param postalCode ο ταχυδρομικός κώδικας του καταλύματος * @param description Η περιγραφή του καταλύματος * @param listOfAmenities Η λίστα με τα είδη παροχών τα οποία προσφέρει το κατάλυμα */ public void editAccommodation(String name, String type, String address, String city, String postalCode, String description, ArrayList<String> listOfAmenities){ delete(); setName(name); setType(type); setAddress(address); setCity(city); setPostalCode(postalCode); setDescription(description); setListOfAmenities(listOfAmenities); ArrayList<Accommodation> AccommodationsDB = (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); AccommodationsDB.add(this); FileInteractions.saveToBinaryFile("src/files/accommodations.bin",AccommodationsDB); } /** * Μέθοδος όπου δέχεται μια λίστα με όλες τις αξιολογήσεις και επιστρέφει μια νεα λίστα με όλες τις * αξιολογήσεις ενός συγκεκριμένου καταλύματος * @return Μια λίστα με όλες τις αξιολογήσεις του συγκεκριμένου καταλύματος για το οποίο καλείται. */ public ArrayList<Review> getListOfReviews(){ ArrayList<Review> reviewsDB= (ArrayList<Review>) FileInteractions.loadFromBinaryFile("src/files/reviews.bin"); ArrayList<Review> list = new ArrayList<>(); for (Review r : reviewsDB){ if (r.getAccommodationReviewed().equals(this)){ list.add(r); } } return list; } /** * Μέθοδος επιστροφής του αριθμού αξιολογήσεων ενός καταλύματος. * @return τον αριθμό αξιολογήσεων του καταλύματος. */ public int getNumberOfReviews(){ return getListOfReviews().size(); } /** * Μέθοδος επιστροφής της μέσης βαθμολογίας ενός καταλύματος με βάση τις αξιολογήσεις του. * @return τημ μέση βαθμολογίας ενός καταλύματος. */ public float getAverageRating(){ int sum=0; if(getNumberOfReviews()==0){ return 0; } for(Review r:getListOfReviews()){ sum+=r.getReviewStars(); } return (float) (sum/(float)getNumberOfReviews()); } /** * Μέθοδος διαγραφής του καταλύματος για το οποίο καλείται από το αρχείο με τη λίστα καταλυμάτων. * Η μέθοδος επίσης διαγράφει όλες τις αξιολογήσεις απο το αρχείο με τις αξιολογήσεις που σχετίζονται με το συγκεκριμένο * κατάλυμα */ public void delete(){ ArrayList<Accommodation> AccommodationsDB = (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); ArrayList<Review> ReviewsDB = (ArrayList<Review>) FileInteractions.loadFromBinaryFile("src/files/reviews.bin"); Iterator itr = ReviewsDB.iterator(); while (itr.hasNext()) { Review r = (Review)itr.next(); if(r.getAccommodationReviewed().equals(this)){ itr.remove(); } } Iterator itr2 = AccommodationsDB.iterator(); while (itr2.hasNext()) { Accommodation accom = (Accommodation) itr2.next(); if(accom.equals(this)){ itr2.remove(); } } FileInteractions.saveToBinaryFile("src/files/accommodations.bin",AccommodationsDB); FileInteractions.saveToBinaryFile("src/files/reviews.bin",ReviewsDB); } /** * Μέθοδος που συγκρίνει το όνομα, τον τύπο, την τοποθεσία, την περιγραφή, και την λίστα με παροχές ενός καταλύματος * με ένα άλλο. * @param a το κατάλυμα με το οποίο γίνεται η σύγκριση * @return Επιστρέφει true αν όλες οι προαναφερθέντες τιμές είναι ίσες, αλλιώς επιστρέφει false. */ public boolean equals(Accommodation a){ return this.getAddress().equals(a.getAddress()) && this.getCity().equals(a.getCity()) && this.getPostalCode().equals(a.getPostalCode()) && this.getDescription().equals(a.getDescription()) && this.getListOfAmenities().equals(a.getListOfAmenities()) && this.getName().equals(a.getName()) && this.getType().equals(a.getType()); } }
12856_3
/* * 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 accounts; import java.util.ArrayList; import java.util.List; /** * * @author mac */ public class BankAccount { // Object private int number; // βλεπω περιεχομενο ενος field == getter private double amount; // αλλάζω περιεχόμενο ... == setter private String name; private boolean active; private List<String> transactions; public BankAccount() { this.active = true; transactions = new ArrayList<String>(); setTransaction(0, 'C'); } public BankAccount(String name, int number) { this(); this.name = name; this.number = number; setTransaction(0, 'C'); } public BankAccount(String name, int number, double amount, boolean active) { this(name, number); this.amount = amount; this.active = active; setTransaction(amount, 'C'); } public void setNumber(int number) { if (number == 0) { this.number = 100; } else { this.number = number; } } public int getNumber() { return this.number; } // public void setAmount(double amount) { // this.amount = amount; // } DANGEROUS - DO NOT TRY THIS AT HOME public void deposit(double amount) { this.amount += amount; setTransaction(amount, 'D'); } public double getAmount() { return (this.amount); } public double withdraw(double amount) { if (amount <= this.amount) { this.amount -= amount; // this.amount -> 1000, double amount = 1200 // transactions.add("withdrawal amount: " + amount); setTransaction(amount, 'W'); // (100, "W") withdrawal, (50, "D") deposit, (0, "C") creation return (amount); } else { // 1. deny the withrawal return (amount); // 2. withdraw available funds // double temp_amount = this.amount; // setTransaction(temp_amount, 'W'); // this.amount -= this.amount; // return(temp_amount); } } public void setName(String name) { this.name = name; } public String getName() { return (this.name); } public void setActive(boolean active) { this.active = active; } public boolean getActive() { return (this.active); } public void setTransactions(List<String> transactions) { this.transactions = transactions; } public List<String> getTransactions() { return (this.transactions); } public void setTransaction(double amount, char type) { switch (type) { case 'C': transactions.add("Creation of account with amount " + amount + " at " + java.time.LocalDateTime.now()); break; case 'D': transactions.add("Deposit of amount: " + amount + " at " + java.time.LocalDateTime.now()); break; case 'W': transactions.add("Withdrawal of amount: " + amount + " at " + java.time.LocalDateTime.now()); break; } } @Override // String name, int number, double amount, boolean active public String toString() { return ("BankAccount[name: " + name + ", number: " + number + ", amount: " + amount + ", active: " + active + "]"); } }
davidoster/BankAccounts
src/accounts/BankAccount.java
895
// αλλάζω περιεχόμενο ... == setter
line_comment
el
/* * 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 accounts; import java.util.ArrayList; import java.util.List; /** * * @author mac */ public class BankAccount { // Object private int number; // βλεπω περιεχομενο ενος field == getter private double amount; // αλλάζω περιεχόμενο<SUF> private String name; private boolean active; private List<String> transactions; public BankAccount() { this.active = true; transactions = new ArrayList<String>(); setTransaction(0, 'C'); } public BankAccount(String name, int number) { this(); this.name = name; this.number = number; setTransaction(0, 'C'); } public BankAccount(String name, int number, double amount, boolean active) { this(name, number); this.amount = amount; this.active = active; setTransaction(amount, 'C'); } public void setNumber(int number) { if (number == 0) { this.number = 100; } else { this.number = number; } } public int getNumber() { return this.number; } // public void setAmount(double amount) { // this.amount = amount; // } DANGEROUS - DO NOT TRY THIS AT HOME public void deposit(double amount) { this.amount += amount; setTransaction(amount, 'D'); } public double getAmount() { return (this.amount); } public double withdraw(double amount) { if (amount <= this.amount) { this.amount -= amount; // this.amount -> 1000, double amount = 1200 // transactions.add("withdrawal amount: " + amount); setTransaction(amount, 'W'); // (100, "W") withdrawal, (50, "D") deposit, (0, "C") creation return (amount); } else { // 1. deny the withrawal return (amount); // 2. withdraw available funds // double temp_amount = this.amount; // setTransaction(temp_amount, 'W'); // this.amount -= this.amount; // return(temp_amount); } } public void setName(String name) { this.name = name; } public String getName() { return (this.name); } public void setActive(boolean active) { this.active = active; } public boolean getActive() { return (this.active); } public void setTransactions(List<String> transactions) { this.transactions = transactions; } public List<String> getTransactions() { return (this.transactions); } public void setTransaction(double amount, char type) { switch (type) { case 'C': transactions.add("Creation of account with amount " + amount + " at " + java.time.LocalDateTime.now()); break; case 'D': transactions.add("Deposit of amount: " + amount + " at " + java.time.LocalDateTime.now()); break; case 'W': transactions.add("Withdrawal of amount: " + amount + " at " + java.time.LocalDateTime.now()); break; } } @Override // String name, int number, double amount, boolean active public String toString() { return ("BankAccount[name: " + name + ", number: " + number + ", amount: " + amount + ", active: " + active + "]"); } }
2440_4
/* * 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 johnandannandjerry; import java.util.ArrayList; import java.util.List; import johnandannandjerry.models.Cat; import johnandannandjerry.models.House; import johnandannandjerry.models.Human; import johnandannandjerry.models.Mammal; import johnandannandjerry.models.Mouse; /** * * @author mac */ public class JohnAndAnnAndJerry { /** * @param args the command line arguments */ public static void main(String[] args) { // Mammal john = new Human(); // CORRECT /* Έστω οτι ο Γιάννης έχει ένα σπίτι. Το σπίτι χωρίζεται στο κεντρικό μέρος που μένει και την αυλή. Για να πάει κάποιος στην αυλή πρέπει να ανοίξει μια πόρτα από το εσωτερικό του σπιτιού. Στο σπίτι μαζί με τον Γιάννη μένει και η γάτα του που λέγεται Άννα. Κάποια στιγμή ο Γιάννης ανοίγει την μεσόπορτα και η Άννα τρέχει στον κήπο. Ξαφνικά ο Γιάννης συνειδητοποιεί οτι η Άννα σταμάτησε ξαφνικά και κοιτάζει επίμονα προ μια κατεύθυνση. Πλησιάζει στην μεσόπορτα ο Γιάννης και βλέπει την Άννα να κοιτάζει ένα ποντίκι τον Τζέρυ. Ο Τζέρυ κοιτάζει την Άννα και ξεκινάει και τρέχει. */ Human john = new Human(); john.setName("John"); Mammal anna = new Cat(); anna.setName("Anna"); Mammal jerry = new Mouse(); jerry.setName("Jerry"); List<Mammal> mammals = new ArrayList<>(); mammals.add(john); mammals.add(anna); mammals.add(jerry); House house = new House("John's House", mammals); john.opensDoor(house.getGarden().getDoor()); } }
davidoster/JohnAndAnnAndJerry
src/johnandannandjerry/JohnAndAnnAndJerry.java
854
/* Έστω οτι ο Γιάννης έχει ένα σπίτι. Το σπίτι χωρίζεται στο κεντρικό μέρος που μένει και την αυλή. Για να πάει κάποιος στην αυλή πρέπει να ανοίξει μια πόρτα από το εσωτερικό του σπιτιού. Στο σπίτι μαζί με τον Γιάννη μένει και η γάτα του που λέγεται Άννα. Κάποια στιγμή ο Γιάννης ανοίγει την μεσόπορτα και η Άννα τρέχει στον κήπο. Ξαφνικά ο Γιάννης συνειδητοποιεί οτι η Άννα σταμάτησε ξαφνικά και κοιτάζει επίμονα προ μια κατεύθυνση. Πλησιάζει στην μεσόπορτα ο Γιάννης και βλέπει την Άννα να κοιτάζει ένα ποντίκι τον Τζέρυ. Ο Τζέρυ κοιτάζει την Άννα και ξεκινάει και τρέχει. */
block_comment
el
/* * 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 johnandannandjerry; import java.util.ArrayList; import java.util.List; import johnandannandjerry.models.Cat; import johnandannandjerry.models.House; import johnandannandjerry.models.Human; import johnandannandjerry.models.Mammal; import johnandannandjerry.models.Mouse; /** * * @author mac */ public class JohnAndAnnAndJerry { /** * @param args the command line arguments */ public static void main(String[] args) { // Mammal john = new Human(); // CORRECT /* Έστω οτι ο<SUF>*/ Human john = new Human(); john.setName("John"); Mammal anna = new Cat(); anna.setName("Anna"); Mammal jerry = new Mouse(); jerry.setName("Jerry"); List<Mammal> mammals = new ArrayList<>(); mammals.add(john); mammals.add(anna); mammals.add(jerry); House house = new House("John's House", mammals); john.opensDoor(house.getGarden().getDoor()); } }
342_8
/* * 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 afdemp.org; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author George.Pasparakis */ public class Questions extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //File file = new File("/quiz2.json"); //BufferedReader br = new BufferedReader(new FileReader(file)); //String st; //response.setContentType("application/json;charset=UTF-8"); response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS, DELETE"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Max-Age", "86400"); //while((st = br.readLine()) != null) out.println(); out.println("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."); /* out.println("[\n" + " {\n" + " \"questions\": [\"Tι είναι το Coding Bootcamp;\",\"Ποια είναι η διαδικασία επιλογής των υποψηφίων;\",\"Υπάρχει κάποιο όριο ηλικίας για τη συμμετοχή στο πρόγραμμα;\",\"Ποιο είναι το κόστος του προγράμματος;\",\"Θα βρω εργασία ως προγραμματιστής με τη λήξη του Bootcamp;\",\"Που γίνονται τα μαθήματα;\",\"Πόσο διαρκεί το πρόγραμμα μαθημάτων;\",\"Ποιος θα κάτσει στον Σιδερένιο Θρόνο στο Game of Thrones;\",\"Ποια τραγουδίστρια θα παρουσιάσει το 7 Rings στα Billboard Music Awards 2019;\",\"Ποιος από τους παρακάτω οδηγούς θα κερδίσει το Ισπανικό Grand Prix της F1 στην Ισπανία;\"]\n" + " \n" + " },\n" + " {\n" + " \"answers\": \n" + " {\n" + " \"1\": [\"Μια σχολή πολεμικών τεχνών για προγραμματιστές\",\"Ένα ιδιαίτερα εντατικό πρόγραμμα το οποίο παρέχει ταχύρρυθμη εκπαίδευση και πιστοποίηση στον τομέα του προγραμματισμού\",\"Δεν ξέρω\",\"Ήρθα για να μάθω\"],\n" + " \"2\": [\"Να είσαι παθιασμένος με τον Προγραμματισμό\",\"Να είσαι προετοιμασμένος να εργαστείς σκληρά καθώς το πρόγραμμα είναι πολύ απαιτητικό\",\"Να γνωρίζεις καλά Αγγλικά (Επίπεδο Β2)\",\"Όλα τα παραπάνω\"],\n" + " \"3\": [\"Ναι, από βρέφος έως 175 ετών\",\"Όχι δεν υπάρχει\",\"Ίσως αλλά δεν μου το λένε\",\"Κανένα από τα παραπάνω\"],\n" + " \"4\": [\"Άκουσα ότι θα με πληρώσουν 2500 ευρώ για να παρακολουθήσω\",\"Ίσως πρέπει να πληρώσω κάποια συνδρομή, 5 ευρώ το μήνα\",\"Νομίζω κοστίζει 200 το μήνα\",\"Το κόστος είναι 2500 ευρώ\"],\n" + " \"5\": [\"Δεν νομίζω\",\"Έτσι διαφημίζουν\",\"Έχει υψηλό ποσοστό απασχολησιμότητας\",\"Μόνο εφόσον ακολουθήσω πιστά το πρόγραμμα\"],\n" + " \"6\": [\"Στην παραλία\",\"Σε διάφορα νησιά της Ελλάδας\",\"Σε σύγχρονες εγκαταστάσεις στο κέντρο της Αθήνας\",\"Διαδικτυακά\"],\n" + " \"7\": [\"3 μήνες\",\"6 μήνες\",\"500 ώρες\",\"3 ή 6 μήνες με σύνολο 500 ώρες μαθημάτων\"],\n" + " \"8\": [\"ο δράκος\",\"ο Τζον Σνόου\",\"ο Σάμγουελ Τάρλυ\",\"ο Χόντορ\"],\n" + " \"9\": [\"Jennifer Lopez\",\"Άννα Βίσση\",\"Ariana Grande\",\"Rihanna\"],\n" + " \"10\": [\"Ποπάυ\",\"Spider Man\",\"Superman\",\"Chuck Norris\"]\n" + " }\n" + " },\n" + " {\n" + " \"correct\": [1,3,1,3,3,2,3,1,2,3]\n" + " }\n" + "]");*/ out.flush(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
davidoster/Simple-Servlets-with-CORS
src/java/afdemp/org/Questions.java
2,466
/* out.println("[\n" + " {\n" + " \"questions\": [\"Tι είναι το Coding Bootcamp;\",\"Ποια είναι η διαδικασία επιλογής των υποψηφίων;\",\"Υπάρχει κάποιο όριο ηλικίας για τη συμμετοχή στο πρόγραμμα;\",\"Ποιο είναι το κόστος του προγράμματος;\",\"Θα βρω εργασία ως προγραμματιστής με τη λήξη του Bootcamp;\",\"Που γίνονται τα μαθήματα;\",\"Πόσο διαρκεί το πρόγραμμα μαθημάτων;\",\"Ποιος θα κάτσει στον Σιδερένιο Θρόνο στο Game of Thrones;\",\"Ποια τραγουδίστρια θα παρουσιάσει το 7 Rings στα Billboard Music Awards 2019;\",\"Ποιος από τους παρακάτω οδηγούς θα κερδίσει το Ισπανικό Grand Prix της F1 στην Ισπανία;\"]\n" + " \n" + " },\n" + " {\n" + " \"answers\": \n" + " {\n" + " \"1\": [\"Μια σχολή πολεμικών τεχνών για προγραμματιστές\",\"Ένα ιδιαίτερα εντατικό πρόγραμμα το οποίο παρέχει ταχύρρυθμη εκπαίδευση και πιστοποίηση στον τομέα του προγραμματισμού\",\"Δεν ξέρω\",\"Ήρθα για να μάθω\"],\n" + " \"2\": [\"Να είσαι παθιασμένος με τον Προγραμματισμό\",\"Να είσαι προετοιμασμένος να εργαστείς σκληρά καθώς το πρόγραμμα είναι πολύ απαιτητικό\",\"Να γνωρίζεις καλά Αγγλικά (Επίπεδο Β2)\",\"Όλα τα παραπάνω\"],\n" + " \"3\": [\"Ναι, από βρέφος έως 175 ετών\",\"Όχι δεν υπάρχει\",\"Ίσως αλλά δεν μου το λένε\",\"Κανένα από τα παραπάνω\"],\n" + " \"4\": [\"Άκουσα ότι θα με πληρώσουν 2500 ευρώ για να παρακολουθήσω\",\"Ίσως πρέπει να πληρώσω κάποια συνδρομή, 5 ευρώ το μήνα\",\"Νομίζω κοστίζει 200 το μήνα\",\"Το κόστος είναι 2500 ευρώ\"],\n" + " \"5\": [\"Δεν νομίζω\",\"Έτσι διαφημίζουν\",\"Έχει υψηλό ποσοστό απασχολησιμότητας\",\"Μόνο εφόσον ακολουθήσω πιστά το πρόγραμμα\"],\n" + " \"6\": [\"Στην παραλία\",\"Σε διάφορα νησιά της Ελλάδας\",\"Σε σύγχρονες εγκαταστάσεις στο κέντρο της Αθήνας\",\"Διαδικτυακά\"],\n" + " \"7\": [\"3 μήνες\",\"6 μήνες\",\"500 ώρες\",\"3 ή 6 μήνες με σύνολο 500 ώρες μαθημάτων\"],\n" + " \"8\": [\"ο δράκος\",\"ο Τζον Σνόου\",\"ο Σάμγουελ Τάρλυ\",\"ο Χόντορ\"],\n" + " \"9\": [\"Jennifer Lopez\",\"Άννα Βίσση\",\"Ariana Grande\",\"Rihanna\"],\n" + " \"10\": [\"Ποπάυ\",\"Spider Man\",\"Superman\",\"Chuck Norris\"]\n" + " }\n" + " },\n" + " {\n" + " \"correct\": [1,3,1,3,3,2,3,1,2,3]\n" + " }\n" + "]");*/
block_comment
el
/* * 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 afdemp.org; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author George.Pasparakis */ public class Questions extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //File file = new File("/quiz2.json"); //BufferedReader br = new BufferedReader(new FileReader(file)); //String st; //response.setContentType("application/json;charset=UTF-8"); response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS, DELETE"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Max-Age", "86400"); //while((st = br.readLine()) != null) out.println(); out.println("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."); /* out.println("[\n" + "<SUF>*/ out.flush(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
16450_46
import java.util.Map; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Arrays; import java.util.ArrayList; import visitor.GJNoArguDepthFirst; import syntaxtree.*; public class TypeChecker extends GJNoArguDepthFirst< String >{ private String className; // The className of the class we are into private String methodName; // The methodName of the class we are into private Map <String, Data> symbol_table; // The symbol table we construct later with the DeclCollector // Constructor TypeChecker(Map <String, Data> symbol_table){ this.symbol_table = symbol_table; this.className = null; this.methodName = null; } // Check if the given type is primitive private boolean isPrimitive(String type){ if(type != "int[]" && type != "boolean[]" && type != "boolean" && type != "int") return false; return true; } // Check if the child type is SubType of another type private boolean isSubType(String childType, String parentType){ // If the childType is primitive then it must be identicall with parentType if(isPrimitive(childType) || isPrimitive(parentType)) return childType.equals(parentType); while(childType != null){ if(childType.equals(parentType)) return true; childType = symbol_table.get(childType).getName(); } return false; } // Check if a variable, method, or class has been declared // Throw SemanticError if not! private void CheckForDeclaration(String value, String classname, int mode) throws Exception { Boolean varFlag = false; Boolean methodFlag = false; Boolean classFlag = false; if(mode == 0){ varFlag = CheckForVarDeclaration(value, classname); if(!varFlag) throw new SemanticError(); } else if(mode == 1){ methodFlag = CheckForMethodDeclaration(value, classname); if(!methodFlag) throw new SemanticError(); } else if(mode == 2){ classFlag = CheckForClassDeclaration(value); if(!classFlag) throw new SemanticError(); } else if (mode == 3){ classFlag = CheckForVarDeclaration(value, classname); methodFlag = CheckForMethodDeclaration(value, classname); if(!varFlag && !methodFlag) throw new SemanticError(); } else{ varFlag = CheckForVarDeclaration(value, classname); methodFlag = CheckForMethodDeclaration(value, classname); classFlag = CheckForClassDeclaration(value); if(!varFlag && !methodFlag && !classFlag) throw new SemanticError(); } } // Returns true if a var has been declared // false if not. // We have already push any inherited method or field to the child // so we dont need to check for redaclaration recursivly private boolean CheckForVarDeclaration(String var, String classname){ Data data = symbol_table.get(classname); if(data == null) return false; // Check for decleration . if(data.getVars().containsKey(var)) return true; if(methodName != null && data.getMethods().get(methodName) != null){ if(data.getMethods().get(methodName).getArgs().containsKey(var)) return true; if(data.getMethods().get(methodName).getVars().containsKey(var)) return true; } return false; } private boolean CheckForMethodDeclaration(String method, String classname){ if (symbol_table.get(classname).getMethods().containsKey(method)) return true; return false; } private boolean CheckForClassDeclaration(String class_){ return symbol_table.containsKey(class_); } // Get the type of the variable. // Precedence: method variables, method args > classe's fields private String getVarType(String var, String classname){ Data data = symbol_table.get(classname); String parentClassName = symbol_table.get(classname).getName(); if(methodName != null && data.getMethods().get(methodName) != null){ if (data.getMethods().get(methodName).getVars().containsKey(var)) return data.getMethods().get(methodName).getVars().get(var); if(data.getMethods().get(methodName).getArgs().containsKey(var)) return data.getMethods().get(methodName).getArgs().get(var); } if(data.getVars().containsKey(var)) return data.getVars().get(var).getType(); return null; } /** Goal * f0 -> MainClass() * f1 -> ( TypeDeclaration() )* */ public String visit(Goal n) throws Exception { // Accept at main class n.f0.accept(this); // When a production has a * it means that this production can appear // zero or more times. So for the ( TypeDeclaration() )* f.e. we need to // iterate all the classes declarations. for( int i = 0; i < n.f1.size(); i++ ) n.f1.elementAt(i).accept(this); return null; } /** MainClass * f1 -> Identifier() { void main ( String[] * f11 -> Identifier() * f14 -> ( VarDeclaration() )* * f15 -> ( Statement() )* * class f1 { void main ( String[] f11 ){ f14 f15 } } */ public String visit(MainClass n) throws Exception { // Keep the name of the "main" class className = n.f1.accept(this); // Go down through the parse Tree for checking for( int i = 0; i < n.f14.size(); i++ ) n.f14.elementAt(i).accept(this); for( int i = 0; i < n.f15.size(); i++ ) n.f15.elementAt(i).accept(this); return null; } /** TypeDeclaration * f0 -> ClassDeclaration() * | ClassExtendsDeclaration() */ public String visit(TypeDeclaration n) throws Exception { n.f0.accept(this); return null; } /** ClassDeclaration * f1 -> Identifier() * f3 -> ( VarDeclaration() )* * f4 -> ( MethodDeclaration() )* class f1 { f3 f4 } */ public String visit(ClassDeclaration n) throws Exception { // Keep the name of the "main" class className = n.f1.accept(this); // Go down through the parse Tree for checking for( int i = 0; i < n.f3.size(); i++ ) n.f3.elementAt(i).accept(this); for( int i = 0; i < n.f4.size(); i++ ) n.f4.elementAt(i).accept(this); return null; } /** ClassExtendsDeclaration * f1 -> Identifier() * f3 -> Identifier() * f5 -> ( VarDeclaration() )* * f6 -> ( MethodDeclaration() )* class f1 extends f3{ f5 f6 } */ public String visit(ClassExtendsDeclaration n) throws Exception { // Keep the name of the class className = n.f1.accept(this); // Check if the name of the parent class not existed inside the symbol table. // If it does not that means we have declare a class whose parent class has not been declared yet. // We do not want that => Throw Semantic Error! String parent_name = n.f3.accept(this); if(!symbol_table.containsKey(parent_name)) throw new SemanticError(); // Go down through the parse Tree for checking for( int i = 0; i < n.f5.size(); i++ ) n.f5.elementAt(i).accept(this); for( int i = 0; i < n.f6.size(); i++ ) n.f6.elementAt(i).accept(this); return null; } /** VarDeclaration * f0 -> Type() * f1 -> Identifier() * f2 -> ";" */ public String visit(VarDeclaration n) throws Exception { // Keep the type off the var and go down into the parse tree. String var_type = n.f0.accept(this); n.f1.accept(this); // The type of the variable(class) has not been declared. if(!isPrimitive(var_type) && !symbol_table.containsKey(var_type)) throw new SemanticError(); return null; } /** MethodDeclaration * f1 -> Type() * f2 -> Identifier() * f4 -> ( FormalParameterList() )? * f7 -> ( VarDeclaration() )* * f8 -> ( Statement() )* * f10 -> Expression() * public f1 f2( f4 ){ f7 f8 return f10; } */ public String visit(MethodDeclaration n) throws Exception { // Get methods return type. String method_RetType = n.f1.accept(this); // Get methods name and update methodName just to // know at what method we are into. String method_name = n.f2.accept(this); methodName = method_name; // We need to check if type is different from (int, boolean, int[], boolean[]) or the other non-primitive types. // if it is => Throw Semantic Error! if(!isPrimitive(method_RetType) && !symbol_table.containsKey(method_RetType)) throw new SemanticError(); if(n.f4.present()) n.f4.accept(this); // Accept to go through the parse tree for( int i = 0; i < n.f7.size(); i++ ) n.f7.elementAt(i).accept(this); for( int i = 0; i < n.f8.size(); i++ ) n.f8.elementAt(i).accept(this); // The return type of the return statement need to match with // the return type of this method or a sub type of it. // If it does not => Throw Semantic Error! String value_RetType = n.f10.accept(this); if(!(value_RetType).equals(method_RetType) && !isSubType(value_RetType, method_RetType)) // μπορει να ειναι και υποτυπος. throw new SemanticError(); methodName = null; return null; } /** FormalParameterList * f0 -> FormalParameter() * f1 -> FormalParameterTail() */ // Go through the parse Tree we have already collect the data public String visit(FormalParameterList n) throws Exception { n.f0.accept(this); n.f1.accept(this); return null; } /** FormalParameter * f0 -> Type() * f1 -> Identifier() */ public String visit(FormalParameter n) throws Exception { String type = n.f0.accept(this); String name = n.f1.accept(this); // We need to check if type is different from (int, boolean, int[], boolean[]) or the other non-primitive types. // if it is => Throw Semantic Error! if(!isPrimitive(type) && !symbol_table.containsKey(type)) throw new SemanticError(); return null; } /** FormalParameterTail * f0 -> ( FormalParameterTerm() )* */ public String visit(FormalParameterTail n) throws Exception { for( int i = 0; i < n.f0.size(); i++ ) n.f0.elementAt(i).accept(this); return null; } /** FormalParameterTerm * f0 -> "," * f1 -> FormalParameter() */ public String visit(FormalParameterTerm n) throws Exception { n.f1.accept(this); return null; } /** Type * f0 -> ArrayType() * | BooleanType() * | IntegerType() * | Identifier() */ public String visit(Type n) throws Exception { return n.f0.accept(this); } /** ArrayType * f0 -> BooleanArrayType() * | IntegerArrayType() */ public String visit(ArrayType n) throws Exception { return n.f0.accept(this); } /** BooleanArrayType * f0 -> "boolean" * f1 -> "[" * f2 -> "]" */ public String visit(BooleanArrayType n) throws Exception { return "boolean[]"; } /** IntegerArrayType * f0 -> "int" * f1 -> "[" * f2 -> "]" */ public String visit(IntegerArrayType n) throws Exception { return "int[]"; } /** BooleanType * f0 -> "boolean" */ public String visit(BooleanType n) throws Exception { return "boolean"; } /** IntegerType * f0 -> "int" */ public String visit(IntegerType n) throws Exception { return "int"; } /** Statement * f0 -> Block() * | AssignmentStatement() * | ArrayAssignmentStatement() * | IfStatement() * | WhileStatement() * | PrintStatement() */ // Go through the parse Tree public String visit(Statement n) throws Exception { n.f0.accept(this); return null; } /** Block * f0 -> "{" * f1 -> ( Statement() )* * f2 -> "}" { f1 } */ // Go through the parse Tree public String visit(Block n) throws Exception { for( int i = 0; i < n.f1.size(); i++ ) n.f1.elementAt(i).accept(this); return null; } /** AssignmentStatement * f0 -> Identifier() * f1 -> "=" * f2 -> Expression() * f3 -> ";" f0 = f2; */ public String visit(AssignmentStatement n) throws Exception { // Check if the var(f0) has been declared. // If not => Throw Semantic Error! String var = n.f0.accept(this); CheckForDeclaration(var, className, 0); String idType = getVarType(var, className); // Check if the type of the expression match the type of the identifier // or a sub type of it. // If not => Throw Semantic Error! String exp_type = n.f2.accept(this); if(!exp_type.equals(idType) && !isSubType(exp_type, idType)) throw new SemanticError(); return null; } /** ArrayAssignmentStatement * f0 -> Identifier() * f1 -> "[" * f2 -> Expression() * f3 -> "]" * f4 -> "=" * f5 -> Expression() * f6 -> ";" f0[f2]=f5; */ public String visit(ArrayAssignmentStatement n) throws Exception { // Check for delcaration String id = n.f0.accept(this); CheckForDeclaration(id, className, 4); // The type of the f0 must be an array type String idType = getVarType(id, className); if(idType == null || (!idType.equals("int[]") && !idType.equals("boolean[]"))) throw new SemanticError(); // Check if the type of the expression f2 is interger. // If not => Throw Semantic Error! if(!n.f2.accept(this).equals("int")) throw new SemanticError(); // Check if the type of the expression is either int or boolean // cause only these two types of arrays we could have. // If not => Throw Semantic Error! String expType = n.f5.accept(this); if(!expType.equals("int") && !expType.equals("boolean")) throw new SemanticError(); return null; } /** IfStatement * f0 -> "if" * f1 -> "(" * f2 -> Expression() * f3 -> ")" * f4 -> Statement() * f5 -> "else" * f6 -> Statement() if (f2){ f4 } else{ f6 } */ public String visit(IfStatement n) throws Exception { // Check if the type of the expression is boolean. // If not => Throw Semantic Error! if(!n.f2.accept(this).equals("boolean")) throw new SemanticError(); n.f4.accept(this); n.f6.accept(this); return null; } /** WhileStatement * f0 -> "while" * f1 -> "(" * f2 -> Expression() * f3 -> ")" * f4 -> Statement() while(f2){ f4 } */ public String visit(WhileStatement n) throws Exception { // Check if the type of the expression is boolean. // If not => Throw Semantic Error! if(!n.f2.accept(this).equals("boolean")) throw new SemanticError(); n.f4.accept(this); return null; } /** PrintStatement * f0 -> "System.out.println" * f1 -> "(" * f2 -> Expression() * f3 -> ")" * f4 -> ";" */ public String visit(PrintStatement n) throws Exception { // We need to check if type of the expression f2 is different from (int, boolean). // if it is => Throw Semantic Error! String expType = n.f2.accept(this); if(!expType.equals("int") && !expType.equals("boolean")) throw new SemanticError(); return null; } /** Expression * f0 -> AndExpression() * | CompareExpression() * | PlusExpression() * | MinusExpression() * | TimesExpression() * | ArrayLookup() * | ArrayLength() * | MessageSend() * | Clause() */ // Go through the parse Tree public String visit(Expression n) throws Exception { return n.f0.accept(this); } /** AndExpression * f0 -> Clause() * f1 -> "&&" * f2 -> Clause() */ public String visit(AndExpression n) throws Exception { // Clause should be type boolean if(!n.f0.accept(this).equals("boolean") || !n.f2.accept(this).equals("boolean")) throw new SemanticError(); return "boolean"; } /** CompareExpression * f0 -> PrimaryExpression() * f1 -> "<" * f2 -> PrimaryExpression() */ public String visit(CompareExpression n) throws Exception { // Exp should be type int if(!n.f0.accept(this).equals("int") || !n.f2.accept(this).equals("int")) throw new SemanticError(); return "boolean"; } /** PlusExpression * f0 -> PrimaryExpression() * f1 -> "+" * f2 -> PrimaryExpression() f0 + f2 */ public String visit(PlusExpression n) throws Exception { // Exp should be type int if(!n.f0.accept(this).equals("int") || !n.f2.accept(this).equals("int")) throw new SemanticError(); return "int"; } /** * f0 -> PrimaryExpression() * f1 -> "-" * f2 -> PrimaryExpression() f0 - f2 */ public String visit(MinusExpression n) throws Exception { // Exp should be type int if(!n.f0.accept(this).equals("int") || !n.f2.accept(this).equals("int")) throw new SemanticError(); return "int"; } /** * f0 -> PrimaryExpression() * f1 -> "*" * f2 -> PrimaryExpression() f0 * f2 */ public String visit(TimesExpression n) throws Exception { // Exp should be type int if(!n.f0.accept(this).equals("int") || !n.f2.accept(this).equals("int")) throw new SemanticError(); return "int"; } /** ArrayLookup * f0 -> PrimaryExpression() * f1 -> "[" * f2 -> PrimaryExpression() * f3 -> "]" f0[f2] */ public String visit(ArrayLookup n) throws Exception { // Check if the var has been declared. String type = n.f0.accept(this); // Check if the type of var is arrayType. if(!type.equals("int[]") && !type.equals("boolean[]")) throw new SemanticError(); // The exp2 must be an integer. String exp2 = n.f2.accept(this); if(!exp2.equals("int")) throw new SemanticError(); return "int"; } /** ArrayLength * f0 -> PrimaryExpression() * f1 -> "." * f2 -> "length" f0.length */ public String visit(ArrayLength n) throws Exception { String type = n.f0.accept(this); // Check if the type of var is arrayType. if(!type.equals("int[]") && !type.equals("boolean[]")) throw new SemanticError(); return "int"; } /** MessageSend * f0 -> PrimaryExpression() * f1 -> "." * f2 -> Identifier() * f3 -> "(" * f4 -> ( ExpressionList() )? * f5 -> ")" f0.f2(f4) */ public String visit(MessageSend n) throws Exception { // Check if the type of the exp has been declared. String type = n.f0.accept(this); CheckForDeclaration(type, className, 2); // Check if the method f2 has been declared. String method = n.f2.accept(this); Boolean flag = false; // Flag to help us to figure out what data to produce if(CheckForClassDeclaration(type)){ // Check if the primary expression f0 is another class if(CheckForMethodDeclaration(method, type)) // If it is check inside this class for the method too flag = true; else{ CheckForDeclaration(method, className, 1); // And then if the method does not be found there check into the current class for it. } } else CheckForDeclaration(method, className,1); // If the primary expression f0 it's not another class, check only inside the current class // Check if the argument types are correct. // Use flag to produce the correct data. // If the method found inside type(f0 class) make data dor that class // else make data for the current class we are into. Data data = new Data(null); if(flag) data = symbol_table.get(type); else data = symbol_table.get(className); LinkedHashMap<String, String> args = new LinkedHashMap<String, String>(); args = data.getMethods().get(method).getArgs(); // Check if args number is the same if(n.f4.present() == false && args.size() != 0) throw new SemanticError(); if(n.f4.present()){ List<String> exp_list = new ArrayList<String>(); exp_list = Arrays.asList(n.f4.accept(this).split(",")); if(exp_list.size() != args.size()) throw new SemanticError(); // If arguments have different type. int i = 0; for(String type1: args.values()){ if(!type1.equals(exp_list.get(i)) && !isSubType(exp_list.get(i), type1)) throw new SemanticError(); i++; } } String ret_type = data.getMethods().get(method).getType(); return ret_type; } /** ExpressionList * f0 -> Expression() * f1 -> ExpressionTail() */ // It will return a string like: int,boolean,Tree public String visit(ExpressionList n) throws Exception { String expression = n.f0.accept(this); String expression_tail = n.f1.accept(this); return expression + expression_tail; } /** ExpressionTail * f0 -> ( ExpressionTerm() )* */ public String visit(ExpressionTail n) throws Exception { String expression_tail = ""; for( int i = 0; i < n.f0.size(); i++ ) expression_tail += n.f0.elementAt(i).accept(this); return expression_tail; } /** ExpressionTerm * f0 -> "," * f1 -> Expression() */ public String visit(ExpressionTerm n) throws Exception { String expression = n.f1.accept(this); return "," + expression; } /** Clause n * f0 -> NotExpression() * | PrimaryExpression() */ public String visit(Clause n) throws Exception { return n.f0.accept(this); } /** PrimaryExpression * f0 -> IntegerLiteral() * | TrueLiteral() * | FalseLiteral() * | Identifier() * | ThisExpression() * | ArrayAllocationExpression() * | AllocationExpression() * | BracketExpression() */ public String visit(PrimaryExpression n) throws Exception { // Check if the PrimaryExpression is an identifier. String exp = n.f0.accept(this); if(n.f0.which == 3){ CheckForDeclaration(exp, className, 0); // Check for declaration // If it has been declared => find and return its type. return getVarType(exp, className); } return exp; } /** IntegerLiteral * f0 -> <INTEGER_LITERAL> */ public String visit(IntegerLiteral n) throws Exception { return "int"; } /** TrueLiteral * f0 -> "true" */ public String visit(TrueLiteral n) throws Exception { return "boolean"; } /** FalseLiteral * f0 -> "false" */ public String visit(FalseLiteral n) throws Exception { return "boolean"; } /** * f0 -> <IDENTIFIER> */ public String visit(Identifier n) throws Exception { return n.f0.toString(); } /** ThisExpression * f0 -> "this" */ // Return the name of the class we are into public String visit(ThisExpression n) throws Exception { return className; } /** ArrayAllocationExpression * f0 -> BooleanArrayAllocationExpression() * | IntegerArrayAllocationExpression() */ public String visit(ArrayAllocationExpression n) throws Exception { return n.f0.accept(this); } /** BooleanArrayAllocationExpression * f0 -> "new" * f1 -> "boolean" * f2 -> "[" * f3 -> Expression() * f4 -> "]" new boolean[f3] */ public String visit(BooleanArrayAllocationExpression n) throws Exception { // Check if the type of expression f3 is integer. // If not => Throw Semantic Error! if(!n.f3.accept(this).equals("int")) throw new SemanticError(); return "boolean[]"; } /** IntegerArrayAllocationExpressions * f0 -> "new" * f1 -> "int" * f2 -> "[" * f3 -> Expression() * f4 -> "]" new int[f3] */ public String visit(IntegerArrayAllocationExpression n) throws Exception { // Check if the type of expression f3 is integer. // If not => Throw Semantic Error! if(!n.f3.accept(this).equals("int")) throw new SemanticError(); return "int[]"; } /** AllocationExpression * f0 -> "new" * f1 -> Identifier() * f2 -> "(" * f3 -> ")" new f1() */ public String visit(AllocationExpression n) throws Exception { // Check if the identifier f1 has been declared as a class String id = n.f1.accept(this); if(!symbol_table.containsKey(id)) throw new SemanticError(); return id; } /** * f0 -> "!" * f1 -> Clause() !f1 */ public String visit(NotExpression n) throws Exception { if(!n.f1.accept(this).equals("boolean")) throw new SemanticError(); return "boolean"; } /** * f0 -> "(" * f1 -> Expression() * f2 -> ")" (f1) */ public String visit(BracketExpression n) throws Exception { return n.f1.accept(this); } }
di-feb/MiniJava_Compiler
MiniJava_Compiler/source/TypeChecker.java
6,687
// μπορει να ειναι και υποτυπος.
line_comment
el
import java.util.Map; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Arrays; import java.util.ArrayList; import visitor.GJNoArguDepthFirst; import syntaxtree.*; public class TypeChecker extends GJNoArguDepthFirst< String >{ private String className; // The className of the class we are into private String methodName; // The methodName of the class we are into private Map <String, Data> symbol_table; // The symbol table we construct later with the DeclCollector // Constructor TypeChecker(Map <String, Data> symbol_table){ this.symbol_table = symbol_table; this.className = null; this.methodName = null; } // Check if the given type is primitive private boolean isPrimitive(String type){ if(type != "int[]" && type != "boolean[]" && type != "boolean" && type != "int") return false; return true; } // Check if the child type is SubType of another type private boolean isSubType(String childType, String parentType){ // If the childType is primitive then it must be identicall with parentType if(isPrimitive(childType) || isPrimitive(parentType)) return childType.equals(parentType); while(childType != null){ if(childType.equals(parentType)) return true; childType = symbol_table.get(childType).getName(); } return false; } // Check if a variable, method, or class has been declared // Throw SemanticError if not! private void CheckForDeclaration(String value, String classname, int mode) throws Exception { Boolean varFlag = false; Boolean methodFlag = false; Boolean classFlag = false; if(mode == 0){ varFlag = CheckForVarDeclaration(value, classname); if(!varFlag) throw new SemanticError(); } else if(mode == 1){ methodFlag = CheckForMethodDeclaration(value, classname); if(!methodFlag) throw new SemanticError(); } else if(mode == 2){ classFlag = CheckForClassDeclaration(value); if(!classFlag) throw new SemanticError(); } else if (mode == 3){ classFlag = CheckForVarDeclaration(value, classname); methodFlag = CheckForMethodDeclaration(value, classname); if(!varFlag && !methodFlag) throw new SemanticError(); } else{ varFlag = CheckForVarDeclaration(value, classname); methodFlag = CheckForMethodDeclaration(value, classname); classFlag = CheckForClassDeclaration(value); if(!varFlag && !methodFlag && !classFlag) throw new SemanticError(); } } // Returns true if a var has been declared // false if not. // We have already push any inherited method or field to the child // so we dont need to check for redaclaration recursivly private boolean CheckForVarDeclaration(String var, String classname){ Data data = symbol_table.get(classname); if(data == null) return false; // Check for decleration . if(data.getVars().containsKey(var)) return true; if(methodName != null && data.getMethods().get(methodName) != null){ if(data.getMethods().get(methodName).getArgs().containsKey(var)) return true; if(data.getMethods().get(methodName).getVars().containsKey(var)) return true; } return false; } private boolean CheckForMethodDeclaration(String method, String classname){ if (symbol_table.get(classname).getMethods().containsKey(method)) return true; return false; } private boolean CheckForClassDeclaration(String class_){ return symbol_table.containsKey(class_); } // Get the type of the variable. // Precedence: method variables, method args > classe's fields private String getVarType(String var, String classname){ Data data = symbol_table.get(classname); String parentClassName = symbol_table.get(classname).getName(); if(methodName != null && data.getMethods().get(methodName) != null){ if (data.getMethods().get(methodName).getVars().containsKey(var)) return data.getMethods().get(methodName).getVars().get(var); if(data.getMethods().get(methodName).getArgs().containsKey(var)) return data.getMethods().get(methodName).getArgs().get(var); } if(data.getVars().containsKey(var)) return data.getVars().get(var).getType(); return null; } /** Goal * f0 -> MainClass() * f1 -> ( TypeDeclaration() )* */ public String visit(Goal n) throws Exception { // Accept at main class n.f0.accept(this); // When a production has a * it means that this production can appear // zero or more times. So for the ( TypeDeclaration() )* f.e. we need to // iterate all the classes declarations. for( int i = 0; i < n.f1.size(); i++ ) n.f1.elementAt(i).accept(this); return null; } /** MainClass * f1 -> Identifier() { void main ( String[] * f11 -> Identifier() * f14 -> ( VarDeclaration() )* * f15 -> ( Statement() )* * class f1 { void main ( String[] f11 ){ f14 f15 } } */ public String visit(MainClass n) throws Exception { // Keep the name of the "main" class className = n.f1.accept(this); // Go down through the parse Tree for checking for( int i = 0; i < n.f14.size(); i++ ) n.f14.elementAt(i).accept(this); for( int i = 0; i < n.f15.size(); i++ ) n.f15.elementAt(i).accept(this); return null; } /** TypeDeclaration * f0 -> ClassDeclaration() * | ClassExtendsDeclaration() */ public String visit(TypeDeclaration n) throws Exception { n.f0.accept(this); return null; } /** ClassDeclaration * f1 -> Identifier() * f3 -> ( VarDeclaration() )* * f4 -> ( MethodDeclaration() )* class f1 { f3 f4 } */ public String visit(ClassDeclaration n) throws Exception { // Keep the name of the "main" class className = n.f1.accept(this); // Go down through the parse Tree for checking for( int i = 0; i < n.f3.size(); i++ ) n.f3.elementAt(i).accept(this); for( int i = 0; i < n.f4.size(); i++ ) n.f4.elementAt(i).accept(this); return null; } /** ClassExtendsDeclaration * f1 -> Identifier() * f3 -> Identifier() * f5 -> ( VarDeclaration() )* * f6 -> ( MethodDeclaration() )* class f1 extends f3{ f5 f6 } */ public String visit(ClassExtendsDeclaration n) throws Exception { // Keep the name of the class className = n.f1.accept(this); // Check if the name of the parent class not existed inside the symbol table. // If it does not that means we have declare a class whose parent class has not been declared yet. // We do not want that => Throw Semantic Error! String parent_name = n.f3.accept(this); if(!symbol_table.containsKey(parent_name)) throw new SemanticError(); // Go down through the parse Tree for checking for( int i = 0; i < n.f5.size(); i++ ) n.f5.elementAt(i).accept(this); for( int i = 0; i < n.f6.size(); i++ ) n.f6.elementAt(i).accept(this); return null; } /** VarDeclaration * f0 -> Type() * f1 -> Identifier() * f2 -> ";" */ public String visit(VarDeclaration n) throws Exception { // Keep the type off the var and go down into the parse tree. String var_type = n.f0.accept(this); n.f1.accept(this); // The type of the variable(class) has not been declared. if(!isPrimitive(var_type) && !symbol_table.containsKey(var_type)) throw new SemanticError(); return null; } /** MethodDeclaration * f1 -> Type() * f2 -> Identifier() * f4 -> ( FormalParameterList() )? * f7 -> ( VarDeclaration() )* * f8 -> ( Statement() )* * f10 -> Expression() * public f1 f2( f4 ){ f7 f8 return f10; } */ public String visit(MethodDeclaration n) throws Exception { // Get methods return type. String method_RetType = n.f1.accept(this); // Get methods name and update methodName just to // know at what method we are into. String method_name = n.f2.accept(this); methodName = method_name; // We need to check if type is different from (int, boolean, int[], boolean[]) or the other non-primitive types. // if it is => Throw Semantic Error! if(!isPrimitive(method_RetType) && !symbol_table.containsKey(method_RetType)) throw new SemanticError(); if(n.f4.present()) n.f4.accept(this); // Accept to go through the parse tree for( int i = 0; i < n.f7.size(); i++ ) n.f7.elementAt(i).accept(this); for( int i = 0; i < n.f8.size(); i++ ) n.f8.elementAt(i).accept(this); // The return type of the return statement need to match with // the return type of this method or a sub type of it. // If it does not => Throw Semantic Error! String value_RetType = n.f10.accept(this); if(!(value_RetType).equals(method_RetType) && !isSubType(value_RetType, method_RetType)) // μπορει να<SUF> throw new SemanticError(); methodName = null; return null; } /** FormalParameterList * f0 -> FormalParameter() * f1 -> FormalParameterTail() */ // Go through the parse Tree we have already collect the data public String visit(FormalParameterList n) throws Exception { n.f0.accept(this); n.f1.accept(this); return null; } /** FormalParameter * f0 -> Type() * f1 -> Identifier() */ public String visit(FormalParameter n) throws Exception { String type = n.f0.accept(this); String name = n.f1.accept(this); // We need to check if type is different from (int, boolean, int[], boolean[]) or the other non-primitive types. // if it is => Throw Semantic Error! if(!isPrimitive(type) && !symbol_table.containsKey(type)) throw new SemanticError(); return null; } /** FormalParameterTail * f0 -> ( FormalParameterTerm() )* */ public String visit(FormalParameterTail n) throws Exception { for( int i = 0; i < n.f0.size(); i++ ) n.f0.elementAt(i).accept(this); return null; } /** FormalParameterTerm * f0 -> "," * f1 -> FormalParameter() */ public String visit(FormalParameterTerm n) throws Exception { n.f1.accept(this); return null; } /** Type * f0 -> ArrayType() * | BooleanType() * | IntegerType() * | Identifier() */ public String visit(Type n) throws Exception { return n.f0.accept(this); } /** ArrayType * f0 -> BooleanArrayType() * | IntegerArrayType() */ public String visit(ArrayType n) throws Exception { return n.f0.accept(this); } /** BooleanArrayType * f0 -> "boolean" * f1 -> "[" * f2 -> "]" */ public String visit(BooleanArrayType n) throws Exception { return "boolean[]"; } /** IntegerArrayType * f0 -> "int" * f1 -> "[" * f2 -> "]" */ public String visit(IntegerArrayType n) throws Exception { return "int[]"; } /** BooleanType * f0 -> "boolean" */ public String visit(BooleanType n) throws Exception { return "boolean"; } /** IntegerType * f0 -> "int" */ public String visit(IntegerType n) throws Exception { return "int"; } /** Statement * f0 -> Block() * | AssignmentStatement() * | ArrayAssignmentStatement() * | IfStatement() * | WhileStatement() * | PrintStatement() */ // Go through the parse Tree public String visit(Statement n) throws Exception { n.f0.accept(this); return null; } /** Block * f0 -> "{" * f1 -> ( Statement() )* * f2 -> "}" { f1 } */ // Go through the parse Tree public String visit(Block n) throws Exception { for( int i = 0; i < n.f1.size(); i++ ) n.f1.elementAt(i).accept(this); return null; } /** AssignmentStatement * f0 -> Identifier() * f1 -> "=" * f2 -> Expression() * f3 -> ";" f0 = f2; */ public String visit(AssignmentStatement n) throws Exception { // Check if the var(f0) has been declared. // If not => Throw Semantic Error! String var = n.f0.accept(this); CheckForDeclaration(var, className, 0); String idType = getVarType(var, className); // Check if the type of the expression match the type of the identifier // or a sub type of it. // If not => Throw Semantic Error! String exp_type = n.f2.accept(this); if(!exp_type.equals(idType) && !isSubType(exp_type, idType)) throw new SemanticError(); return null; } /** ArrayAssignmentStatement * f0 -> Identifier() * f1 -> "[" * f2 -> Expression() * f3 -> "]" * f4 -> "=" * f5 -> Expression() * f6 -> ";" f0[f2]=f5; */ public String visit(ArrayAssignmentStatement n) throws Exception { // Check for delcaration String id = n.f0.accept(this); CheckForDeclaration(id, className, 4); // The type of the f0 must be an array type String idType = getVarType(id, className); if(idType == null || (!idType.equals("int[]") && !idType.equals("boolean[]"))) throw new SemanticError(); // Check if the type of the expression f2 is interger. // If not => Throw Semantic Error! if(!n.f2.accept(this).equals("int")) throw new SemanticError(); // Check if the type of the expression is either int or boolean // cause only these two types of arrays we could have. // If not => Throw Semantic Error! String expType = n.f5.accept(this); if(!expType.equals("int") && !expType.equals("boolean")) throw new SemanticError(); return null; } /** IfStatement * f0 -> "if" * f1 -> "(" * f2 -> Expression() * f3 -> ")" * f4 -> Statement() * f5 -> "else" * f6 -> Statement() if (f2){ f4 } else{ f6 } */ public String visit(IfStatement n) throws Exception { // Check if the type of the expression is boolean. // If not => Throw Semantic Error! if(!n.f2.accept(this).equals("boolean")) throw new SemanticError(); n.f4.accept(this); n.f6.accept(this); return null; } /** WhileStatement * f0 -> "while" * f1 -> "(" * f2 -> Expression() * f3 -> ")" * f4 -> Statement() while(f2){ f4 } */ public String visit(WhileStatement n) throws Exception { // Check if the type of the expression is boolean. // If not => Throw Semantic Error! if(!n.f2.accept(this).equals("boolean")) throw new SemanticError(); n.f4.accept(this); return null; } /** PrintStatement * f0 -> "System.out.println" * f1 -> "(" * f2 -> Expression() * f3 -> ")" * f4 -> ";" */ public String visit(PrintStatement n) throws Exception { // We need to check if type of the expression f2 is different from (int, boolean). // if it is => Throw Semantic Error! String expType = n.f2.accept(this); if(!expType.equals("int") && !expType.equals("boolean")) throw new SemanticError(); return null; } /** Expression * f0 -> AndExpression() * | CompareExpression() * | PlusExpression() * | MinusExpression() * | TimesExpression() * | ArrayLookup() * | ArrayLength() * | MessageSend() * | Clause() */ // Go through the parse Tree public String visit(Expression n) throws Exception { return n.f0.accept(this); } /** AndExpression * f0 -> Clause() * f1 -> "&&" * f2 -> Clause() */ public String visit(AndExpression n) throws Exception { // Clause should be type boolean if(!n.f0.accept(this).equals("boolean") || !n.f2.accept(this).equals("boolean")) throw new SemanticError(); return "boolean"; } /** CompareExpression * f0 -> PrimaryExpression() * f1 -> "<" * f2 -> PrimaryExpression() */ public String visit(CompareExpression n) throws Exception { // Exp should be type int if(!n.f0.accept(this).equals("int") || !n.f2.accept(this).equals("int")) throw new SemanticError(); return "boolean"; } /** PlusExpression * f0 -> PrimaryExpression() * f1 -> "+" * f2 -> PrimaryExpression() f0 + f2 */ public String visit(PlusExpression n) throws Exception { // Exp should be type int if(!n.f0.accept(this).equals("int") || !n.f2.accept(this).equals("int")) throw new SemanticError(); return "int"; } /** * f0 -> PrimaryExpression() * f1 -> "-" * f2 -> PrimaryExpression() f0 - f2 */ public String visit(MinusExpression n) throws Exception { // Exp should be type int if(!n.f0.accept(this).equals("int") || !n.f2.accept(this).equals("int")) throw new SemanticError(); return "int"; } /** * f0 -> PrimaryExpression() * f1 -> "*" * f2 -> PrimaryExpression() f0 * f2 */ public String visit(TimesExpression n) throws Exception { // Exp should be type int if(!n.f0.accept(this).equals("int") || !n.f2.accept(this).equals("int")) throw new SemanticError(); return "int"; } /** ArrayLookup * f0 -> PrimaryExpression() * f1 -> "[" * f2 -> PrimaryExpression() * f3 -> "]" f0[f2] */ public String visit(ArrayLookup n) throws Exception { // Check if the var has been declared. String type = n.f0.accept(this); // Check if the type of var is arrayType. if(!type.equals("int[]") && !type.equals("boolean[]")) throw new SemanticError(); // The exp2 must be an integer. String exp2 = n.f2.accept(this); if(!exp2.equals("int")) throw new SemanticError(); return "int"; } /** ArrayLength * f0 -> PrimaryExpression() * f1 -> "." * f2 -> "length" f0.length */ public String visit(ArrayLength n) throws Exception { String type = n.f0.accept(this); // Check if the type of var is arrayType. if(!type.equals("int[]") && !type.equals("boolean[]")) throw new SemanticError(); return "int"; } /** MessageSend * f0 -> PrimaryExpression() * f1 -> "." * f2 -> Identifier() * f3 -> "(" * f4 -> ( ExpressionList() )? * f5 -> ")" f0.f2(f4) */ public String visit(MessageSend n) throws Exception { // Check if the type of the exp has been declared. String type = n.f0.accept(this); CheckForDeclaration(type, className, 2); // Check if the method f2 has been declared. String method = n.f2.accept(this); Boolean flag = false; // Flag to help us to figure out what data to produce if(CheckForClassDeclaration(type)){ // Check if the primary expression f0 is another class if(CheckForMethodDeclaration(method, type)) // If it is check inside this class for the method too flag = true; else{ CheckForDeclaration(method, className, 1); // And then if the method does not be found there check into the current class for it. } } else CheckForDeclaration(method, className,1); // If the primary expression f0 it's not another class, check only inside the current class // Check if the argument types are correct. // Use flag to produce the correct data. // If the method found inside type(f0 class) make data dor that class // else make data for the current class we are into. Data data = new Data(null); if(flag) data = symbol_table.get(type); else data = symbol_table.get(className); LinkedHashMap<String, String> args = new LinkedHashMap<String, String>(); args = data.getMethods().get(method).getArgs(); // Check if args number is the same if(n.f4.present() == false && args.size() != 0) throw new SemanticError(); if(n.f4.present()){ List<String> exp_list = new ArrayList<String>(); exp_list = Arrays.asList(n.f4.accept(this).split(",")); if(exp_list.size() != args.size()) throw new SemanticError(); // If arguments have different type. int i = 0; for(String type1: args.values()){ if(!type1.equals(exp_list.get(i)) && !isSubType(exp_list.get(i), type1)) throw new SemanticError(); i++; } } String ret_type = data.getMethods().get(method).getType(); return ret_type; } /** ExpressionList * f0 -> Expression() * f1 -> ExpressionTail() */ // It will return a string like: int,boolean,Tree public String visit(ExpressionList n) throws Exception { String expression = n.f0.accept(this); String expression_tail = n.f1.accept(this); return expression + expression_tail; } /** ExpressionTail * f0 -> ( ExpressionTerm() )* */ public String visit(ExpressionTail n) throws Exception { String expression_tail = ""; for( int i = 0; i < n.f0.size(); i++ ) expression_tail += n.f0.elementAt(i).accept(this); return expression_tail; } /** ExpressionTerm * f0 -> "," * f1 -> Expression() */ public String visit(ExpressionTerm n) throws Exception { String expression = n.f1.accept(this); return "," + expression; } /** Clause n * f0 -> NotExpression() * | PrimaryExpression() */ public String visit(Clause n) throws Exception { return n.f0.accept(this); } /** PrimaryExpression * f0 -> IntegerLiteral() * | TrueLiteral() * | FalseLiteral() * | Identifier() * | ThisExpression() * | ArrayAllocationExpression() * | AllocationExpression() * | BracketExpression() */ public String visit(PrimaryExpression n) throws Exception { // Check if the PrimaryExpression is an identifier. String exp = n.f0.accept(this); if(n.f0.which == 3){ CheckForDeclaration(exp, className, 0); // Check for declaration // If it has been declared => find and return its type. return getVarType(exp, className); } return exp; } /** IntegerLiteral * f0 -> <INTEGER_LITERAL> */ public String visit(IntegerLiteral n) throws Exception { return "int"; } /** TrueLiteral * f0 -> "true" */ public String visit(TrueLiteral n) throws Exception { return "boolean"; } /** FalseLiteral * f0 -> "false" */ public String visit(FalseLiteral n) throws Exception { return "boolean"; } /** * f0 -> <IDENTIFIER> */ public String visit(Identifier n) throws Exception { return n.f0.toString(); } /** ThisExpression * f0 -> "this" */ // Return the name of the class we are into public String visit(ThisExpression n) throws Exception { return className; } /** ArrayAllocationExpression * f0 -> BooleanArrayAllocationExpression() * | IntegerArrayAllocationExpression() */ public String visit(ArrayAllocationExpression n) throws Exception { return n.f0.accept(this); } /** BooleanArrayAllocationExpression * f0 -> "new" * f1 -> "boolean" * f2 -> "[" * f3 -> Expression() * f4 -> "]" new boolean[f3] */ public String visit(BooleanArrayAllocationExpression n) throws Exception { // Check if the type of expression f3 is integer. // If not => Throw Semantic Error! if(!n.f3.accept(this).equals("int")) throw new SemanticError(); return "boolean[]"; } /** IntegerArrayAllocationExpressions * f0 -> "new" * f1 -> "int" * f2 -> "[" * f3 -> Expression() * f4 -> "]" new int[f3] */ public String visit(IntegerArrayAllocationExpression n) throws Exception { // Check if the type of expression f3 is integer. // If not => Throw Semantic Error! if(!n.f3.accept(this).equals("int")) throw new SemanticError(); return "int[]"; } /** AllocationExpression * f0 -> "new" * f1 -> Identifier() * f2 -> "(" * f3 -> ")" new f1() */ public String visit(AllocationExpression n) throws Exception { // Check if the identifier f1 has been declared as a class String id = n.f1.accept(this); if(!symbol_table.containsKey(id)) throw new SemanticError(); return id; } /** * f0 -> "!" * f1 -> Clause() !f1 */ public String visit(NotExpression n) throws Exception { if(!n.f1.accept(this).equals("boolean")) throw new SemanticError(); return "boolean"; } /** * f0 -> "(" * f1 -> Expression() * f2 -> ")" (f1) */ public String visit(BracketExpression n) throws Exception { return n.f1.accept(this); } }
3587_0
package com.mgiandia.library.util; import java.util.Calendar; /** * Αμετάβλητη κλάση για τη διαχείριση ημερομηνιών * αγνοώντας την ώρα. * @author Νίκος Διαμαντίδης * */ public class SimpleCalendar implements Comparable<SimpleCalendar> { private static final long MILLIS_PER_DAY = 86400000; private Calendar date; /** * Κατασκευάζει μία ημερομηνία με βάση το έτος, * το μήνα και την ημέρα του μήνα. * @param year Το έτος * @param month Ο μήνας από 1 έως 12 * @param day Η ημέρα του μήνα */ public SimpleCalendar(int year, int month, int day) { date = Calendar.getInstance(); date.set(year, month - 1, day); trimToDays(this.date); } /** * Κατασκευάζει μία ημερομηνία λαμβάνοντας. * ως παράμετρο αντικείμενο της κλάσης {@code Calendar} * @param date Η ημερομηνία */ public SimpleCalendar(Calendar date) { this.date = Calendar.getInstance(); this.date.setTimeInMillis(date.getTimeInMillis()); trimToDays(this.date); } private void trimToDays(Calendar javaDate) { javaDate.set(Calendar.HOUR_OF_DAY, 0); javaDate.set(Calendar.MINUTE, 0); javaDate.set(Calendar.SECOND, 0); javaDate.set(Calendar.MILLISECOND, 0); } /** * Η διάρκεια σε ημέρες σε σχέση με μία άλλη ημερομηνία. * @param other Η δεύτερη ημερομηνία για την οποία * υπολογίζεται η διάρκεια * @return Ο αριθμός των ημερών. Θετικός αριθμός ημερών * σημαίνει ότι η άλλη ημερομηνία είναι μεταγενέστερη, * ενώ αρνητικός το αντίθετο. */ public long durationInDays(SimpleCalendar other) { long timeDiff = other.date.getTimeInMillis() - date.getTimeInMillis(); return timeDiff / MILLIS_PER_DAY; } /** * Επιστρέφει το έτος της ημερομηνίας. * @return Το έτος */ public int getYear() { return date.get(Calendar.YEAR); } /** * Επιστρέφει το μήνα της ημερομηνίας (1-12). * @return Ο μήνας */ public int getMonth() { return date.get(Calendar.MONTH) + 1; } /** * Επιστρέφει την ημέρα σε του μήνα. * @return Η ημέρα του μήνα */ public int getDayOfMonth() { return date.get(Calendar.DAY_OF_MONTH); } /** * Επιστρέφει την ημέρα της εβδομάδας της ημερομηνίας. * @return Η ημέρα της εβδομάδας */ public int getDayOfWeek() { return date.get(Calendar.DAY_OF_WEEK); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * μεταγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * μεταγενέστερη της άλλης */ public boolean after(SimpleCalendar other) { if (equals(other)) { return false; } return date.after(other.date); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * προγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * προγενέστερη της άλλης */ public boolean before(SimpleCalendar other) { if (equals(other)) { return false; } return date.before(other.date); } /** * Επιστρέφει μία ημερομηνία προσθέτοντας κάποιο * αριθμό ημερών. * @param days Ο αριθμός των ημερών που προστίθενται * @return Η νέα ημερομηνία */ public SimpleCalendar addDays(int days) { Calendar newDate = Calendar.getInstance(); newDate.setTimeInMillis(date.getTimeInMillis()); newDate.add(Calendar.DAY_OF_MONTH, days); return new SimpleCalendar(newDate); } /** * Επιστρέφει μία ημερομηνία τύπου {@code Calendar}. * @return Η ημερομηνία */ public Calendar getJavaCalendar() { Calendar javaCalendar = Calendar.getInstance(); javaCalendar.setTimeInMillis(date.getTimeInMillis()); trimToDays(javaCalendar); return javaCalendar; } /** * {@inheritDoc} */ public int compareTo(SimpleCalendar other) { return date.compareTo(other.date); } @Override public boolean equals(Object other) { if (other == null) { return false; } if (this == other) { return true; } if (!(other instanceof SimpleCalendar)) { return false; } SimpleCalendar theDate = (SimpleCalendar) other; if (date == null) { return theDate.date == null; } if (getYear() != theDate.getYear()) { return false; } if (getMonth() != theDate.getMonth()) { return false; } if (getDayOfMonth() != theDate.getDayOfMonth()) { return false; } return true; } @Override public int hashCode() { return date == null ? 0 : date.hashCode(); } }
diamantidakos/Library
src/main/java/com/mgiandia/library/util/SimpleCalendar.java
2,047
/** * Αμετάβλητη κλάση για τη διαχείριση ημερομηνιών * αγνοώντας την ώρα. * @author Νίκος Διαμαντίδης * */
block_comment
el
package com.mgiandia.library.util; import java.util.Calendar; /** * Αμετάβλητη κλάση για<SUF>*/ public class SimpleCalendar implements Comparable<SimpleCalendar> { private static final long MILLIS_PER_DAY = 86400000; private Calendar date; /** * Κατασκευάζει μία ημερομηνία με βάση το έτος, * το μήνα και την ημέρα του μήνα. * @param year Το έτος * @param month Ο μήνας από 1 έως 12 * @param day Η ημέρα του μήνα */ public SimpleCalendar(int year, int month, int day) { date = Calendar.getInstance(); date.set(year, month - 1, day); trimToDays(this.date); } /** * Κατασκευάζει μία ημερομηνία λαμβάνοντας. * ως παράμετρο αντικείμενο της κλάσης {@code Calendar} * @param date Η ημερομηνία */ public SimpleCalendar(Calendar date) { this.date = Calendar.getInstance(); this.date.setTimeInMillis(date.getTimeInMillis()); trimToDays(this.date); } private void trimToDays(Calendar javaDate) { javaDate.set(Calendar.HOUR_OF_DAY, 0); javaDate.set(Calendar.MINUTE, 0); javaDate.set(Calendar.SECOND, 0); javaDate.set(Calendar.MILLISECOND, 0); } /** * Η διάρκεια σε ημέρες σε σχέση με μία άλλη ημερομηνία. * @param other Η δεύτερη ημερομηνία για την οποία * υπολογίζεται η διάρκεια * @return Ο αριθμός των ημερών. Θετικός αριθμός ημερών * σημαίνει ότι η άλλη ημερομηνία είναι μεταγενέστερη, * ενώ αρνητικός το αντίθετο. */ public long durationInDays(SimpleCalendar other) { long timeDiff = other.date.getTimeInMillis() - date.getTimeInMillis(); return timeDiff / MILLIS_PER_DAY; } /** * Επιστρέφει το έτος της ημερομηνίας. * @return Το έτος */ public int getYear() { return date.get(Calendar.YEAR); } /** * Επιστρέφει το μήνα της ημερομηνίας (1-12). * @return Ο μήνας */ public int getMonth() { return date.get(Calendar.MONTH) + 1; } /** * Επιστρέφει την ημέρα σε του μήνα. * @return Η ημέρα του μήνα */ public int getDayOfMonth() { return date.get(Calendar.DAY_OF_MONTH); } /** * Επιστρέφει την ημέρα της εβδομάδας της ημερομηνίας. * @return Η ημέρα της εβδομάδας */ public int getDayOfWeek() { return date.get(Calendar.DAY_OF_WEEK); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * μεταγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * μεταγενέστερη της άλλης */ public boolean after(SimpleCalendar other) { if (equals(other)) { return false; } return date.after(other.date); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * προγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * προγενέστερη της άλλης */ public boolean before(SimpleCalendar other) { if (equals(other)) { return false; } return date.before(other.date); } /** * Επιστρέφει μία ημερομηνία προσθέτοντας κάποιο * αριθμό ημερών. * @param days Ο αριθμός των ημερών που προστίθενται * @return Η νέα ημερομηνία */ public SimpleCalendar addDays(int days) { Calendar newDate = Calendar.getInstance(); newDate.setTimeInMillis(date.getTimeInMillis()); newDate.add(Calendar.DAY_OF_MONTH, days); return new SimpleCalendar(newDate); } /** * Επιστρέφει μία ημερομηνία τύπου {@code Calendar}. * @return Η ημερομηνία */ public Calendar getJavaCalendar() { Calendar javaCalendar = Calendar.getInstance(); javaCalendar.setTimeInMillis(date.getTimeInMillis()); trimToDays(javaCalendar); return javaCalendar; } /** * {@inheritDoc} */ public int compareTo(SimpleCalendar other) { return date.compareTo(other.date); } @Override public boolean equals(Object other) { if (other == null) { return false; } if (this == other) { return true; } if (!(other instanceof SimpleCalendar)) { return false; } SimpleCalendar theDate = (SimpleCalendar) other; if (date == null) { return theDate.date == null; } if (getYear() != theDate.getYear()) { return false; } if (getMonth() != theDate.getMonth()) { return false; } if (getDayOfMonth() != theDate.getDayOfMonth()) { return false; } return true; } @Override public int hashCode() { return date == null ? 0 : date.hashCode(); } }
3874_8
package com.mgiandia.se2ed.ch11.p07composition.var1; /** * Η ταχυδρομική διεύθυνση. * @author Νίκος Διαμαντίδης * */ public class Address { private String street; private String number; private String city; private ZipCode zip; private String country = "Ελλάδα"; /** * Προκαθορισμένος κατασκευαστής. */ public Address() { } /** * Βοηθητικός κατασκευαστής που αντιγράφει την κατάσταση. * κάποιας άλλης διεύθυνσης * @param address Η άλλη διεύθυνση */ public Address(Address address) { this.street = address.getStreet(); this.number = address.getNumber(); this.city = address.getCity(); this.zip = address.getZipCode(); this.country = address.getCountry(); } /** * Θέτει την οδό. * @param street Η οδός */ public void setStreet(String street) { this.street = street; } /** * Επιστρέφει την οδό. * @return Η οδός */ public String getStreet() { return street; } /** * Θέτει τον αριθμό. * @param number Ο αριθμός */ public void setNumber(String number) { this.number = number; } /** * Επιστρέφει τον αριθμό. * @return Ο αριθμός */ public String getNumber() { return number; } /** * Θέτει την πόλη. * @param city Η πόλη */ public void setCity(String city) { this.city = city; } /** * Επιστρέφει την πόλη. * @return Η πόλη */ public String getCity() { return city; } /** * Θέτει τον ταχυδρομικό κώδικα. * @param zipcode Ο ταχυδρομικός κώδικας */ public void setZipCode(ZipCode zipcode) { this.zip = zipcode; } /** * Επιστρέφει τον ταχυδρομικό κώδικα. * @return Ο ταχυδρομικός κώδικας */ public ZipCode getZipCode() { return zip; } /** * Θέτει τη χώρα. * @param country Η χώρα */ public void setCountry(String country) { this.country = country; } /** * Επιστρέφει τη χώρα. * @return Η χώρα */ public String getCountry() { return country; } /** * Η ισότητα βασίζεται σε όλα τα πεδία της διεύθυνσης. * @param other Το άλλο αντικείμενο προς έλεγχο * @return {@code true} αν τα αντικείμενα είναι ίσα */ @Override public boolean equals(Object other) { if (other == null) { return false; } if (this == other) { return true; } if (!(other instanceof Address)) { return false; } Address theAddress = (Address) other; if (!(street == null ? theAddress.street == null : street.equals(theAddress.street))) { return false; } if (!(number == null ? theAddress.number == null : number.equals(theAddress.number))) { return false; } if (!(city == null ? theAddress.city == null : city.equals(theAddress.city))) { return false; } if (!(zip == null ? theAddress.zip == null : zip.equals(theAddress.zip))) { return false; } if (!(country == null ? theAddress.country == null : country.equals(theAddress.country))) { return false; } return true; } @Override public int hashCode() { if (street == null && number == null && city == null && zip == null && country == null) { return 0; } int result = 0; result = street == null ? result : 13 * result + street.hashCode(); result = number == null ? result : 13 * result + number.hashCode(); result = city == null ? result : 13 * result + city.hashCode(); result = zip == null ? result : 13 * result + zip.hashCode(); result = country == null ? result : 13 * result + country.hashCode(); return result; } }
diamantidakos/se2ed
src/main/java/com/mgiandia/se2ed/ch11/p07composition/var1/Address.java
1,399
/** * Επιστρέφει την πόλη. * @return Η πόλη */
block_comment
el
package com.mgiandia.se2ed.ch11.p07composition.var1; /** * Η ταχυδρομική διεύθυνση. * @author Νίκος Διαμαντίδης * */ public class Address { private String street; private String number; private String city; private ZipCode zip; private String country = "Ελλάδα"; /** * Προκαθορισμένος κατασκευαστής. */ public Address() { } /** * Βοηθητικός κατασκευαστής που αντιγράφει την κατάσταση. * κάποιας άλλης διεύθυνσης * @param address Η άλλη διεύθυνση */ public Address(Address address) { this.street = address.getStreet(); this.number = address.getNumber(); this.city = address.getCity(); this.zip = address.getZipCode(); this.country = address.getCountry(); } /** * Θέτει την οδό. * @param street Η οδός */ public void setStreet(String street) { this.street = street; } /** * Επιστρέφει την οδό. * @return Η οδός */ public String getStreet() { return street; } /** * Θέτει τον αριθμό. * @param number Ο αριθμός */ public void setNumber(String number) { this.number = number; } /** * Επιστρέφει τον αριθμό. * @return Ο αριθμός */ public String getNumber() { return number; } /** * Θέτει την πόλη. * @param city Η πόλη */ public void setCity(String city) { this.city = city; } /** * Επιστρέφει την πόλη. <SUF>*/ public String getCity() { return city; } /** * Θέτει τον ταχυδρομικό κώδικα. * @param zipcode Ο ταχυδρομικός κώδικας */ public void setZipCode(ZipCode zipcode) { this.zip = zipcode; } /** * Επιστρέφει τον ταχυδρομικό κώδικα. * @return Ο ταχυδρομικός κώδικας */ public ZipCode getZipCode() { return zip; } /** * Θέτει τη χώρα. * @param country Η χώρα */ public void setCountry(String country) { this.country = country; } /** * Επιστρέφει τη χώρα. * @return Η χώρα */ public String getCountry() { return country; } /** * Η ισότητα βασίζεται σε όλα τα πεδία της διεύθυνσης. * @param other Το άλλο αντικείμενο προς έλεγχο * @return {@code true} αν τα αντικείμενα είναι ίσα */ @Override public boolean equals(Object other) { if (other == null) { return false; } if (this == other) { return true; } if (!(other instanceof Address)) { return false; } Address theAddress = (Address) other; if (!(street == null ? theAddress.street == null : street.equals(theAddress.street))) { return false; } if (!(number == null ? theAddress.number == null : number.equals(theAddress.number))) { return false; } if (!(city == null ? theAddress.city == null : city.equals(theAddress.city))) { return false; } if (!(zip == null ? theAddress.zip == null : zip.equals(theAddress.zip))) { return false; } if (!(country == null ? theAddress.country == null : country.equals(theAddress.country))) { return false; } return true; } @Override public int hashCode() { if (street == null && number == null && city == null && zip == null && country == null) { return 0; } int result = 0; result = street == null ? result : 13 * result + street.hashCode(); result = number == null ? result : 13 * result + number.hashCode(); result = city == null ? result : 13 * result + city.hashCode(); result = zip == null ? result : 13 * result + zip.hashCode(); result = country == null ? result : 13 * result + country.hashCode(); return result; } }
3800_8
package com.kosdiam.epoweredmove.gatewayserver.filter; import java.nio.charset.StandardCharsets; import java.util.Set; import java.util.concurrent.ExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Primary; import org.springframework.core.annotation.Order; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Order(1) @Component public class AuthFilter implements GlobalFilter { final Logger logger = LoggerFactory.getLogger(AuthFilter.class); @Autowired @Lazy private WebClient.Builder builder; // //USER resolves in Eureka server // private final WebClient webClient = // this.loadBalancedWebClientBuilder().build(); private Boolean verified; private String authorization; private Boolean devMode; @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); logger.info("Pre-Filter executed"); String requestPath = exchange.getRequest().getPath().toString(); logger.debug("Request path = " + requestPath); org.springframework.http.HttpHeaders headers = request.getHeaders(); Set<String> headerNames = headers.keySet(); devMode = false; headerNames.forEach((header) -> { logger.info(header + " " + headers.get(header)); if(header.equals("Authorization") || header.equals("authorization")) { authorization = headers.get(header).get(0); } if (header.equals("Devmode")) { devMode = Boolean.parseBoolean(headers.get(header).get(0)); logger.info("Devmode : inside if clause"); } }); if(!devMode) { logger.info("Devmode : false -- " + devMode); //check for specific ips and hostnames ---------------------// String remoteHost = exchange.getRequest().getHeaders().getFirst("Host"); logger.debug("Remote Host : " + remoteHost); // if(!remoteHost.contains("34.30.106.243")) { //!remoteHost.contains("localhost") && // exchange.getResponse().getHeaders().add("Content-Type", "application/json"); // exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // byte[] bytes = "Prohibited : Not Allowed Host".getBytes(StandardCharsets.UTF_8); // DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes); // return exchange.getResponse().writeWith(Flux.just(buffer)); // } } //check for specific allowed calls ---------------------// String apiCalled = exchange.getRequest().getPath().toString(); logger.debug("API Called : " + apiCalled); if(apiCalled.contains("/epoweredmove/user/createUser") || apiCalled.contains("/epoweredmove/user/verifyToken") || apiCalled.contains("/epoweredmove/poi/all") || apiCalled.contains("/epoweredmove/poi/allWithPlugAvailability") || apiCalled.contains("/epoweredmove/plug/allByChargingStation") || apiCalled.contains("/epoweredmove/plug?") || apiCalled.contains("/hello")) { logger.info("Allowed API : " + apiCalled); exchange.getResponse().setStatusCode(HttpStatus.OK); return chain.filter(exchange); } //-------- // if(request.getMethod().equals("OPTIONS")){ exchange.getResponse().setStatusCode(HttpStatus.OK); return chain.filter(exchange); } verified = null; try{ logger.debug("----- token below -------"); logger.debug(authorization); logger.debug("----- token above -------"); verified = this.verifyToken(authorization); logger.debug(" --- --- ---"); logger.info("verified : " + verified); }catch(Exception ex) { ex.printStackTrace(); } //γιατί την μία φορά έβγαζε 401 και την άλλη 404.--// // if(verified == null || !verified){ // exchange.getResponse().getHeaders().add("Content-Type", "application/json"); // exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // byte[] bytes = "Prohibited : Unauthorized Call / User".getBytes(StandardCharsets.UTF_8); // DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes); // return exchange.getResponse().writeWith(Flux.just(buffer)); // } return chain.filter(exchange); } public Boolean verifyToken(String token) throws InterruptedException, ExecutionException { return builder.build().post().uri("lb://user/epoweredmove/user/verifyToken").header("Authorization", token) .retrieve().bodyToMono(Boolean.class).toFuture().get(); } }
diamantopoulosConstantinos/ePoweredMove
backend/micro_epoweredmove_gatewayserver/src/main/java/com/kosdiam/epoweredmove/gatewayserver/filter/AuthFilter.java
1,395
//γιατί την μία φορά έβγαζε 401 και την άλλη 404.--//
line_comment
el
package com.kosdiam.epoweredmove.gatewayserver.filter; import java.nio.charset.StandardCharsets; import java.util.Set; import java.util.concurrent.ExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Primary; import org.springframework.core.annotation.Order; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Order(1) @Component public class AuthFilter implements GlobalFilter { final Logger logger = LoggerFactory.getLogger(AuthFilter.class); @Autowired @Lazy private WebClient.Builder builder; // //USER resolves in Eureka server // private final WebClient webClient = // this.loadBalancedWebClientBuilder().build(); private Boolean verified; private String authorization; private Boolean devMode; @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); logger.info("Pre-Filter executed"); String requestPath = exchange.getRequest().getPath().toString(); logger.debug("Request path = " + requestPath); org.springframework.http.HttpHeaders headers = request.getHeaders(); Set<String> headerNames = headers.keySet(); devMode = false; headerNames.forEach((header) -> { logger.info(header + " " + headers.get(header)); if(header.equals("Authorization") || header.equals("authorization")) { authorization = headers.get(header).get(0); } if (header.equals("Devmode")) { devMode = Boolean.parseBoolean(headers.get(header).get(0)); logger.info("Devmode : inside if clause"); } }); if(!devMode) { logger.info("Devmode : false -- " + devMode); //check for specific ips and hostnames ---------------------// String remoteHost = exchange.getRequest().getHeaders().getFirst("Host"); logger.debug("Remote Host : " + remoteHost); // if(!remoteHost.contains("34.30.106.243")) { //!remoteHost.contains("localhost") && // exchange.getResponse().getHeaders().add("Content-Type", "application/json"); // exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // byte[] bytes = "Prohibited : Not Allowed Host".getBytes(StandardCharsets.UTF_8); // DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes); // return exchange.getResponse().writeWith(Flux.just(buffer)); // } } //check for specific allowed calls ---------------------// String apiCalled = exchange.getRequest().getPath().toString(); logger.debug("API Called : " + apiCalled); if(apiCalled.contains("/epoweredmove/user/createUser") || apiCalled.contains("/epoweredmove/user/verifyToken") || apiCalled.contains("/epoweredmove/poi/all") || apiCalled.contains("/epoweredmove/poi/allWithPlugAvailability") || apiCalled.contains("/epoweredmove/plug/allByChargingStation") || apiCalled.contains("/epoweredmove/plug?") || apiCalled.contains("/hello")) { logger.info("Allowed API : " + apiCalled); exchange.getResponse().setStatusCode(HttpStatus.OK); return chain.filter(exchange); } //-------- // if(request.getMethod().equals("OPTIONS")){ exchange.getResponse().setStatusCode(HttpStatus.OK); return chain.filter(exchange); } verified = null; try{ logger.debug("----- token below -------"); logger.debug(authorization); logger.debug("----- token above -------"); verified = this.verifyToken(authorization); logger.debug(" --- --- ---"); logger.info("verified : " + verified); }catch(Exception ex) { ex.printStackTrace(); } //γιατί την<SUF> // if(verified == null || !verified){ // exchange.getResponse().getHeaders().add("Content-Type", "application/json"); // exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // byte[] bytes = "Prohibited : Unauthorized Call / User".getBytes(StandardCharsets.UTF_8); // DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes); // return exchange.getResponse().writeWith(Flux.just(buffer)); // } return chain.filter(exchange); } public Boolean verifyToken(String token) throws InterruptedException, ExecutionException { return builder.build().post().uri("lb://user/epoweredmove/user/verifyToken").header("Authorization", token) .retrieve().bodyToMono(Boolean.class).toFuture().get(); } }
27876_1
package gr.gov.diavgeia.opendata.samples.decisions; import java.util.List; import java.util.ArrayList; import static java.util.Arrays.asList; import java.io.InputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Date; import org.apache.commons.io.IOUtils; import gr.gov.diavgeia.opendata.http.HttpRequests; import gr.gov.diavgeia.opendata.http.HttpResponse; import gr.gov.diavgeia.opendata.http.MultipartPostHttpRequestBuilder; import gr.gov.diavgeia.opendata.json.DecisionStoreRequest; import gr.gov.diavgeia.opendata.json.AttachmentStoreRequest; import gr.gov.diavgeia.opendata.json.Decision; import gr.gov.diavgeia.opendata.json.Errors; import gr.gov.diavgeia.opendata.json.Error; import gr.gov.diavgeia.opendata.samples.Configuration; import gr.gov.diavgeia.opendata.util.JsonUtil; import gr.gov.diavgeia.opendata.util.StringUtil; import static gr.gov.diavgeia.opendata.util.ObjectUtil.createMap; /** * * @author Diavgeia Developers */ public class PublishDecisionWithAttachment { private static final String PDF_FILE_PATH = "/gr/gov/diavgeia/opendata/samples/decisions/PublishDecision.pdf"; private static final String ATTACHMENT1_FILE_PATH = "/gr/gov/diavgeia/opendata/samples/decisions/Attachment.docx"; private static final String ATTACHMENT2_FILE_PATH = "/gr/gov/diavgeia/opendata/samples/decisions/Attachment.xlsx"; private static DecisionStoreRequest createDecisionStoreRequest() { DecisionStoreRequest decision = new DecisionStoreRequest(); long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); String entryNumber = Long.toString(nowMillis % 10000); decision.setSubject("ΑΠΟΦΑΣΗ ΑΝΑΛΗΨΗΣ ΥΠΟΧΡΕΩΣΗΣ " + entryNumber); decision.setProtocolNumber("2014/" + System.currentTimeMillis()); decision.setIssueDate(now); decision.setDecisionTypeId("Β.1.3"); // ΑΝΑΛΗΨΗ ΥΠΟΧΡΕΩΣΗΣ decision.setThematicCategoryIds(asList("20")); // ΟΙΚΟΝΟΜΙΚΕΣ ΚΑΙ ΕΜΠΟΡΙΚΕΣ ΣΥΝΑΛΛΑΓΕΣ decision.setOrganizationId("10599"); decision.setUnitIds(asList("10602")); decision.setSignerIds(asList("10911")); decision.setExtraFieldValues(createMap( "financialYear", 2014, "budgettype", "Τακτικός Προϋπολογισμός", "entryNumber", entryNumber, "partialead", false, "recalledExpenseDecision", false, "amountWithVAT", createMap( "amount", 150, "currency", "EUR" ), "amountWithKae", asList( createMap("kae", "1234", "amountWithVAT", 100), createMap("kae", "4321", "amountWithVAT", 50) ), "documentType", "ΠΡΑΞΗ" )); // Set this to false to temporarily store the decision (No ADA is created). decision.setPublish(true); decision.setAttachments(null); return decision; } private static void addAttachments(MultipartPostHttpRequestBuilder post) throws IOException { List<String> attachmentDescriptions = new ArrayList<>(); // Attachment.docx byte[] att1Bytes = null; try (InputStream attStream = PublishDecisionWithJsonString.class.getResourceAsStream(ATTACHMENT1_FILE_PATH)) { att1Bytes = IOUtils.toByteArray(attStream); attachmentDescriptions.add("The first attachment is a Word file"); // Add the rest of the attachment information in the binary part post.addFilePart("attachments", "Attachment.docx", att1Bytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); } // Attachment.xlsx byte[] att2Bytes = null; try (InputStream attStream = PublishDecisionWithJsonString.class.getResourceAsStream(ATTACHMENT2_FILE_PATH)) { att2Bytes = IOUtils.toByteArray(attStream); attachmentDescriptions.add("The second attachment is an Excel file"); // Add the rest of the attachment information in the binary part post.addFilePart("attachments", "Attachment.xlsx", att2Bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); } post.addFormField("attachmentDescr", JsonUtil.toString(attachmentDescriptions)); } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); // Prepare metadata and decision file DecisionStoreRequest decision = createDecisionStoreRequest(); byte[] pdfContent; try (InputStream pdfStream = PublishDecisionWithJsonString.class.getResourceAsStream(PDF_FILE_PATH)) { pdfContent = IOUtils.toByteArray(pdfStream); } // Prepare POST MultipartPostHttpRequestBuilder post = HttpRequests.postMultipart(conf.getBaseUrl() + "/decisions"); if (conf.isAuthenticationEnabled()) { post.addCredentials(conf.getUsername(), conf.getPassword()); } // post.addCredentials("10599_api", "User@10599"); post.addHeader("Accept", "application/json"); String jsonString = JsonUtil.toString(decision); post.addFormField("metadata", jsonString); post.addFilePart("decisionFile", "decision.pdf", pdfContent, "application/pdf"); addAttachments(post); HttpResponse response = post.execute(); if (response.getStatusCode() == HttpURLConnection.HTTP_OK) { String responseBody = StringUtil.readInputStream(response.getBody()); System.out.println(responseBody); Decision d = JsonUtil.fromString(responseBody, Decision.class); System.out.println("Got ADA: " + d.getAda()); } else { System.out.println(String.format("Error: %s %s", response.getStatusCode(), response.getStatusMessage())); if (response.getStatusCode() == HttpURLConnection.HTTP_BAD_REQUEST) { String errorBody = StringUtil.readInputStream(response.getBody()); Errors errors = JsonUtil.fromString(errorBody, Errors.class); for (Error err : errors.getErrors()) { System.out.println(String.format("%s: %s", err.getErrorCode(), err.getErrorMessage())); } } } } }
diavgeia/opendata-client-samples-java
src/main/java/gr/gov/diavgeia/opendata/samples/decisions/PublishDecisionWithAttachment.java
1,725
// ΟΙΚΟΝΟΜΙΚΕΣ ΚΑΙ ΕΜΠΟΡΙΚΕΣ ΣΥΝΑΛΛΑΓΕΣ
line_comment
el
package gr.gov.diavgeia.opendata.samples.decisions; import java.util.List; import java.util.ArrayList; import static java.util.Arrays.asList; import java.io.InputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Date; import org.apache.commons.io.IOUtils; import gr.gov.diavgeia.opendata.http.HttpRequests; import gr.gov.diavgeia.opendata.http.HttpResponse; import gr.gov.diavgeia.opendata.http.MultipartPostHttpRequestBuilder; import gr.gov.diavgeia.opendata.json.DecisionStoreRequest; import gr.gov.diavgeia.opendata.json.AttachmentStoreRequest; import gr.gov.diavgeia.opendata.json.Decision; import gr.gov.diavgeia.opendata.json.Errors; import gr.gov.diavgeia.opendata.json.Error; import gr.gov.diavgeia.opendata.samples.Configuration; import gr.gov.diavgeia.opendata.util.JsonUtil; import gr.gov.diavgeia.opendata.util.StringUtil; import static gr.gov.diavgeia.opendata.util.ObjectUtil.createMap; /** * * @author Diavgeia Developers */ public class PublishDecisionWithAttachment { private static final String PDF_FILE_PATH = "/gr/gov/diavgeia/opendata/samples/decisions/PublishDecision.pdf"; private static final String ATTACHMENT1_FILE_PATH = "/gr/gov/diavgeia/opendata/samples/decisions/Attachment.docx"; private static final String ATTACHMENT2_FILE_PATH = "/gr/gov/diavgeia/opendata/samples/decisions/Attachment.xlsx"; private static DecisionStoreRequest createDecisionStoreRequest() { DecisionStoreRequest decision = new DecisionStoreRequest(); long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); String entryNumber = Long.toString(nowMillis % 10000); decision.setSubject("ΑΠΟΦΑΣΗ ΑΝΑΛΗΨΗΣ ΥΠΟΧΡΕΩΣΗΣ " + entryNumber); decision.setProtocolNumber("2014/" + System.currentTimeMillis()); decision.setIssueDate(now); decision.setDecisionTypeId("Β.1.3"); // ΑΝΑΛΗΨΗ ΥΠΟΧΡΕΩΣΗΣ decision.setThematicCategoryIds(asList("20")); // ΟΙΚΟΝΟΜΙΚΕΣ ΚΑΙ<SUF> decision.setOrganizationId("10599"); decision.setUnitIds(asList("10602")); decision.setSignerIds(asList("10911")); decision.setExtraFieldValues(createMap( "financialYear", 2014, "budgettype", "Τακτικός Προϋπολογισμός", "entryNumber", entryNumber, "partialead", false, "recalledExpenseDecision", false, "amountWithVAT", createMap( "amount", 150, "currency", "EUR" ), "amountWithKae", asList( createMap("kae", "1234", "amountWithVAT", 100), createMap("kae", "4321", "amountWithVAT", 50) ), "documentType", "ΠΡΑΞΗ" )); // Set this to false to temporarily store the decision (No ADA is created). decision.setPublish(true); decision.setAttachments(null); return decision; } private static void addAttachments(MultipartPostHttpRequestBuilder post) throws IOException { List<String> attachmentDescriptions = new ArrayList<>(); // Attachment.docx byte[] att1Bytes = null; try (InputStream attStream = PublishDecisionWithJsonString.class.getResourceAsStream(ATTACHMENT1_FILE_PATH)) { att1Bytes = IOUtils.toByteArray(attStream); attachmentDescriptions.add("The first attachment is a Word file"); // Add the rest of the attachment information in the binary part post.addFilePart("attachments", "Attachment.docx", att1Bytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); } // Attachment.xlsx byte[] att2Bytes = null; try (InputStream attStream = PublishDecisionWithJsonString.class.getResourceAsStream(ATTACHMENT2_FILE_PATH)) { att2Bytes = IOUtils.toByteArray(attStream); attachmentDescriptions.add("The second attachment is an Excel file"); // Add the rest of the attachment information in the binary part post.addFilePart("attachments", "Attachment.xlsx", att2Bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); } post.addFormField("attachmentDescr", JsonUtil.toString(attachmentDescriptions)); } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); // Prepare metadata and decision file DecisionStoreRequest decision = createDecisionStoreRequest(); byte[] pdfContent; try (InputStream pdfStream = PublishDecisionWithJsonString.class.getResourceAsStream(PDF_FILE_PATH)) { pdfContent = IOUtils.toByteArray(pdfStream); } // Prepare POST MultipartPostHttpRequestBuilder post = HttpRequests.postMultipart(conf.getBaseUrl() + "/decisions"); if (conf.isAuthenticationEnabled()) { post.addCredentials(conf.getUsername(), conf.getPassword()); } // post.addCredentials("10599_api", "User@10599"); post.addHeader("Accept", "application/json"); String jsonString = JsonUtil.toString(decision); post.addFormField("metadata", jsonString); post.addFilePart("decisionFile", "decision.pdf", pdfContent, "application/pdf"); addAttachments(post); HttpResponse response = post.execute(); if (response.getStatusCode() == HttpURLConnection.HTTP_OK) { String responseBody = StringUtil.readInputStream(response.getBody()); System.out.println(responseBody); Decision d = JsonUtil.fromString(responseBody, Decision.class); System.out.println("Got ADA: " + d.getAda()); } else { System.out.println(String.format("Error: %s %s", response.getStatusCode(), response.getStatusMessage())); if (response.getStatusCode() == HttpURLConnection.HTTP_BAD_REQUEST) { String errorBody = StringUtil.readInputStream(response.getBody()); Errors errors = JsonUtil.fromString(errorBody, Errors.class); for (Error err : errors.getErrors()) { System.out.println(String.format("%s: %s", err.getErrorCode(), err.getErrorMessage())); } } } } }
2040_1
package com.dimipet.bank; import java.util.ArrayList; import java.util.List; public class Bank { private String name; private List<Account> accounts; public Bank(String name) { this.name = name; accounts = new ArrayList<Account>(); } public String getName() { return name; } /** * Αίτηση δημιουργίας νέου λογαριασμού * @param name * @param annualIncome */ public Account applyForAccount(String name, int annualIncome) { Account a = null; if(annualIncome>10000) { System.out.println("Η αίτηση σας εγκρίθηκε"); a = createAccount(name); } else { System.out.println("Η αίτηση σας απορρίφθηκε, το ετήσιο εισόδημα σας είναι πολύ χαμηλό"); } return a; } /** * Δημιουργια νεου πελατη και λογαριασμου * * @param customerName * @return */ private Account createAccount(String customerName) { Customer newCustomer = new Customer(customerName); Account newAccount = new Account(Utils.getRandomAccountId(), newCustomer); accounts.add(newAccount); System.out.println("Η τράπεζα " + this.name + " δημιουργησε τον λογαριασμό " + newAccount.getId() + " για τον πελάτη " + newCustomer.getName()); return newAccount; } /** * Δημιουργία κάρτας και ανάθεσης της σε πελάτη * @param customer * @param cardType * @return */ public Card createAndAssignCard(Customer customer, CardType cardType) { //new Card(String type, int number, String holder, int ccv, int pin, String expiration); Card newCard = new Card(cardType, Utils.getCardRandomNumber(), customer.getName(), Utils.getCardRandomCcv(), Utils.getCardRandomPin(), Utils.getCardRandomExpirationDate()); customer.setCard(newCard); System.out.println("Created " + newCard.toString() + " and assigned to " + customer.toString()); return newCard; } /** * εμφανιση ολων των λογαριασμων */ public void printAllAccounts() { System.out.println("----------------------------------------"); System.out.println("Εμφανιση ολων των λογαριασμων"); for(Account a : accounts) { System.out.println(a.toString()); } } }
dimipet/edu
Java/simpleApps/bank/src/com/dimipet/bank/Bank.java
810
/** * Δημιουργια νεου πελατη και λογαριασμου * * @param customerName * @return */
block_comment
el
package com.dimipet.bank; import java.util.ArrayList; import java.util.List; public class Bank { private String name; private List<Account> accounts; public Bank(String name) { this.name = name; accounts = new ArrayList<Account>(); } public String getName() { return name; } /** * Αίτηση δημιουργίας νέου λογαριασμού * @param name * @param annualIncome */ public Account applyForAccount(String name, int annualIncome) { Account a = null; if(annualIncome>10000) { System.out.println("Η αίτηση σας εγκρίθηκε"); a = createAccount(name); } else { System.out.println("Η αίτηση σας απορρίφθηκε, το ετήσιο εισόδημα σας είναι πολύ χαμηλό"); } return a; } /** * Δημιουργια νεου πελατη<SUF>*/ private Account createAccount(String customerName) { Customer newCustomer = new Customer(customerName); Account newAccount = new Account(Utils.getRandomAccountId(), newCustomer); accounts.add(newAccount); System.out.println("Η τράπεζα " + this.name + " δημιουργησε τον λογαριασμό " + newAccount.getId() + " για τον πελάτη " + newCustomer.getName()); return newAccount; } /** * Δημιουργία κάρτας και ανάθεσης της σε πελάτη * @param customer * @param cardType * @return */ public Card createAndAssignCard(Customer customer, CardType cardType) { //new Card(String type, int number, String holder, int ccv, int pin, String expiration); Card newCard = new Card(cardType, Utils.getCardRandomNumber(), customer.getName(), Utils.getCardRandomCcv(), Utils.getCardRandomPin(), Utils.getCardRandomExpirationDate()); customer.setCard(newCard); System.out.println("Created " + newCard.toString() + " and assigned to " + customer.toString()); return newCard; } /** * εμφανιση ολων των λογαριασμων */ public void printAllAccounts() { System.out.println("----------------------------------------"); System.out.println("Εμφανιση ολων των λογαριασμων"); for(Account a : accounts) { System.out.println(a.toString()); } } }
31412_0
package gr.aueb.cf.ch16.products; import java.util.ArrayList; import java.util.Collections; import java.util.List; public abstract class AbstractGenericProduct implements IGenericProduct { private static List<IGenericProduct> products = new ArrayList<>(); private long id; private String productName; private String description; private double price; private int quantity; public AbstractGenericProduct() { } public AbstractGenericProduct(long id, String productName, String description, double price, int quantity) { this.id = id; this.productName = productName; this.description = description; this.price = price; this.quantity = quantity; } public static List<IGenericProduct> getProducts() { return Collections.unmodifiableList(products); // επιστρέφει unmodifiable λίστα } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } @Override public void insert() { products.add(this); // } }
dimisysk/java-coding-factory
src/gr/aueb/cf/ch16/products/AbstractGenericProduct.java
393
// επιστρέφει unmodifiable λίστα
line_comment
el
package gr.aueb.cf.ch16.products; import java.util.ArrayList; import java.util.Collections; import java.util.List; public abstract class AbstractGenericProduct implements IGenericProduct { private static List<IGenericProduct> products = new ArrayList<>(); private long id; private String productName; private String description; private double price; private int quantity; public AbstractGenericProduct() { } public AbstractGenericProduct(long id, String productName, String description, double price, int quantity) { this.id = id; this.productName = productName; this.description = description; this.price = price; this.quantity = quantity; } public static List<IGenericProduct> getProducts() { return Collections.unmodifiableList(products); // επιστρέφει unmodifiable<SUF> } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } @Override public void insert() { products.add(this); // } }
26419_0
package gr.dcu.utils; /** * * @author Δημήτρης Γαβρίλης */ import java.util.Iterator; import javax.xml.*; import javax.xml.namespace.NamespaceContext; public class MoReNamespaceContext implements NamespaceContext { @Override public String getNamespaceURI(String prefix) { //ystem.out.println(prefix); if (prefix == null) throw new NullPointerException("Null prefix"); else if ("edm".equals(prefix)) return "http://www.europeana.eu/schemas/edm/"; else if ("car".equals(prefix)) return "http://www.dcu.gr/carareSchema"; else if ("carare".equals(prefix)) return "http://www.carare.eu/carareSchema"; else if ("dc".equals(prefix)) return "http://purl.org/dc/elements/1.1/"; else if ("dcterms".equals(prefix)) return "http://purl.org/dc/terms/"; else if ("oai_dc".equals(prefix)) return "http://www.openarchives.org/OAI/2.0/oai_dc/"; else if ("ore".equals(prefix)) return "http://www.openarchives.org/ore/terms/"; else if ("xsi".equals(prefix)) return "http://www.w3.org/2001/XMLSchema-instance"; else if ("rdf".equals(prefix)) return "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; else if ("wgs84_pos".equals(prefix)) return "http://www.w3.org/2003/01/geo/wgs84_pos#"; else if ("europeana".equals(prefix)) return "http://www.europeana.eu/schemas/ese/"; else if ("skos".equals(prefix)) return "http://www.w3.org/2004/02/skos/core#"; else if ("owl".equals(prefix)) return "http://www.w3.org/2002/07/owl#"; else if ("foaf".equals(prefix)) return "http://xmlns.com/foaf/"; else if ("rdau".equals(prefix)) return "http://www.rdaregistry.info/Elements/u/"; else if ("crm".equals(prefix)) return "http://www.cidoc-crm.org/rdfs/cidoc-crm#"; else if ("emd".equals(prefix)) return "http://easy.dans.knaw.nl/easy/easymetadata/"; else if ("cc".equals(prefix)) return "https://creativecommons.org/ns#"; // else if ("acdm".equals(prefix)) return "http://schemas.cloud.dcu.gr/ariadne-registry/"; else if ("acdm".equals(prefix)) return "http://registry.ariadne-infrastructure.eu/"; else if ("oai".equals(prefix)) return "http://www.openarchives.org/OAI/2.0/"; else if ("marc".equals(prefix)) return "http://www.loc.gov/MARC21/slim"; else if ("dli".equals(prefix)) return "http://dliservice.research-infrastructures.eu"; else if ("mets".equals(prefix)) return "http://www.loc.gov/METS/"; else if ("mods".equals(prefix)) return "http://www.loc.gov/mods/v3"; else if ("agls".equals(prefix)) return "http://www.naa.gov.au/recordkeeping/gov_online/agls/1.2"; else if ("ags".equals(prefix)) return "http://purl.org/agmes/1.1/"; else if ("xalan".equals(prefix)) return "http://xml.apache.org/xalan"; else if ("dcat".equals(prefix)) return "http://www.w3.org/acdm/dcat#"; else if ("geo".equals(prefix)) return "http://www.w3.org/2003/01/geo/wgs84_pos"; else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI; return XMLConstants.NULL_NS_URI; } // This method isn't necessary for XPath processing. @Override public String getPrefix(String uri) { throw new UnsupportedOperationException(); } // This method isn't necessary for XPath processing either. @Override public Iterator getPrefixes(String uri) { throw new UnsupportedOperationException(); } }
dimitrisgavrilis/europeana-archaeology-api
src/main/java/gr/dcu/utils/MoReNamespaceContext.java
1,086
/** * * @author Δημήτρης Γαβρίλης */
block_comment
el
package gr.dcu.utils; /** * * @author Δημήτρης Γαβρίλης<SUF>*/ import java.util.Iterator; import javax.xml.*; import javax.xml.namespace.NamespaceContext; public class MoReNamespaceContext implements NamespaceContext { @Override public String getNamespaceURI(String prefix) { //ystem.out.println(prefix); if (prefix == null) throw new NullPointerException("Null prefix"); else if ("edm".equals(prefix)) return "http://www.europeana.eu/schemas/edm/"; else if ("car".equals(prefix)) return "http://www.dcu.gr/carareSchema"; else if ("carare".equals(prefix)) return "http://www.carare.eu/carareSchema"; else if ("dc".equals(prefix)) return "http://purl.org/dc/elements/1.1/"; else if ("dcterms".equals(prefix)) return "http://purl.org/dc/terms/"; else if ("oai_dc".equals(prefix)) return "http://www.openarchives.org/OAI/2.0/oai_dc/"; else if ("ore".equals(prefix)) return "http://www.openarchives.org/ore/terms/"; else if ("xsi".equals(prefix)) return "http://www.w3.org/2001/XMLSchema-instance"; else if ("rdf".equals(prefix)) return "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; else if ("wgs84_pos".equals(prefix)) return "http://www.w3.org/2003/01/geo/wgs84_pos#"; else if ("europeana".equals(prefix)) return "http://www.europeana.eu/schemas/ese/"; else if ("skos".equals(prefix)) return "http://www.w3.org/2004/02/skos/core#"; else if ("owl".equals(prefix)) return "http://www.w3.org/2002/07/owl#"; else if ("foaf".equals(prefix)) return "http://xmlns.com/foaf/"; else if ("rdau".equals(prefix)) return "http://www.rdaregistry.info/Elements/u/"; else if ("crm".equals(prefix)) return "http://www.cidoc-crm.org/rdfs/cidoc-crm#"; else if ("emd".equals(prefix)) return "http://easy.dans.knaw.nl/easy/easymetadata/"; else if ("cc".equals(prefix)) return "https://creativecommons.org/ns#"; // else if ("acdm".equals(prefix)) return "http://schemas.cloud.dcu.gr/ariadne-registry/"; else if ("acdm".equals(prefix)) return "http://registry.ariadne-infrastructure.eu/"; else if ("oai".equals(prefix)) return "http://www.openarchives.org/OAI/2.0/"; else if ("marc".equals(prefix)) return "http://www.loc.gov/MARC21/slim"; else if ("dli".equals(prefix)) return "http://dliservice.research-infrastructures.eu"; else if ("mets".equals(prefix)) return "http://www.loc.gov/METS/"; else if ("mods".equals(prefix)) return "http://www.loc.gov/mods/v3"; else if ("agls".equals(prefix)) return "http://www.naa.gov.au/recordkeeping/gov_online/agls/1.2"; else if ("ags".equals(prefix)) return "http://purl.org/agmes/1.1/"; else if ("xalan".equals(prefix)) return "http://xml.apache.org/xalan"; else if ("dcat".equals(prefix)) return "http://www.w3.org/acdm/dcat#"; else if ("geo".equals(prefix)) return "http://www.w3.org/2003/01/geo/wgs84_pos"; else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI; return XMLConstants.NULL_NS_URI; } // This method isn't necessary for XPath processing. @Override public String getPrefix(String uri) { throw new UnsupportedOperationException(); } // This method isn't necessary for XPath processing either. @Override public Iterator getPrefixes(String uri) { throw new UnsupportedOperationException(); } }
16592_1
package model; import jakarta.persistence.*; import java.util.Random; @Entity @Table(name = "Transactions") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "TransactionType", discriminatorType = DiscriminatorType.STRING) @DiscriminatorValue(value = "Transactions") public class Transactions { @Id @Column(name = "ID", nullable = false, length = 50) private String ID; @Column(name = "Date", nullable = false, length = 50) private String date; @Column(name = "Amount", nullable = false, length = 50) private double amount; @Column(name = "Description", nullable = false, length = 50) private String description; @Column(name = "ClientUsername", nullable = false, length = 50) private String clientusername; // χρησιμοποιείται για να ξέρουμε ποιανού το transaction είναι public Transactions() { } public Transactions(String ID, String date, double amount, String description, String clientusername) { this.ID = genID(); this.date = date; this.amount = amount; this.description = description; this.clientusername = clientusername; } public double calculateNewBalance(double balance, double amount){ balance += amount; return balance ; } public String genID(){ //Δημιουργία ενός τυχαίου ID με 8 χαρακτήρες π.χ. kHFujh%4 String characters ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+"; int length = 8; Random random = new Random(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < length; i++) { int index = random.nextInt(characters.length()); builder.append(characters.charAt(index)); } return builder.toString(); } public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getClientusername() { return clientusername; } public void setClientusername(String clientusername) { this.clientusername = clientusername; } }
dimsparagis0210/UomBankingApp
src/main/java/model/Transactions.java
673
//Δημιουργία ενός τυχαίου ID με 8 χαρακτήρες π.χ. kHFujh%4
line_comment
el
package model; import jakarta.persistence.*; import java.util.Random; @Entity @Table(name = "Transactions") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "TransactionType", discriminatorType = DiscriminatorType.STRING) @DiscriminatorValue(value = "Transactions") public class Transactions { @Id @Column(name = "ID", nullable = false, length = 50) private String ID; @Column(name = "Date", nullable = false, length = 50) private String date; @Column(name = "Amount", nullable = false, length = 50) private double amount; @Column(name = "Description", nullable = false, length = 50) private String description; @Column(name = "ClientUsername", nullable = false, length = 50) private String clientusername; // χρησιμοποιείται για να ξέρουμε ποιανού το transaction είναι public Transactions() { } public Transactions(String ID, String date, double amount, String description, String clientusername) { this.ID = genID(); this.date = date; this.amount = amount; this.description = description; this.clientusername = clientusername; } public double calculateNewBalance(double balance, double amount){ balance += amount; return balance ; } public String genID(){ //Δημιουργία ενός<SUF> String characters ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+"; int length = 8; Random random = new Random(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < length; i++) { int index = random.nextInt(characters.length()); builder.append(characters.charAt(index)); } return builder.toString(); } public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getClientusername() { return clientusername; } public void setClientusername(String clientusername) { this.clientusername = clientusername; } }
603_4
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dkpro.core.io.xces; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.IOException; import java.io.InputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.apache.uima.collection.CollectionException; import org.apache.uima.fit.descriptor.MimeTypeCapability; import org.apache.uima.fit.descriptor.ResourceMetaData; import org.apache.uima.fit.descriptor.TypeCapability; import org.apache.uima.fit.factory.JCasBuilder; import org.apache.uima.jcas.JCas; import org.dkpro.core.api.io.JCasResourceCollectionReader_ImplBase; import org.dkpro.core.api.parameter.MimeTypes; import org.dkpro.core.api.resources.CompressionUtils; import org.dkpro.core.io.xces.models.XcesBody; import org.dkpro.core.io.xces.models.XcesPara; import org.dkpro.core.io.xces.models.XcesSentence; import org.dkpro.core.io.xces.models.XcesToken; import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import eu.openminted.share.annotations.api.DocumentationResource; /** * Reader for the XCES XML format. */ @ResourceMetaData(name = "XCES XML Reader") @DocumentationResource("${docbase}/format-reference.html#format-${command}") @TypeCapability( outputs = { "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token" }) @MimeTypeCapability({MimeTypes.APPLICATION_X_XCES}) public class XcesXmlReader extends JCasResourceCollectionReader_ImplBase { @Override public void getNext(JCas aJCas) throws IOException, CollectionException { Resource res = nextFile(); initCas(aJCas, res); InputStream is = null; try { is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream()); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is); JAXBContext context = JAXBContext.newInstance(XcesBody.class); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setEventHandler(new ValidationEventHandler() { @Override public boolean handleEvent(ValidationEvent event) { throw new RuntimeException(event.getMessage(), event.getLinkedException()); } }); JCasBuilder jb = new JCasBuilder(aJCas); XMLEvent e = null; while ((e = xmlEventReader.peek()) != null) { if (isStartElement(e, "body")) { try { XcesBody paras = (XcesBody) unmarshaller .unmarshal(xmlEventReader, XcesBody.class).getValue(); readPara(jb, paras); } catch (RuntimeException ex) { System.out.println("Unable to parse XCES format: " + ex); } } else { xmlEventReader.next(); } } jb.close(); } catch (XMLStreamException ex1) { throw new IOException(ex1); } catch (JAXBException e1) { throw new IOException(e1); } finally { closeQuietly(is); } } private void readPara(JCasBuilder jb, Object bodyObj) { // Below is the sample paragraph format // <p id="p1"> // <s id="s1"> // <t id="t1" word="Αυτή" tag="PnDmFe03SgNmXx" lemma="αυτός" /> // <t id="t2" word="είναι" tag="VbMnIdPr03SgXxIpPvXx" lemma="είμαι" /> // <t id="t3" word="η" tag="AtDfFeSgNm" lemma="ο" /> // <t id="t4" word="πρώτη" tag="NmOdFeSgNmAj" lemma="πρώτος" /> // <t id="t5" word="γραμμή" tag="NoCmFeSgNm" lemma="γραμμή" /> // <t id="t6" word="." tag="PTERM_P" lemma="." /> // </s> // </p> if (bodyObj instanceof XcesBody) { for (XcesPara paras : ((XcesBody) bodyObj).p) { int paraStart = jb.getPosition(); int paraEnd = jb.getPosition(); for (XcesSentence s : paras.s) { int sentStart = jb.getPosition(); int sentEnd = jb.getPosition(); for (int i = 0; i < s.xcesTokens.size(); i++) { XcesToken t = s.xcesTokens.get(i); XcesToken tnext = i + 1 == s.xcesTokens.size() ? null : s.xcesTokens.get(i + 1); Token token = jb.add(t.word, Token.class); if (t.lemma != null) { Lemma lemma = new Lemma(jb.getJCas(), token.getBegin(), token.getEnd()); lemma.setValue(t.lemma); lemma.addToIndexes(); token.setLemma(lemma); } if (t.tag != null) { POS pos = new POS(jb.getJCas(), token.getBegin(), token.getEnd()); pos.setPosValue(t.tag); pos.addToIndexes(); token.setPos(pos); } sentEnd = jb.getPosition(); if (tnext == null) { jb.add("\n"); } if (tnext != null) { jb.add(" "); } } Sentence sent = new Sentence(jb.getJCas(), sentStart, sentEnd); sent.addToIndexes(); paraEnd = sent.getEnd(); } Paragraph para = new Paragraph(jb.getJCas(), paraStart, paraEnd); para.addToIndexes(); jb.add("\n"); } } } public static boolean isStartElement(XMLEvent aEvent, String aElement) { return aEvent.isStartElement() && ((StartElement) aEvent).getName().getLocalPart().equals(aElement); } }
dkpro/dkpro-core
dkpro-core-io-xces-asl/src/main/java/org/dkpro/core/io/xces/XcesXmlReader.java
2,014
// <t id="t2" word="είναι" tag="VbMnIdPr03SgXxIpPvXx" lemma="είμαι" />
line_comment
el
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dkpro.core.io.xces; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.IOException; import java.io.InputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.apache.uima.collection.CollectionException; import org.apache.uima.fit.descriptor.MimeTypeCapability; import org.apache.uima.fit.descriptor.ResourceMetaData; import org.apache.uima.fit.descriptor.TypeCapability; import org.apache.uima.fit.factory.JCasBuilder; import org.apache.uima.jcas.JCas; import org.dkpro.core.api.io.JCasResourceCollectionReader_ImplBase; import org.dkpro.core.api.parameter.MimeTypes; import org.dkpro.core.api.resources.CompressionUtils; import org.dkpro.core.io.xces.models.XcesBody; import org.dkpro.core.io.xces.models.XcesPara; import org.dkpro.core.io.xces.models.XcesSentence; import org.dkpro.core.io.xces.models.XcesToken; import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import eu.openminted.share.annotations.api.DocumentationResource; /** * Reader for the XCES XML format. */ @ResourceMetaData(name = "XCES XML Reader") @DocumentationResource("${docbase}/format-reference.html#format-${command}") @TypeCapability( outputs = { "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence", "de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token" }) @MimeTypeCapability({MimeTypes.APPLICATION_X_XCES}) public class XcesXmlReader extends JCasResourceCollectionReader_ImplBase { @Override public void getNext(JCas aJCas) throws IOException, CollectionException { Resource res = nextFile(); initCas(aJCas, res); InputStream is = null; try { is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream()); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is); JAXBContext context = JAXBContext.newInstance(XcesBody.class); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setEventHandler(new ValidationEventHandler() { @Override public boolean handleEvent(ValidationEvent event) { throw new RuntimeException(event.getMessage(), event.getLinkedException()); } }); JCasBuilder jb = new JCasBuilder(aJCas); XMLEvent e = null; while ((e = xmlEventReader.peek()) != null) { if (isStartElement(e, "body")) { try { XcesBody paras = (XcesBody) unmarshaller .unmarshal(xmlEventReader, XcesBody.class).getValue(); readPara(jb, paras); } catch (RuntimeException ex) { System.out.println("Unable to parse XCES format: " + ex); } } else { xmlEventReader.next(); } } jb.close(); } catch (XMLStreamException ex1) { throw new IOException(ex1); } catch (JAXBException e1) { throw new IOException(e1); } finally { closeQuietly(is); } } private void readPara(JCasBuilder jb, Object bodyObj) { // Below is the sample paragraph format // <p id="p1"> // <s id="s1"> // <t id="t1" word="Αυτή" tag="PnDmFe03SgNmXx" lemma="αυτός" /> // <t id="t2"<SUF> // <t id="t3" word="η" tag="AtDfFeSgNm" lemma="ο" /> // <t id="t4" word="πρώτη" tag="NmOdFeSgNmAj" lemma="πρώτος" /> // <t id="t5" word="γραμμή" tag="NoCmFeSgNm" lemma="γραμμή" /> // <t id="t6" word="." tag="PTERM_P" lemma="." /> // </s> // </p> if (bodyObj instanceof XcesBody) { for (XcesPara paras : ((XcesBody) bodyObj).p) { int paraStart = jb.getPosition(); int paraEnd = jb.getPosition(); for (XcesSentence s : paras.s) { int sentStart = jb.getPosition(); int sentEnd = jb.getPosition(); for (int i = 0; i < s.xcesTokens.size(); i++) { XcesToken t = s.xcesTokens.get(i); XcesToken tnext = i + 1 == s.xcesTokens.size() ? null : s.xcesTokens.get(i + 1); Token token = jb.add(t.word, Token.class); if (t.lemma != null) { Lemma lemma = new Lemma(jb.getJCas(), token.getBegin(), token.getEnd()); lemma.setValue(t.lemma); lemma.addToIndexes(); token.setLemma(lemma); } if (t.tag != null) { POS pos = new POS(jb.getJCas(), token.getBegin(), token.getEnd()); pos.setPosValue(t.tag); pos.addToIndexes(); token.setPos(pos); } sentEnd = jb.getPosition(); if (tnext == null) { jb.add("\n"); } if (tnext != null) { jb.add(" "); } } Sentence sent = new Sentence(jb.getJCas(), sentStart, sentEnd); sent.addToIndexes(); paraEnd = sent.getEnd(); } Paragraph para = new Paragraph(jb.getJCas(), paraStart, paraEnd); para.addToIndexes(); jb.add("\n"); } } } public static boolean isStartElement(XMLEvent aEvent, String aElement) { return aEvent.isStartElement() && ((StartElement) aEvent).getName().getLocalPart().equals(aElement); } }
1633_7
/* This file is part of SmartLib Project. SmartLib is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SmartLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with SmartLib. If not, see <http://www.gnu.org/licenses/>. Author: Paschalis Mpeis Affiliation: Data Management Systems Laboratory Dept. of Computer Science University of Cyprus P.O. Box 20537 1678 Nicosia, CYPRUS Web: http://dmsl.cs.ucy.ac.cy/ Email: [email protected] Tel: +357-22-892755 Fax: +357-22-892701 */ package cy.ac.ucy.paschalis.client.android; /** * The Library User * * @author paschalis */ public class User { /** * Username User puts on login form */ String username; /** * Password User puts on login form */ String password; /** * Name of user */ String name; /** * Surname of user */ String surname; String email; String telephone; /* @formatter:off */ /** * Level Explanation * 0: ούτε ειδοποιήσεις εντός εφαρμογής, ούτε email * 1: μόνο ειδοποιήσεις εντός εφαρμογής * 2: μόνο ειδοποιήσεις μέσω email * 3: και ειδοποιήσεις εντός εφαρμογής αλλά και email */ /* @formatter:on */ int allowRequests = ALLOW_REQUESTS_NOT_SET; public static final int ALLOW_REQUESTS_NOTHING = 0; public static final int ALLOW_REQUESTS_APP = 1; public static final int ALLOW_REQUESTS_EMAIL = 2; public static final int ALLOW_REQUESTS_ALL = 3; public static final int ALLOW_REQUESTS_NOT_SET = -10; /* @formatter:off */ /** * Level of User * Level 2: Μπορεί να κάνει κάποιον Level2(mod), ή να διαγράψει κάποιον χρήστη από την Βιβλιοθήκη * Level 1: Μπορεί να εισάγει τις προσωπικές του Βιβλιοθήκες * Level 0: Ο χρήστης δεν ενεργοποίησε ακόμη τον λογαριασμό του μέσω του email του. * Level -1: Ο χρήστης είναι επισκέπτης στο σύστημα. */ /* @formatter:on */ int level = LEVEL_NOT_SET; public int totalBooks = 0; public static final int LEVEL_MOD = 2; public static final int LEVEL_ACTIVATED = 1; public static final int LEVEL_NOT_ACTIVATED = 0; public static final int LEVEL_VISITOR = -1; /** * Exists only in Android enviroment, to flag user credencials as invalid */ public static final int LEVEL_BANNED = -2; public static final int LEVEL_NOT_SET = -10; }
dmsl/smartlib
Android - Corrected - Play Version/src/cy/ac/ucy/paschalis/client/android/User.java
1,074
/** * Level of User * Level 2: Μπορεί να κάνει κάποιον Level2(mod), ή να διαγράψει κάποιον χρήστη από την Βιβλιοθήκη * Level 1: Μπορεί να εισάγει τις προσωπικές του Βιβλιοθήκες * Level 0: Ο χρήστης δεν ενεργοποίησε ακόμη τον λογαριασμό του μέσω του email του. * Level -1: Ο χρήστης είναι επισκέπτης στο σύστημα. */
block_comment
el
/* This file is part of SmartLib Project. SmartLib is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SmartLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with SmartLib. If not, see <http://www.gnu.org/licenses/>. Author: Paschalis Mpeis Affiliation: Data Management Systems Laboratory Dept. of Computer Science University of Cyprus P.O. Box 20537 1678 Nicosia, CYPRUS Web: http://dmsl.cs.ucy.ac.cy/ Email: [email protected] Tel: +357-22-892755 Fax: +357-22-892701 */ package cy.ac.ucy.paschalis.client.android; /** * The Library User * * @author paschalis */ public class User { /** * Username User puts on login form */ String username; /** * Password User puts on login form */ String password; /** * Name of user */ String name; /** * Surname of user */ String surname; String email; String telephone; /* @formatter:off */ /** * Level Explanation * 0: ούτε ειδοποιήσεις εντός εφαρμογής, ούτε email * 1: μόνο ειδοποιήσεις εντός εφαρμογής * 2: μόνο ειδοποιήσεις μέσω email * 3: και ειδοποιήσεις εντός εφαρμογής αλλά και email */ /* @formatter:on */ int allowRequests = ALLOW_REQUESTS_NOT_SET; public static final int ALLOW_REQUESTS_NOTHING = 0; public static final int ALLOW_REQUESTS_APP = 1; public static final int ALLOW_REQUESTS_EMAIL = 2; public static final int ALLOW_REQUESTS_ALL = 3; public static final int ALLOW_REQUESTS_NOT_SET = -10; /* @formatter:off */ /** * Level of User<SUF>*/ /* @formatter:on */ int level = LEVEL_NOT_SET; public int totalBooks = 0; public static final int LEVEL_MOD = 2; public static final int LEVEL_ACTIVATED = 1; public static final int LEVEL_NOT_ACTIVATED = 0; public static final int LEVEL_VISITOR = -1; /** * Exists only in Android enviroment, to flag user credencials as invalid */ public static final int LEVEL_BANNED = -2; public static final int LEVEL_NOT_SET = -10; }
3423_6
package esk.lottery.RegistrationUpdater; import esk.lottery.Config; import esk.lottery.Statistics.StatisticsCollector; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashMap; /** * Συγκεντρώνει εγγραφές (επιτυχείς και ανεπτυχείς) από το έμπειρο σύστημα και * όταν φτάσει σε ένα συγκεκριμένο νούμερο (δηλωμένο σαν σταθερά στο config) * ανήγει ένα ξεχωριστό thread και ενημερώνει την αποθήκη δεδομένων. * @author Dimosthenis Nikoudis */ public class RegistrationUpdater implements Runnable { /** * Ο πίνακας που κρατάει τις εγγραφές που πρόκειται να περαστούν στη βάση. */ protected ArrayList<Registration> registrations = new ArrayList<Registration>(); /** * Πίνακας που κρατάει τα διάφορα update threads. */ protected HashMap registrationUpdaterThreads = new HashMap(); /** * Ο αριθμός των εγγραφών που πρέπει να συγκεντρωθεί για να γίνει update * στην βάση. Το update θα γίνει σε ξεχωριστό thread. */ protected Integer registrationsBeforeUpdate; /** * Το αντικείμενο StatisticsCollector που θα συλλέγει στατιστικά. * Χρειάζεται εδώ για να του στέλνει updates ο RegistrationUpdater. */ protected StatisticsCollector statisticsCollector; /** * Αρχικοποιεί το αντικείμενο RegistrationUpdater. * @param registrationsBeforeUpdate Ο αριθμός των εγγραφών που πρέπει να * συγκεντρωθεί για να γίνει update στην βάση. */ public RegistrationUpdater(Integer registrationsBeforeUpdate) { this.registrationsBeforeUpdate = registrationsBeforeUpdate; } /** * Αρχικοποιεί το αντικείμενο RegistrationUpdater. Ορίζει μια default τιμή * στην ιδιότητα registrationsBeforeUpdate (200). */ public RegistrationUpdater() { this(600); } public void addRegistration(Registration r) { // Ενημέρωση των στατιστικών if(statisticsCollector != null) { statisticsCollector.collectStat(r); } registrations.add(r); if(registrations.size() >= registrationsBeforeUpdate) { update(); } } public void update() { Thread thread = new Thread(this); registrationUpdaterThreads.put(thread.getId(), thread); thread.start(); } public void join() { update(); // Πριν κάνουμε join εξασφαλίζουμε ότι έχουν γίνει όλα τα updates synchronized(this) { try { Collection<Thread> registrationUpdaterThreadsCollection = registrationUpdaterThreads.values(); for(Thread thread : registrationUpdaterThreadsCollection) { try { thread.join(); } catch (InterruptedException ex) { System.err.println(ex.toString()); } } } catch(ConcurrentModificationException ex) { //System.err.println(ex); //System.err.println(ex.getCause()); } } } /** * Το thread που θα ενημερώσει την αποθήκη δεδομένων. Όταν τελειώσει αυτή η * συνάρτηση το αντικείμενο δεν θα περιέχει καμία εγγραφή. */ public void run() { // Αποθήκευση των αποτελεσμάτων στη βάση if(Config.get().getProperty("simulationMode", "1").equals("0")) { ArrayList<Registration> tempReg = new ArrayList<Registration>(registrations); registrations = new ArrayList<Registration>(); Config.get().getDataHandler().updateRegistrations(tempReg); } else { System.out.println("Simulation mode is active. No database changes."); } registrationUpdaterThreads.remove(Thread.currentThread().getId()); // Remove the thread after its finished } /** * Δηλώνει ένα αντικείμενο StatisticsCollector ώστε να του στέλονται * στατιστικά για κάθε επιτυχημένη/αποτυχημένη εγγραφή. * @param statisticsCollector Το αντικείμενο που θα συλλέγει τα στατιστικά. */ public void setStatisticsCollector(StatisticsCollector statisticsCollector) { this.statisticsCollector = statisticsCollector; } /** * Επιστρέφει το αντικείμενο StatisticsCollector που έχει δηλωθεί για να * συλλέγει στατιστικά. * @return Το αντικείμενο που έχει δηλωθεί για να συλλέγει στατιστικά. */ public StatisticsCollector getStatisticsCollector() { return this.statisticsCollector; } }
dnna/seep-thesis
sourceCode/esk/src/esk/lottery/RegistrationUpdater/RegistrationUpdater.java
1,718
/** * Αρχικοποιεί το αντικείμενο RegistrationUpdater. Ορίζει μια default τιμή * στην ιδιότητα registrationsBeforeUpdate (200). */
block_comment
el
package esk.lottery.RegistrationUpdater; import esk.lottery.Config; import esk.lottery.Statistics.StatisticsCollector; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashMap; /** * Συγκεντρώνει εγγραφές (επιτυχείς και ανεπτυχείς) από το έμπειρο σύστημα και * όταν φτάσει σε ένα συγκεκριμένο νούμερο (δηλωμένο σαν σταθερά στο config) * ανήγει ένα ξεχωριστό thread και ενημερώνει την αποθήκη δεδομένων. * @author Dimosthenis Nikoudis */ public class RegistrationUpdater implements Runnable { /** * Ο πίνακας που κρατάει τις εγγραφές που πρόκειται να περαστούν στη βάση. */ protected ArrayList<Registration> registrations = new ArrayList<Registration>(); /** * Πίνακας που κρατάει τα διάφορα update threads. */ protected HashMap registrationUpdaterThreads = new HashMap(); /** * Ο αριθμός των εγγραφών που πρέπει να συγκεντρωθεί για να γίνει update * στην βάση. Το update θα γίνει σε ξεχωριστό thread. */ protected Integer registrationsBeforeUpdate; /** * Το αντικείμενο StatisticsCollector που θα συλλέγει στατιστικά. * Χρειάζεται εδώ για να του στέλνει updates ο RegistrationUpdater. */ protected StatisticsCollector statisticsCollector; /** * Αρχικοποιεί το αντικείμενο RegistrationUpdater. * @param registrationsBeforeUpdate Ο αριθμός των εγγραφών που πρέπει να * συγκεντρωθεί για να γίνει update στην βάση. */ public RegistrationUpdater(Integer registrationsBeforeUpdate) { this.registrationsBeforeUpdate = registrationsBeforeUpdate; } /** * Αρχικοποιεί το αντικείμενο<SUF>*/ public RegistrationUpdater() { this(600); } public void addRegistration(Registration r) { // Ενημέρωση των στατιστικών if(statisticsCollector != null) { statisticsCollector.collectStat(r); } registrations.add(r); if(registrations.size() >= registrationsBeforeUpdate) { update(); } } public void update() { Thread thread = new Thread(this); registrationUpdaterThreads.put(thread.getId(), thread); thread.start(); } public void join() { update(); // Πριν κάνουμε join εξασφαλίζουμε ότι έχουν γίνει όλα τα updates synchronized(this) { try { Collection<Thread> registrationUpdaterThreadsCollection = registrationUpdaterThreads.values(); for(Thread thread : registrationUpdaterThreadsCollection) { try { thread.join(); } catch (InterruptedException ex) { System.err.println(ex.toString()); } } } catch(ConcurrentModificationException ex) { //System.err.println(ex); //System.err.println(ex.getCause()); } } } /** * Το thread που θα ενημερώσει την αποθήκη δεδομένων. Όταν τελειώσει αυτή η * συνάρτηση το αντικείμενο δεν θα περιέχει καμία εγγραφή. */ public void run() { // Αποθήκευση των αποτελεσμάτων στη βάση if(Config.get().getProperty("simulationMode", "1").equals("0")) { ArrayList<Registration> tempReg = new ArrayList<Registration>(registrations); registrations = new ArrayList<Registration>(); Config.get().getDataHandler().updateRegistrations(tempReg); } else { System.out.println("Simulation mode is active. No database changes."); } registrationUpdaterThreads.remove(Thread.currentThread().getId()); // Remove the thread after its finished } /** * Δηλώνει ένα αντικείμενο StatisticsCollector ώστε να του στέλονται * στατιστικά για κάθε επιτυχημένη/αποτυχημένη εγγραφή. * @param statisticsCollector Το αντικείμενο που θα συλλέγει τα στατιστικά. */ public void setStatisticsCollector(StatisticsCollector statisticsCollector) { this.statisticsCollector = statisticsCollector; } /** * Επιστρέφει το αντικείμενο StatisticsCollector που έχει δηλωθεί για να * συλλέγει στατιστικά. * @return Το αντικείμενο που έχει δηλωθεί για να συλλέγει στατιστικά. */ public StatisticsCollector getStatisticsCollector() { return this.statisticsCollector; } }
67_4
import java.util.*; /** * @author Δημήτριος Παντελεήμων Γιακάτος * @version 1.0.0 * Η κλάση βρίσκει και αποθηκεύει σε αρχείο το συντομότερο μονοπάτι που ενώνει όλα τα μυρμήγκια. Προκειμένου να βρει * αυτό το μονοπάτι χρησιμοποιεί τον αλγόριθμο Kruskal Union-find. */ public class KruskalUnionFind { private TreeMap<Integer, ArrayList<Number>> data; private ArrayList<Ant> partArrayList = new ArrayList<>(); private int[] parent; private HashMap<Integer, ArrayList<Integer>> kuf = new HashMap<>(); private double totalKuf = 0; /** * Η μέθοδος είναι ο constructor της κλάσης, που καλεί κάποιες από τις μεθόδους της κλάσεις ώστε να παράγει το * ζητούμενο αποτέλεσμα για την άσκηση. * @param data Το Tree Map που έχει αποθηκευμένα τα δεδομένα του αρχείου. * @throws Exception Σε περίπτωση που δεν θα βρεθεί το αρχείο ή δεν θα μπορέσει να το ανοίξει τότε εκτυπώνει το κατάλληλο * exception ώστε να μην κωλύσει το πρόγραμμα. */ public KruskalUnionFind(TreeMap<Integer, ArrayList<Number>> data) throws Exception { this.data = data; setPartArrayList(); kruskal(); print(); } /** * Η μέθοδος υπολογίζει την ευκλείδεια απόσταση μεταξύ δύο μυρμηγκιών και αποθηκεύει τα δύο μυρμήγκια και την * απόσταση τους στη δομή partArrayList. */ private void setPartArrayList() { for (Integer ver : data.keySet()) { for (Map.Entry<Integer, ArrayList<Number>> edg : data.tailMap(ver).entrySet()) { partArrayList.add(new Ant().setDataForKUF(ver, data.get(ver).get(0).doubleValue(), data.get(ver).get(1).doubleValue(), edg.getKey(), data.get(edg.getKey()).get(0).doubleValue(), data.get(edg.getKey()).get(1).doubleValue()) ); } } } /** * Η μέθοδος υλοποιεί τον αλγόριθμο Kruskal Union-find ώστε να υπολογίσει το ελάχιστο μονοπάτι. Αρχικά αποθηκεύει * σε μία ουρά προτεραιότητας τα ζεύγη των μυρμηγκιών με βάση την απόσταση τους, δηλαδή πρώτο στην ουρά θα είναι τα * δύο μυρμήγκια που έχουν την μικρότερη απόσταση. Επίσης θα σχηματιστεί και ο πίνακας parent, ο οποίος θα έχει ως * κλειδί τα id όλων των μυρμηγκιών και ως τιμή θα έχουν τα μυρμήγκια με τα οποία θα συνεχιστεί το μονοπάτι. Για * παράδειγμα από το μυρμήγκι 1 (κλειδί) θα πάμε στο μυρμήγκι 2 (τιμή), άρα parent[1]=2. Τα μυρμήγκια που ακόμα δεν * έχουν εξεταστεί θα έχουν ως τιμή τον εαυτό τους, δηλαδή parent[id]=id. */ private void kruskal() { PriorityQueue<Ant> priorityQueue = new PriorityQueue<>(partArrayList.size()); parent = new int[partArrayList.size()]; for (Ant ant : partArrayList) { priorityQueue.add(ant); parent[ant.vertical-1] = ant.vertical-1; } int eCounter = 0; Integer ver1; Integer ver2; while (eCounter < data.size()-1) { Ant ant = priorityQueue.remove(); ver1 = findPath(ant.vertical-1); ver2 = findPath(ant.edge-1); if (!ver1.equals(ver2)) { if (ant.vertical-1 <= ant.edge-1) { kuf.computeIfAbsent(ant.vertical, o -> new ArrayList<>()).add(ant.edge); } else { kuf.computeIfAbsent(ant.edge, o -> new ArrayList<>()).add(ant.vertical); } eCounter++; parent[findPath(ver1)] = findPath(ver2); totalKuf = totalKuf + ant.distance; } } } /** * Η μέθοδος βρίσκει και επιστρέφει το id του μυρμηγκιού που δεν έχει κάποιο μονοπάτι, δηλαδή από αυτό το id δεν * μπορούμε να πάμε σε κάποιο άλλο id (γυρνάει στον εαυτό του). * @param i Το id του μυρμηγκιού. * @return Το id του μυρμηγκιού που μπορεί να πάει, δηλαδή να συνεχίσει το μονοπάτι. */ private Integer findPath(Integer i) { if (parent[i] == i) { return i; } return findPath(parent[i]); } /** * Η μέθοδος εκτυπώνει στο αρχείο τα δεδομένα της δομής Hash Map (kuf), δηλαδή τα ζεύγη των μυρμηγκιών και το * συνολικό βάρος του ελάχιστου μονοπατιού. * @throws Exception Σε περίπτωση που δεν θα βρεθεί το αρχείο ή δεν θα μπορέσει να το ανοίξει τότε εκτυπώνει το κατάλληλο * exception ώστε να μην κωλύσει το πρόγραμμα. */ private void print() throws Exception { FileManager fileManager = new FileManager(); fileManager.output("A.txt", String.valueOf(totalKuf)+"\r\n"); for (Integer key : kuf.keySet()) { Collections.sort(kuf.get(key)); for (int i=0; i<kuf.get(key).size(); i++) { fileManager.output("A.txt", key + " " + kuf.get(key).get(i) + "\r\n"); } } } }
dpgiakatos/AntsProject
KruskalUnionFind.java
2,334
/** * Η μέθοδος βρίσκει και επιστρέφει το id του μυρμηγκιού που δεν έχει κάποιο μονοπάτι, δηλαδή από αυτό το id δεν * μπορούμε να πάμε σε κάποιο άλλο id (γυρνάει στον εαυτό του). * @param i Το id του μυρμηγκιού. * @return Το id του μυρμηγκιού που μπορεί να πάει, δηλαδή να συνεχίσει το μονοπάτι. */
block_comment
el
import java.util.*; /** * @author Δημήτριος Παντελεήμων Γιακάτος * @version 1.0.0 * Η κλάση βρίσκει και αποθηκεύει σε αρχείο το συντομότερο μονοπάτι που ενώνει όλα τα μυρμήγκια. Προκειμένου να βρει * αυτό το μονοπάτι χρησιμοποιεί τον αλγόριθμο Kruskal Union-find. */ public class KruskalUnionFind { private TreeMap<Integer, ArrayList<Number>> data; private ArrayList<Ant> partArrayList = new ArrayList<>(); private int[] parent; private HashMap<Integer, ArrayList<Integer>> kuf = new HashMap<>(); private double totalKuf = 0; /** * Η μέθοδος είναι ο constructor της κλάσης, που καλεί κάποιες από τις μεθόδους της κλάσεις ώστε να παράγει το * ζητούμενο αποτέλεσμα για την άσκηση. * @param data Το Tree Map που έχει αποθηκευμένα τα δεδομένα του αρχείου. * @throws Exception Σε περίπτωση που δεν θα βρεθεί το αρχείο ή δεν θα μπορέσει να το ανοίξει τότε εκτυπώνει το κατάλληλο * exception ώστε να μην κωλύσει το πρόγραμμα. */ public KruskalUnionFind(TreeMap<Integer, ArrayList<Number>> data) throws Exception { this.data = data; setPartArrayList(); kruskal(); print(); } /** * Η μέθοδος υπολογίζει την ευκλείδεια απόσταση μεταξύ δύο μυρμηγκιών και αποθηκεύει τα δύο μυρμήγκια και την * απόσταση τους στη δομή partArrayList. */ private void setPartArrayList() { for (Integer ver : data.keySet()) { for (Map.Entry<Integer, ArrayList<Number>> edg : data.tailMap(ver).entrySet()) { partArrayList.add(new Ant().setDataForKUF(ver, data.get(ver).get(0).doubleValue(), data.get(ver).get(1).doubleValue(), edg.getKey(), data.get(edg.getKey()).get(0).doubleValue(), data.get(edg.getKey()).get(1).doubleValue()) ); } } } /** * Η μέθοδος υλοποιεί τον αλγόριθμο Kruskal Union-find ώστε να υπολογίσει το ελάχιστο μονοπάτι. Αρχικά αποθηκεύει * σε μία ουρά προτεραιότητας τα ζεύγη των μυρμηγκιών με βάση την απόσταση τους, δηλαδή πρώτο στην ουρά θα είναι τα * δύο μυρμήγκια που έχουν την μικρότερη απόσταση. Επίσης θα σχηματιστεί και ο πίνακας parent, ο οποίος θα έχει ως * κλειδί τα id όλων των μυρμηγκιών και ως τιμή θα έχουν τα μυρμήγκια με τα οποία θα συνεχιστεί το μονοπάτι. Για * παράδειγμα από το μυρμήγκι 1 (κλειδί) θα πάμε στο μυρμήγκι 2 (τιμή), άρα parent[1]=2. Τα μυρμήγκια που ακόμα δεν * έχουν εξεταστεί θα έχουν ως τιμή τον εαυτό τους, δηλαδή parent[id]=id. */ private void kruskal() { PriorityQueue<Ant> priorityQueue = new PriorityQueue<>(partArrayList.size()); parent = new int[partArrayList.size()]; for (Ant ant : partArrayList) { priorityQueue.add(ant); parent[ant.vertical-1] = ant.vertical-1; } int eCounter = 0; Integer ver1; Integer ver2; while (eCounter < data.size()-1) { Ant ant = priorityQueue.remove(); ver1 = findPath(ant.vertical-1); ver2 = findPath(ant.edge-1); if (!ver1.equals(ver2)) { if (ant.vertical-1 <= ant.edge-1) { kuf.computeIfAbsent(ant.vertical, o -> new ArrayList<>()).add(ant.edge); } else { kuf.computeIfAbsent(ant.edge, o -> new ArrayList<>()).add(ant.vertical); } eCounter++; parent[findPath(ver1)] = findPath(ver2); totalKuf = totalKuf + ant.distance; } } } /** * Η μέθοδος βρίσκει<SUF>*/ private Integer findPath(Integer i) { if (parent[i] == i) { return i; } return findPath(parent[i]); } /** * Η μέθοδος εκτυπώνει στο αρχείο τα δεδομένα της δομής Hash Map (kuf), δηλαδή τα ζεύγη των μυρμηγκιών και το * συνολικό βάρος του ελάχιστου μονοπατιού. * @throws Exception Σε περίπτωση που δεν θα βρεθεί το αρχείο ή δεν θα μπορέσει να το ανοίξει τότε εκτυπώνει το κατάλληλο * exception ώστε να μην κωλύσει το πρόγραμμα. */ private void print() throws Exception { FileManager fileManager = new FileManager(); fileManager.output("A.txt", String.valueOf(totalKuf)+"\r\n"); for (Integer key : kuf.keySet()) { Collections.sort(kuf.get(key)); for (int i=0; i<kuf.get(key).size(); i++) { fileManager.output("A.txt", key + " " + kuf.get(key).get(i) + "\r\n"); } } } }
1054_3
import java.util.concurrent.ThreadLocalRandom; /** * Η κλάση υλοποιεί το κανάλι θορύβου. * * @author Δημήτριος Παντελεήμων Γιακάτος * @version 1.0.0 */ public class BitErrorRate { private double possibility; private String data; /** * Η μέθοδος είναι ο constructor. */ public BitErrorRate() {} /** * H μέθοδος αποθηκεύει το μήνυμα T στη μεταβλητή data. * @param data Μία συμβολοσειρά που περιλαμβάνει το μήνυμα T. */ public void setData(String data) {this.data = data;} /** * Η μέθοδος αποθηκεύει τη πιθανότητα σφάλματος στη μεταβλητή possibility. * @param possibility Η πιθανότητα σφάλματος. */ public void setPossibility(double possibility) {this.possibility = possibility;} /** * Η μέθοδος είναι ο εκκινητής της διαδικασίας για το κανάλι θορύβου. * @return Επιστρέφει το μήνυμα T το οποίο πιθανό να έχει αλλοιωθεί από το κανάλι θορύβου. */ public String start() { generateBitErrorRate(); return data; } /** * Η μέθοδος ανάλογα με την πιθανότητα σφάλματος που έχει δώσει ο χρήστης αλλοιώνει κάθε bit του μηνύματος T που * είναι στη μεταβλητή data. Με λίγα λόγια η κλάση δημιουργεί για κάθε ένα bit του T ένα αριθμό από το 0.0 μέχρι * και το 1.0 και αν αυτός ο αριθμός είναι μικρότερος ή ίσος με τη πιθανότητα σφάλματος τότε αλλάζει το bit του * μηνύματος από 0 σε 1 και από 1 σε 0. */ private void generateBitErrorRate() { double randomError; for (int i=0; i<data.length(); i++) { randomError = ThreadLocalRandom.current().nextDouble(0.0, 1.0); if (possibility>=randomError) { if (data.charAt(i)=='0') { data = data.substring(0, i) + "1" + data.substring(i+1); } else { data = data.substring(0, i) + "0" + data.substring(i+1); } } } } }
dpgiakatos/CRC
src/BitErrorRate.java
962
/** * Η μέθοδος αποθηκεύει τη πιθανότητα σφάλματος στη μεταβλητή possibility. * @param possibility Η πιθανότητα σφάλματος. */
block_comment
el
import java.util.concurrent.ThreadLocalRandom; /** * Η κλάση υλοποιεί το κανάλι θορύβου. * * @author Δημήτριος Παντελεήμων Γιακάτος * @version 1.0.0 */ public class BitErrorRate { private double possibility; private String data; /** * Η μέθοδος είναι ο constructor. */ public BitErrorRate() {} /** * H μέθοδος αποθηκεύει το μήνυμα T στη μεταβλητή data. * @param data Μία συμβολοσειρά που περιλαμβάνει το μήνυμα T. */ public void setData(String data) {this.data = data;} /** * Η μέθοδος αποθηκεύει<SUF>*/ public void setPossibility(double possibility) {this.possibility = possibility;} /** * Η μέθοδος είναι ο εκκινητής της διαδικασίας για το κανάλι θορύβου. * @return Επιστρέφει το μήνυμα T το οποίο πιθανό να έχει αλλοιωθεί από το κανάλι θορύβου. */ public String start() { generateBitErrorRate(); return data; } /** * Η μέθοδος ανάλογα με την πιθανότητα σφάλματος που έχει δώσει ο χρήστης αλλοιώνει κάθε bit του μηνύματος T που * είναι στη μεταβλητή data. Με λίγα λόγια η κλάση δημιουργεί για κάθε ένα bit του T ένα αριθμό από το 0.0 μέχρι * και το 1.0 και αν αυτός ο αριθμός είναι μικρότερος ή ίσος με τη πιθανότητα σφάλματος τότε αλλάζει το bit του * μηνύματος από 0 σε 1 και από 1 σε 0. */ private void generateBitErrorRate() { double randomError; for (int i=0; i<data.length(); i++) { randomError = ThreadLocalRandom.current().nextDouble(0.0, 1.0); if (possibility>=randomError) { if (data.charAt(i)=='0') { data = data.substring(0, i) + "1" + data.substring(i+1); } else { data = data.substring(0, i) + "0" + data.substring(i+1); } } } } }
5859_0
package i18n; import java.util.ListResourceBundle; /** * Η κλάση περιέχει το περιεχόμενο των κειμένων στα ελληνικά. * * @author Δημήτριος Παντελεήμων Γιακάτος * @version 1.0.0 */ public class MessageListBundle_el_GR extends ListResourceBundle{ @Override protected Object[][] getContents() { return contents; } private Object[][] contents = { {"frameTitle", "Παιχνίδι μνήμης"}, {"homePanelTitle", "Παιχνίδι μνήμης"}, {"homePanelStartB", "Έναρξη"}, {"homePanelScoreB", "Βαθμολογία"}, {"homePanelAboutB", "Πιστώσεις"}, {"homePanelHelpB", "Βοήθεια"}, {"homePanelExitB", "Έξοδος"}, {"homePanelChangeLanguage", "Αλλαγή γλώσσας:"}, {"aboutPanelTitle", "Σχετικά με το παιχνίδι"}, {"aboutPanelText", "Πρόκειται για ένα έργο που δημιούργησε ο Δημήτρης και ο Θέμης."}, {"aboutPanelBackB", "Πίσω"}, {"helpPanelTitle", "Βοήθεια"}, {"helpPanelText", "Πατήστε το κουμπί Έναρξη για να ξεκινήσετε το παιχνίδι."}, {"helpPanelBackB", "Πίσω"}, {"scorePanelTitle", "Επιλέξτε ποιο βαθμολογία θέλετε να δείτε:"}, {"genericBackButton", "Πίσω"}, {"cpuMode1", "Ένας παίκτης"}, {"cpuMode2", "Χρυσόψαρο"}, {"cpuMode3", "Καγκουρό"}, {"cpuMode4", "Ελέφαντας"}, {"difficultyPanelTitle", "Επιλέξτε Δυσκολία"}, {"difficultyPanelPlayers", "Επιλέξτε Παίκτες:"}, {"difficultyPanelSubTitle1", "Παίχτης"}, {"difficultyPanelSubTitle2", "Υπολογιστής"}, {"difficultyPanelCTitle", "Μονομαχία:"}, {"difficultyPanelCOn", "Ενεργοποιημένο"}, {"difficultyPanelCOff", "Απενεργοποιημένο"}, {"difficultyPanelGM", "Λειτουργία παιχνιδιού"}, {"difficultyPanelDM", "Έναρξη μονομαχίας"}, {"difficultyPanelGM1", "2 αντίγραφα των 12 διαφορετικών καρτών"}, {"difficultyPanelGM2", "2 αντίγραφα των 24 διαφορετικών καρτών"}, {"difficultyPanelGM3", "3 αντίγραφα των 12 διαφορετικών καρτών"}, {"scorePanelS0", "Σειρά"}, {"scorePanelS1", "Ονόματα"}, {"scorePanelS2", "Καλύτερα Βήματα"}, {"scorePanelM0", "Σειρά"}, {"scorePanelM1", "Ονόματα"}, {"scorePanelM2", "Νίκες"}, {"gamePanelCP", "Παίζει τώρα:"}, {"gamePanelCPDB", "Παίζει τώρα στο μπλε τραπέζι ο/η:"}, {"gamePanelCPDR", "Παίζει τώρα στο κόκκινο τραπέζι ο/η:"}, {"gamePanelSt", "Βήματα"}, {"gamePanelSc", "Βαθμολογία"}, {"gamePanelWinS", "Το παιχνίδι τελείωσε!"}, {"gamePanelWinD", "Το παιχνίδι είναι ισοπαλία!"}, {"gamePanelWinM", "Ο/Η νικητής/τρια είναι ο/η"}, {"scorePanelSB0", "Ατομική -> 2 αντίγραφα των 12 διαφορετικών καρτών"}, {"scorePanelSB1", "Ατομική -> 2 αντίγραφα των 24 διαφορετικών καρτών"}, {"scorePanelSB2", "Ατομική -> 3 αντίγραφα των 12 διαφορετικών καρτών"}, {"scorePanelSB3", "Πολλαπλών παικτών -> 2 αντίγραφα των 12 διαφορετικών καρτών"}, {"scorePanelSB4", "Πολλαπλών παικτών -> 2 αντίγραφα των 24 διαφορετικών καρτών"}, {"scorePanelSB5", "Πολλαπλών παικτών -> 3 αντίγραφα των 12 διαφορετικών καρτών"}, {"scorePanelSB6", "Μονομαχία"} }; }
dpgiakatos/MemoryGame
i18n/MessageListBundle_el_GR.java
1,739
/** * Η κλάση περιέχει το περιεχόμενο των κειμένων στα ελληνικά. * * @author Δημήτριος Παντελεήμων Γιακάτος * @version 1.0.0 */
block_comment
el
package i18n; import java.util.ListResourceBundle; /** * Η κλάση περιέχει<SUF>*/ public class MessageListBundle_el_GR extends ListResourceBundle{ @Override protected Object[][] getContents() { return contents; } private Object[][] contents = { {"frameTitle", "Παιχνίδι μνήμης"}, {"homePanelTitle", "Παιχνίδι μνήμης"}, {"homePanelStartB", "Έναρξη"}, {"homePanelScoreB", "Βαθμολογία"}, {"homePanelAboutB", "Πιστώσεις"}, {"homePanelHelpB", "Βοήθεια"}, {"homePanelExitB", "Έξοδος"}, {"homePanelChangeLanguage", "Αλλαγή γλώσσας:"}, {"aboutPanelTitle", "Σχετικά με το παιχνίδι"}, {"aboutPanelText", "Πρόκειται για ένα έργο που δημιούργησε ο Δημήτρης και ο Θέμης."}, {"aboutPanelBackB", "Πίσω"}, {"helpPanelTitle", "Βοήθεια"}, {"helpPanelText", "Πατήστε το κουμπί Έναρξη για να ξεκινήσετε το παιχνίδι."}, {"helpPanelBackB", "Πίσω"}, {"scorePanelTitle", "Επιλέξτε ποιο βαθμολογία θέλετε να δείτε:"}, {"genericBackButton", "Πίσω"}, {"cpuMode1", "Ένας παίκτης"}, {"cpuMode2", "Χρυσόψαρο"}, {"cpuMode3", "Καγκουρό"}, {"cpuMode4", "Ελέφαντας"}, {"difficultyPanelTitle", "Επιλέξτε Δυσκολία"}, {"difficultyPanelPlayers", "Επιλέξτε Παίκτες:"}, {"difficultyPanelSubTitle1", "Παίχτης"}, {"difficultyPanelSubTitle2", "Υπολογιστής"}, {"difficultyPanelCTitle", "Μονομαχία:"}, {"difficultyPanelCOn", "Ενεργοποιημένο"}, {"difficultyPanelCOff", "Απενεργοποιημένο"}, {"difficultyPanelGM", "Λειτουργία παιχνιδιού"}, {"difficultyPanelDM", "Έναρξη μονομαχίας"}, {"difficultyPanelGM1", "2 αντίγραφα των 12 διαφορετικών καρτών"}, {"difficultyPanelGM2", "2 αντίγραφα των 24 διαφορετικών καρτών"}, {"difficultyPanelGM3", "3 αντίγραφα των 12 διαφορετικών καρτών"}, {"scorePanelS0", "Σειρά"}, {"scorePanelS1", "Ονόματα"}, {"scorePanelS2", "Καλύτερα Βήματα"}, {"scorePanelM0", "Σειρά"}, {"scorePanelM1", "Ονόματα"}, {"scorePanelM2", "Νίκες"}, {"gamePanelCP", "Παίζει τώρα:"}, {"gamePanelCPDB", "Παίζει τώρα στο μπλε τραπέζι ο/η:"}, {"gamePanelCPDR", "Παίζει τώρα στο κόκκινο τραπέζι ο/η:"}, {"gamePanelSt", "Βήματα"}, {"gamePanelSc", "Βαθμολογία"}, {"gamePanelWinS", "Το παιχνίδι τελείωσε!"}, {"gamePanelWinD", "Το παιχνίδι είναι ισοπαλία!"}, {"gamePanelWinM", "Ο/Η νικητής/τρια είναι ο/η"}, {"scorePanelSB0", "Ατομική -> 2 αντίγραφα των 12 διαφορετικών καρτών"}, {"scorePanelSB1", "Ατομική -> 2 αντίγραφα των 24 διαφορετικών καρτών"}, {"scorePanelSB2", "Ατομική -> 3 αντίγραφα των 12 διαφορετικών καρτών"}, {"scorePanelSB3", "Πολλαπλών παικτών -> 2 αντίγραφα των 12 διαφορετικών καρτών"}, {"scorePanelSB4", "Πολλαπλών παικτών -> 2 αντίγραφα των 24 διαφορετικών καρτών"}, {"scorePanelSB5", "Πολλαπλών παικτών -> 3 αντίγραφα των 12 διαφορετικών καρτών"}, {"scorePanelSB6", "Μονομαχία"} }; }
5028_2
/** * @author Δημήτριος Παντελεήμων Γιακάτος * Η κλάση περιλαμβάνει τη δομή ενός μηνύματος. */ public class Email { private boolean isNew; private String sender; private String receiver; private String subject; private String mainBody; /** * Ο constructor αρχικοποεί τις μεταβλητές της κλάσης. Οι μεταβλητές τύπου String παίρνουν τιμή null και η μεταβλητή * τύπου boolean παίρνει τιμή false. */ Email() { this.isNew = false; this.sender = null; this.receiver = null; this.subject = null; this.mainBody = null; } /** * Ο constructor ορίζει τις μεταβλητές της κλάσης. * @param isNew Υποδεικνύει αν το μήνυμα έχει ήδη διαβαστεί. true, αν είναι καινούργιο μήνυμα. false, αν δεν * είναι καινούργιο το μήνυμα. * @param sender Ο αποστολέας του μηνύματος. * @param receiver Ο παραλήπτης του μηνύματος. * @param subject Το θέμα του μηνύματος. * @param mainBody Το κείμενο του μηνύματος. */ Email(boolean isNew, String sender, String receiver, String subject, String mainBody) { this.isNew = isNew; this.sender = sender; this.receiver = receiver; this.subject = subject; this.mainBody = mainBody; } /** * @param isNew Υποδεικνύει αν το μήνυμα έχει ήδη διαβαστεί. true, αν είναι καινούργιο μήνυμα. false, αν δεν * είναι καινούργιο το μήνυμα. */ void setIsNew(boolean isNew) { this.isNew = isNew; } /** * @return Επιστρέφει αν το μήνυμα έχει ήδη διαβαστεί. */ boolean getIsNew() { return isNew; } /** * @param sender Ο αποστολέας του μηνύματος. */ void setSender(String sender) { this.sender = sender; } /** * @return Επιστρέφει τον αποστολέα του μηνύματος. */ String getSender() { return sender; } /** * @param receiver Ο παραλήπτης του μηνύματος. */ void setReceiver(String receiver) { this.receiver = receiver; } /** * @return Επιστρέφει τον παραλήπτη του μηνύματος. */ String getReceiver() { return receiver; } /** * @param subject Το θέμα του μηνύματος. */ void setSubject(String subject) { this.subject = subject; } /** * @return Επιστρέφει το θέμα του μηνύματος. */ String getSubject() { return subject; } /** * @param mainBody Το κείμενο του μηνύματος. */ void setMainBody(String mainBody) { this.mainBody = mainBody; } /** * @return Επιστρέφει το κείμενο του μηνύματος. */ String getMainBody() { return mainBody; } }
dpgiakatos/email2019
MailServer/Email.java
1,188
/** * Ο constructor ορίζει τις μεταβλητές της κλάσης. * @param isNew Υποδεικνύει αν το μήνυμα έχει ήδη διαβαστεί. true, αν είναι καινούργιο μήνυμα. false, αν δεν * είναι καινούργιο το μήνυμα. * @param sender Ο αποστολέας του μηνύματος. * @param receiver Ο παραλήπτης του μηνύματος. * @param subject Το θέμα του μηνύματος. * @param mainBody Το κείμενο του μηνύματος. */
block_comment
el
/** * @author Δημήτριος Παντελεήμων Γιακάτος * Η κλάση περιλαμβάνει τη δομή ενός μηνύματος. */ public class Email { private boolean isNew; private String sender; private String receiver; private String subject; private String mainBody; /** * Ο constructor αρχικοποεί τις μεταβλητές της κλάσης. Οι μεταβλητές τύπου String παίρνουν τιμή null και η μεταβλητή * τύπου boolean παίρνει τιμή false. */ Email() { this.isNew = false; this.sender = null; this.receiver = null; this.subject = null; this.mainBody = null; } /** * Ο constructor ορίζει<SUF>*/ Email(boolean isNew, String sender, String receiver, String subject, String mainBody) { this.isNew = isNew; this.sender = sender; this.receiver = receiver; this.subject = subject; this.mainBody = mainBody; } /** * @param isNew Υποδεικνύει αν το μήνυμα έχει ήδη διαβαστεί. true, αν είναι καινούργιο μήνυμα. false, αν δεν * είναι καινούργιο το μήνυμα. */ void setIsNew(boolean isNew) { this.isNew = isNew; } /** * @return Επιστρέφει αν το μήνυμα έχει ήδη διαβαστεί. */ boolean getIsNew() { return isNew; } /** * @param sender Ο αποστολέας του μηνύματος. */ void setSender(String sender) { this.sender = sender; } /** * @return Επιστρέφει τον αποστολέα του μηνύματος. */ String getSender() { return sender; } /** * @param receiver Ο παραλήπτης του μηνύματος. */ void setReceiver(String receiver) { this.receiver = receiver; } /** * @return Επιστρέφει τον παραλήπτη του μηνύματος. */ String getReceiver() { return receiver; } /** * @param subject Το θέμα του μηνύματος. */ void setSubject(String subject) { this.subject = subject; } /** * @return Επιστρέφει το θέμα του μηνύματος. */ String getSubject() { return subject; } /** * @param mainBody Το κείμενο του μηνύματος. */ void setMainBody(String mainBody) { this.mainBody = mainBody; } /** * @return Επιστρέφει το κείμενο του μηνύματος. */ String getMainBody() { return mainBody; } }
339_6
package ai.engine; import ai.engine.schema.JDomSchema; import d.log.Log; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.SystemMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.context.annotation.SessionScope; import java.util.List; @Service public class AiService { @Autowired private ChatClient chatClient; public AiService () { } // @Autowired // @SessionScope // public void setChatClient(ChatClient chatClient) { // this.chatClient = chatClient; // //Log.log ("setChatClient", chatClient.getClass().getName()); // } // public ChatClient getChatClient() { // return this.chatClient; // } public String call (String text) { return chatClient.call(text); } public String call(Prompt prompt) { return chatClient.call(prompt).getResult().getOutput().getContent(); } public String call (String docText, String question) { // String message = "Πάρε υπ' όψη σου το έγγραφο: {docText}\n"; // message += "Ερώτηση: {question}\n"; // message += "Λάβε υπ' όψη σου ότι είμαι δικηγόρος\n"; // message += "Αν δε ξέρεις την απάντηση, απλά πες 'Δεν ξέρω'\n"; // PromptTemplate promptTemplate = new PromptTemplate(message); // Prompt prompt = promptTemplate.create(Map.of("docText", docText, // "question", question)); //List<Document> similarDocuments = new VectorStoreRetriever(vectorStore).retrieve(question, 5); SystemMessage systemMessage = getSystemMessage(docText); //similarDocuments UserMessage userMessage = new UserMessage(question); Prompt prompt = new Prompt (List.of(systemMessage, userMessage)); ChatResponse response = chatClient.call(prompt); String answer = response.getResult().getOutput().getContent(); Log.log ("----------answer--------\n", answer); return answer; } private SystemMessage getSystemMessage(String docText) { //List<Document> similarDocuments String systemS = "Διάβασε το έγγραφο: \n" + docText + "\n"; systemS += "[ΤΕΛΟΣ ΕΓΓΡΑΦΟΥ]\n"; systemS += "Να γνωρίζεις ότι είμαι ο συμβολαιογράφος του εγγράφου που σου δίνω\n"; systemS += "Είσαι συμβολαιογράφος βοηθός μου και πολύ προσεκτικός με τα έγγραφα\n"; systemS += "Αν δε ξέρεις την απάντηση, απλά πες 'Δεν ξέρω'\n"; SystemMessage systemMessage = new SystemMessage(systemS); return systemMessage; } public JDomSchema getJDomSchema (JDomSchema schema, String prompt) { return schema; } } //BeanOutputParser<TopSong> parser = new BeanOutputParser<TopSong>(TopSong.class); //parser.getFormat(); //PromptTemplate template = new PromptTemplate(str); //template.setOutputParser(parser); //String text = template.render(); //TopSong ts = parser.parse(text);
drakator/ais
src/main/java/ai/engine/AiService.java
1,016
// message += "Λάβε υπ' όψη σου ότι είμαι δικηγόρος\n";
line_comment
el
package ai.engine; import ai.engine.schema.JDomSchema; import d.log.Log; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.SystemMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.context.annotation.SessionScope; import java.util.List; @Service public class AiService { @Autowired private ChatClient chatClient; public AiService () { } // @Autowired // @SessionScope // public void setChatClient(ChatClient chatClient) { // this.chatClient = chatClient; // //Log.log ("setChatClient", chatClient.getClass().getName()); // } // public ChatClient getChatClient() { // return this.chatClient; // } public String call (String text) { return chatClient.call(text); } public String call(Prompt prompt) { return chatClient.call(prompt).getResult().getOutput().getContent(); } public String call (String docText, String question) { // String message = "Πάρε υπ' όψη σου το έγγραφο: {docText}\n"; // message += "Ερώτηση: {question}\n"; // message +=<SUF> // message += "Αν δε ξέρεις την απάντηση, απλά πες 'Δεν ξέρω'\n"; // PromptTemplate promptTemplate = new PromptTemplate(message); // Prompt prompt = promptTemplate.create(Map.of("docText", docText, // "question", question)); //List<Document> similarDocuments = new VectorStoreRetriever(vectorStore).retrieve(question, 5); SystemMessage systemMessage = getSystemMessage(docText); //similarDocuments UserMessage userMessage = new UserMessage(question); Prompt prompt = new Prompt (List.of(systemMessage, userMessage)); ChatResponse response = chatClient.call(prompt); String answer = response.getResult().getOutput().getContent(); Log.log ("----------answer--------\n", answer); return answer; } private SystemMessage getSystemMessage(String docText) { //List<Document> similarDocuments String systemS = "Διάβασε το έγγραφο: \n" + docText + "\n"; systemS += "[ΤΕΛΟΣ ΕΓΓΡΑΦΟΥ]\n"; systemS += "Να γνωρίζεις ότι είμαι ο συμβολαιογράφος του εγγράφου που σου δίνω\n"; systemS += "Είσαι συμβολαιογράφος βοηθός μου και πολύ προσεκτικός με τα έγγραφα\n"; systemS += "Αν δε ξέρεις την απάντηση, απλά πες 'Δεν ξέρω'\n"; SystemMessage systemMessage = new SystemMessage(systemS); return systemMessage; } public JDomSchema getJDomSchema (JDomSchema schema, String prompt) { return schema; } } //BeanOutputParser<TopSong> parser = new BeanOutputParser<TopSong>(TopSong.class); //parser.getFormat(); //PromptTemplate template = new PromptTemplate(str); //template.setOutputParser(parser); //String text = template.render(); //TopSong ts = parser.parse(text);
6932_0
package social; import java.util.Vector; public class User { String name; String date; String mail; Vector<User> friends; public User(String name, String date, String mail) { this.name = name; this.date = date; this.mail = mail; friends = new Vector<User>(); } public Vector<User> getFriends() { return friends; } public String getName() { return name; } public String getDate() { return date; } public String getMail() { return mail; } public void setName(User u) { this.name = u.name; } public void setDate(User u) { this.date = u.date; } public void setEMail(User u) { this.mail = u.mail; } @Override public String toString() { return name; } public void addFriend(User u) { if ((!friends.contains(u)) && (this != u)) { //***Συμμετρική σχέση φίλων!***// u.request(this); this.request(u); } } public void removeFriend(User u) { u.dlt(this); this.dlt(u); } public void request(User w) { friends.add(w); } public void dlt(User w) { friends.remove(w); } }
dsimop/SoftwareDevelopmentFrameworks
1st Application/src/social/User.java
354
//***Συμμετρική σχέση φίλων!***//
line_comment
el
package social; import java.util.Vector; public class User { String name; String date; String mail; Vector<User> friends; public User(String name, String date, String mail) { this.name = name; this.date = date; this.mail = mail; friends = new Vector<User>(); } public Vector<User> getFriends() { return friends; } public String getName() { return name; } public String getDate() { return date; } public String getMail() { return mail; } public void setName(User u) { this.name = u.name; } public void setDate(User u) { this.date = u.date; } public void setEMail(User u) { this.mail = u.mail; } @Override public String toString() { return name; } public void addFriend(User u) { if ((!friends.contains(u)) && (this != u)) { //***Συμμετρική σχέση<SUF> u.request(this); this.request(u); } } public void removeFriend(User u) { u.dlt(this); this.dlt(u); } public void request(User w) { friends.add(w); } public void dlt(User w) { friends.remove(w); } }
44022_0
package com.example.e_med_help.controllers; import com.example.e_med_help.dtos.LoginUserDto; import com.example.e_med_help.dtos.NewUserDto; import com.example.e_med_help.models.Role; import com.example.e_med_help.models.User; import com.example.e_med_help.services.RolesServiceInterface; import com.example.e_med_help.services.UsersServiceInterface; import com.example.e_med_help.validators.LoginUserValidator; import com.example.e_med_help.validators.NewUserDtoValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import javax.validation.Valid; @RequestMapping("/") @Controller public class MainController { @Autowired RolesServiceInterface rolesServiceInterface; @Autowired UsersServiceInterface usersServiceInterface; @Autowired PasswordEncoder passwordEncoder; @Autowired NewUserDtoValidator newUserDtoValidator; @Autowired LoginUserValidator loginUserValidator; @GetMapping public String welcomePage() { return "index"; } @InitBinder("LoginUserDto")// Εδω θα βαλεις το object που θες να κανεις validate public void setupBinder1(WebDataBinder binder) { binder.addValidators(loginUserValidator); } @GetMapping(value = "/registerForm") public String registerForm(ModelMap mm) { NewUserDto newUser = new NewUserDto(); mm.addAttribute("roles", rolesServiceInterface.getAllRoles()); mm.addAttribute("newUser", newUser); return "addUser"; } @GetMapping(value = "/shoppingbasket") public String shoppingBasket() { return "shoppingbasket"; } @GetMapping(value = "/payment") public String payment() { return "payment"; } @GetMapping(value = "/contact") public String contact() { return "contact"; } @PostMapping(value = "/addUser") public String addUser(@Valid @ModelAttribute(name = "newUser") NewUserDto newUser, BindingResult br, ModelMap mm) { if (br.hasErrors()) { mm.addAttribute("roles", rolesServiceInterface.getAllRoles()); return "addUser"; } User temp = new User(); Role role = rolesServiceInterface.getById(newUser.getRole()); if (role != null) { temp.setURoleId(role); } else { return "error"; } temp.setUName(newUser.getName()); temp.setUSurname(newUser.getSurname()); temp.setULoginname(newUser.getUsername()); temp.setUPassword(passwordEncoder.encode(newUser.getPassword1())); usersServiceInterface.insertUser(temp); return "index"; } @GetMapping(value = "/loginForm") public String loginForm(ModelMap mm) { mm.addAttribute("LoginUserDto", new LoginUserDto()); return "login"; } @PostMapping(value = "/login") public String login(@Valid @ModelAttribute(name = "LoginUserDto") LoginUserDto user, BindingResult br, HttpSession session, ModelMap mm) { if (br.hasErrors()) { return "login"; } User current = usersServiceInterface.getUserByUsername(user.getLousername()); System.out.println(current); session.setAttribute("user", current); if (current.getURoleId().getRoleId() == 2) { return "redirect:physician/home"; } if (current.getURoleId().getRoleId() == 3) { return "redirect:pharmacist/home"; } if (current.getURoleId().getRoleId() == 1) { return "redirect:/patient/home"; } else return "login"; } @ResponseBody @PostMapping(value = "/checkUsername/{username}") public boolean checkUsername(@PathVariable(name = "username") String username) { User user = usersServiceInterface.getUserByUsername(username); return (user != null); } }
e-Med-Tech/e-med-help
src/main/java/com/example/e_med_help/controllers/MainController.java
1,052
// Εδω θα βαλεις το object που θες να κανεις validate
line_comment
el
package com.example.e_med_help.controllers; import com.example.e_med_help.dtos.LoginUserDto; import com.example.e_med_help.dtos.NewUserDto; import com.example.e_med_help.models.Role; import com.example.e_med_help.models.User; import com.example.e_med_help.services.RolesServiceInterface; import com.example.e_med_help.services.UsersServiceInterface; import com.example.e_med_help.validators.LoginUserValidator; import com.example.e_med_help.validators.NewUserDtoValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import javax.validation.Valid; @RequestMapping("/") @Controller public class MainController { @Autowired RolesServiceInterface rolesServiceInterface; @Autowired UsersServiceInterface usersServiceInterface; @Autowired PasswordEncoder passwordEncoder; @Autowired NewUserDtoValidator newUserDtoValidator; @Autowired LoginUserValidator loginUserValidator; @GetMapping public String welcomePage() { return "index"; } @InitBinder("LoginUserDto")// Εδω θα<SUF> public void setupBinder1(WebDataBinder binder) { binder.addValidators(loginUserValidator); } @GetMapping(value = "/registerForm") public String registerForm(ModelMap mm) { NewUserDto newUser = new NewUserDto(); mm.addAttribute("roles", rolesServiceInterface.getAllRoles()); mm.addAttribute("newUser", newUser); return "addUser"; } @GetMapping(value = "/shoppingbasket") public String shoppingBasket() { return "shoppingbasket"; } @GetMapping(value = "/payment") public String payment() { return "payment"; } @GetMapping(value = "/contact") public String contact() { return "contact"; } @PostMapping(value = "/addUser") public String addUser(@Valid @ModelAttribute(name = "newUser") NewUserDto newUser, BindingResult br, ModelMap mm) { if (br.hasErrors()) { mm.addAttribute("roles", rolesServiceInterface.getAllRoles()); return "addUser"; } User temp = new User(); Role role = rolesServiceInterface.getById(newUser.getRole()); if (role != null) { temp.setURoleId(role); } else { return "error"; } temp.setUName(newUser.getName()); temp.setUSurname(newUser.getSurname()); temp.setULoginname(newUser.getUsername()); temp.setUPassword(passwordEncoder.encode(newUser.getPassword1())); usersServiceInterface.insertUser(temp); return "index"; } @GetMapping(value = "/loginForm") public String loginForm(ModelMap mm) { mm.addAttribute("LoginUserDto", new LoginUserDto()); return "login"; } @PostMapping(value = "/login") public String login(@Valid @ModelAttribute(name = "LoginUserDto") LoginUserDto user, BindingResult br, HttpSession session, ModelMap mm) { if (br.hasErrors()) { return "login"; } User current = usersServiceInterface.getUserByUsername(user.getLousername()); System.out.println(current); session.setAttribute("user", current); if (current.getURoleId().getRoleId() == 2) { return "redirect:physician/home"; } if (current.getURoleId().getRoleId() == 3) { return "redirect:pharmacist/home"; } if (current.getURoleId().getRoleId() == 1) { return "redirect:/patient/home"; } else return "login"; } @ResponseBody @PostMapping(value = "/checkUsername/{username}") public boolean checkUsername(@PathVariable(name = "username") String username) { User user = usersServiceInterface.getUserByUsername(username); return (user != null); } }
3432_7
package com.panagiotiswarpro.panos.businessplan; import android.Manifest; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class BusinessCreationScreen extends AppCompatActivity { //public static String globalPreferences = "com." Button businessPlanButton,workersButton,proffesionalEquipmentButton,saveButton,proiontaButton; private File pdfFile; final private int REQUEST_CODE_ASK_PERMISSIONS = 111; boolean synopsiHasText=false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_business_creation_screen); businessPlanButton = (Button) findViewById(R.id.BusinessPlanButton); ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar2); workersButton = (Button) findViewById(R.id.WorkersButton); proffesionalEquipmentButton = (Button) findViewById(R.id.ProfessionalEquipmentButton); saveButton = (Button) findViewById(R.id.saveButton); proiontaButton = (Button) findViewById(R.id.ProiontaButton); EditText synopsi = (EditText) findViewById(R.id.synopsh); //make the progressbar bigger progressBar.setScaleY(3f); businessPlanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(BusinessCreationScreen.this,BusinessModel.class)); } }); proiontaButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(BusinessCreationScreen.this,ProiontaTab.class)); } }); workersButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(BusinessCreationScreen.this,Team.class)); } }); proffesionalEquipmentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(BusinessCreationScreen.this,Equipment.class)); } }); reloadPage(); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText synopsi = (EditText) findViewById(R.id.synopsh); if(synopsi.getText().toString().isEmpty()) { Toast.makeText(BusinessCreationScreen.this,"Δεν γράψατε σύνοψη",Toast.LENGTH_LONG).show(); } else{ try { createPdfWrapper(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } } } }); synopsi.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { SharedPreferences sharedPreferences = getSharedPreferences("synopsi", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("synopsiText",s.toString()); editor.apply(); ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar2); if(s.length() != 0) { if(!synopsiHasText) { progressBar.setProgress(progressBar.getProgress() + 1); synopsiHasText=true; } } else { progressBar.setProgress(progressBar.getProgress() - 1); synopsiHasText=false; } saveButton.setEnabled(progressBar.getProgress()==5); } }); } private void createPdfWrapper() throws FileNotFoundException,DocumentException{ int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) { showMessageOKCancel("You need to allow access to Storage", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS); } } }); return; } requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS); } return; }else { createPdf(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case REQUEST_CODE_ASK_PERMISSIONS: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission Granted try { createPdfWrapper(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } } else { // Permission Denied Toast.makeText(this, "WRITE_EXTERNAL Permission Denied", Toast.LENGTH_SHORT) .show(); } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(this) .setMessage(message) .setPositiveButton("OK", okListener) .setNegativeButton("Cancel", null) .create() .show(); } private void createPdf() throws FileNotFoundException, DocumentException { File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents"); if (!docsFolder.exists()) { docsFolder.mkdir(); } pdfFile = new File(docsFolder.getAbsolutePath(),"Plan.pdf"); OutputStream output = new FileOutputStream(pdfFile); Document document = new Document(); PdfWriter.getInstance(document, output); document.open(); try{ InputStream in = getResources().openRawResource(R.raw.arialbd); FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Documents/arialbd.ttf"); byte[] buff = new byte[1024]; int read = 0; try { while ((read = in.read(buff)) > 0) { out.write(buff, 0, read); } } finally { in.close(); out.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //itext needed a unicode font to support greek FontFactory.register(Environment.getExternalStorageDirectory() + "/Documents/arialbd.ttf","Greek-Regular"); Font f = FontFactory.getFont("Greek-Regular", BaseFont.IDENTITY_H, true); EditText synopsi = (EditText) findViewById(R.id.synopsh); f.setStyle("bold"); f.setSize(20); Paragraph centerSynopsi = new Paragraph("Σύνοψη\n\n",f); centerSynopsi.setAlignment(Element.ALIGN_CENTER); document.add(centerSynopsi); f.setSize(13); f.setStyle("normal"); document.add(new Paragraph(synopsi.getText().toString()+"\n\n",f)); f.setStyle("bold"); f.setSize(20); Paragraph centerModel = new Paragraph("Επιχειρηματικό Μοντέλο\n\n",f); centerModel.setAlignment(Element.ALIGN_CENTER); document.add(centerModel); f.setSize(16); document.add(new Paragraph("Ταυτότητα\n\n",f)); f.setSize(13); f.setStyle("normal"); SharedPreferences sharedPref = getSharedPreferences("businessModel", Context.MODE_PRIVATE); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Τόπος Εγκατάστασης: "+sharedPref.getString("ToposEgkastasis","")+ "\nΗμερομηνία Έναρξης: " + sharedPref.getString("DateEgkatastash","")+ "\nΜορφή Εταιρείας: "); switch(sharedPref.getInt("morfh", 0)) { case 1: stringBuilder.append("Ατομική Επιχείρηση"); break; case 2: stringBuilder.append("Συνεταιριστική Εταιρεία"); break; case 3: stringBuilder.append("Ανώνυμη Εταιρεία"); break; } stringBuilder.append("\n\nΤύπος Επιχείρησης:"); if(sharedPref.getBoolean("paragwgikh", false)) stringBuilder.append("\nΠαραγωγική"); if(sharedPref.getBoolean("emporikh", false)) stringBuilder.append("\nΕμπορική"); if(sharedPref.getBoolean("paroxh", false)) stringBuilder.append("\nΠαροχή υπηρεσιών"); if(sharedPref.getBoolean("franchise", false)) stringBuilder.append("\nFranchise"); if(sharedPref.getBoolean("distrubutor", false)) stringBuilder.append("\nDistributor"); if(sharedPref.getBoolean("alloTypos", false)) { stringBuilder.append("\nΆλλο: "); stringBuilder.append(sharedPref.getString("PerigrafiAllo","")); } stringBuilder.append("\n\nΠελάτες Επιχείρησης:"); if(sharedPref.getBoolean("idiotes", false)) stringBuilder.append("\nΙδιώτες"); if(sharedPref.getBoolean("epixeirhseis", false)) stringBuilder.append("\nΕπιχειρήσεις"); if(sharedPref.getBoolean("alloPelates", false)) { stringBuilder.append("\nΆλλο: "); stringBuilder.append(sharedPref.getString("PerigrafiAlloPelates","")); } String BusinessModel = stringBuilder.toString(); document.add(new Paragraph(BusinessModel,f)); f.setSize(16); f.setStyle("bold"); document.add(new Paragraph("\nΠεριγραφή\n\n",f)); f.setSize(13); f.setStyle("normal"); document.add(new Paragraph( sharedPref.getString("perigrafh", ""),f)); document.add(new Paragraph("\n\n")); SharedPreferences sharedTeamTabs = getSharedPreferences("TeamTabs", Context.MODE_PRIVATE); f.setStyle("bold"); f.setSize(20); Paragraph centerModel2 = new Paragraph("Ομάδα υλοποίησης και δοίκησης\n\n",f); centerModel2.setAlignment(Element.ALIGN_CENTER); document.add(centerModel2); f.setSize(16); document.add(new Paragraph("Διοικητές:\n",f)); f.setStyle("normal"); f.setSize(13); document.add(new Paragraph(sharedTeamTabs.getString("Dioikhtes","") + "\n",f)); f.setStyle("bold"); f.setSize(16); document.add(new Paragraph("Εργατικό Δυναμικό:\n",f)); f.setStyle("normal"); f.setSize(13); document.add(new Paragraph(sharedTeamTabs.getString("Ergates","") + "\n",f)); f.setStyle("bold"); f.setSize(15); document.add(new Paragraph("Συνολικό Κόστος Εργατικού Δυναμικού: " + sharedTeamTabs.getInt("Kostos",0) + "\n\n",f)); SharedPreferences shareEquipmentTabs = getSharedPreferences("equipmentTabs", Context.MODE_PRIVATE); f.setStyle("bold"); f.setSize(20); Paragraph centerModel3 = new Paragraph("Εγκαταστάσεις και Εξοπλισμός:\n",f); centerModel3.setAlignment(Element.ALIGN_CENTER); document.add(centerModel3); f.setStyle("normal"); f.setSize(13); document.add(new Paragraph(shareEquipmentTabs.getString("equipmentLista",""),f)); f.setStyle("bold"); f.setSize(15); document.add(new Paragraph("\nΣυνολικό Κόστος Εγκαταστάσεων και Εξοπλισμού: " + shareEquipmentTabs.getInt("sunolikaEksoda",0) + "\n\n\n",f)); SharedPreferences sharedProiontaTabs = getSharedPreferences("proiontaTabs", Context.MODE_PRIVATE); f.setStyle("bold"); f.setSize(20); Paragraph centerModel4 = new Paragraph("Προϊόντα ή Υπηρεσίες:\n",f); centerModel4.setAlignment(Element.ALIGN_CENTER); document.add(centerModel4); f.setStyle("normal"); f.setSize(13); document.add(new Paragraph(sharedProiontaTabs.getString("esodaProiontaLista","") + "\n",f)); f.setStyle("bold"); f.setSize(15); document.add(new Paragraph("Συνολικά Έσοδα Προϊόντων ή Υπηρεσιών: " + sharedProiontaTabs.getInt("sunolikaEsoda",0) + "\n",f)); document.close(); previewPdf(); } private void previewPdf() { Intent target = new Intent(Intent.ACTION_VIEW); target.setDataAndType(Uri.fromFile(pdfFile),"application/pdf"); target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); Intent intent = Intent.createChooser(target, "Open File"); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(this,"Download a PDF Viewer to see the generated PDF",Toast.LENGTH_SHORT).show(); } } @Override protected void onResume() { super.onResume(); reloadPage(); } public void reloadPage() { EditText synopsi = (EditText) findViewById(R.id.synopsh); ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar2); progressBar.setProgress(0); //removeFocus from editTexts this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); //βλέπω αν τα στοιχεία του businessModel αποθηκεύτηκαν για να συνεχίσει η πρόοδος.. SharedPreferences sharedBusinessModel = getSharedPreferences("businessModel", Context.MODE_PRIVATE); if(sharedBusinessModel.getBoolean("businessModelDone", false)) { businessPlanButton.setBackgroundColor(Color.GREEN); progressBar.setProgress(progressBar.getProgress()+1); } //βλέπω αν τα στοιχεία του proiontaTabs αποθηκεύτηκαν για να συνεχίσει η πρόοδος.. SharedPreferences sharedProionta = getSharedPreferences("proiontaTabs",Context.MODE_PRIVATE); if(sharedProionta.getBoolean("ProiontaTabsDone",false)){ proiontaButton.setBackgroundColor(Color.GREEN); progressBar.setProgress((progressBar.getProgress()+1)); } //βλέπω αν τα στοιχεία του TeamTabs αποθηκεύτηκαν για να συνεχίσει η πρόοδος.. SharedPreferences sharedTeamTabs = getSharedPreferences("TeamTabs", Context.MODE_PRIVATE); if(sharedTeamTabs.getBoolean("TeamTabsDone",false)){ workersButton.setBackgroundColor(Color.GREEN); progressBar.setProgress(progressBar.getProgress()+1); } //βλέπω αν τα στοιχεία του EquipmentTabs αποθηκεύτηκαν για να συνεχίσει η πρόοδος.. SharedPreferences sharedEquipmentTabs = getSharedPreferences("equipmentTabs", Context.MODE_PRIVATE); if(sharedEquipmentTabs.getBoolean("EquipmentTabsDone",false)){ proffesionalEquipmentButton.setBackgroundColor(Color.GREEN); progressBar.setProgress(progressBar.getProgress()+1); } SharedPreferences sharedSynopsi = getSharedPreferences("synopsi", Context.MODE_PRIVATE); if(!sharedSynopsi.getString("synopsiText","").isEmpty()) { synopsi.setText(sharedSynopsi.getString("synopsiText", "")); progressBar.setProgress(progressBar.getProgress() + 1); synopsiHasText=true; } saveButton.setEnabled(progressBar.getProgress()==5); } }
eellak/BusinessPlan
BusinessPlan/app/src/main/java/com/panagiotiswarpro/panos/businessplan/BusinessCreationScreen.java
4,621
//βλέπω αν τα στοιχεία του EquipmentTabs αποθηκεύτηκαν για να συνεχίσει η πρόοδος..
line_comment
el
package com.panagiotiswarpro.panos.businessplan; import android.Manifest; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class BusinessCreationScreen extends AppCompatActivity { //public static String globalPreferences = "com." Button businessPlanButton,workersButton,proffesionalEquipmentButton,saveButton,proiontaButton; private File pdfFile; final private int REQUEST_CODE_ASK_PERMISSIONS = 111; boolean synopsiHasText=false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_business_creation_screen); businessPlanButton = (Button) findViewById(R.id.BusinessPlanButton); ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar2); workersButton = (Button) findViewById(R.id.WorkersButton); proffesionalEquipmentButton = (Button) findViewById(R.id.ProfessionalEquipmentButton); saveButton = (Button) findViewById(R.id.saveButton); proiontaButton = (Button) findViewById(R.id.ProiontaButton); EditText synopsi = (EditText) findViewById(R.id.synopsh); //make the progressbar bigger progressBar.setScaleY(3f); businessPlanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(BusinessCreationScreen.this,BusinessModel.class)); } }); proiontaButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(BusinessCreationScreen.this,ProiontaTab.class)); } }); workersButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(BusinessCreationScreen.this,Team.class)); } }); proffesionalEquipmentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(BusinessCreationScreen.this,Equipment.class)); } }); reloadPage(); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText synopsi = (EditText) findViewById(R.id.synopsh); if(synopsi.getText().toString().isEmpty()) { Toast.makeText(BusinessCreationScreen.this,"Δεν γράψατε σύνοψη",Toast.LENGTH_LONG).show(); } else{ try { createPdfWrapper(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } } } }); synopsi.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { SharedPreferences sharedPreferences = getSharedPreferences("synopsi", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("synopsiText",s.toString()); editor.apply(); ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar2); if(s.length() != 0) { if(!synopsiHasText) { progressBar.setProgress(progressBar.getProgress() + 1); synopsiHasText=true; } } else { progressBar.setProgress(progressBar.getProgress() - 1); synopsiHasText=false; } saveButton.setEnabled(progressBar.getProgress()==5); } }); } private void createPdfWrapper() throws FileNotFoundException,DocumentException{ int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) { showMessageOKCancel("You need to allow access to Storage", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS); } } }); return; } requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS); } return; }else { createPdf(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case REQUEST_CODE_ASK_PERMISSIONS: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission Granted try { createPdfWrapper(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } } else { // Permission Denied Toast.makeText(this, "WRITE_EXTERNAL Permission Denied", Toast.LENGTH_SHORT) .show(); } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(this) .setMessage(message) .setPositiveButton("OK", okListener) .setNegativeButton("Cancel", null) .create() .show(); } private void createPdf() throws FileNotFoundException, DocumentException { File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents"); if (!docsFolder.exists()) { docsFolder.mkdir(); } pdfFile = new File(docsFolder.getAbsolutePath(),"Plan.pdf"); OutputStream output = new FileOutputStream(pdfFile); Document document = new Document(); PdfWriter.getInstance(document, output); document.open(); try{ InputStream in = getResources().openRawResource(R.raw.arialbd); FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Documents/arialbd.ttf"); byte[] buff = new byte[1024]; int read = 0; try { while ((read = in.read(buff)) > 0) { out.write(buff, 0, read); } } finally { in.close(); out.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //itext needed a unicode font to support greek FontFactory.register(Environment.getExternalStorageDirectory() + "/Documents/arialbd.ttf","Greek-Regular"); Font f = FontFactory.getFont("Greek-Regular", BaseFont.IDENTITY_H, true); EditText synopsi = (EditText) findViewById(R.id.synopsh); f.setStyle("bold"); f.setSize(20); Paragraph centerSynopsi = new Paragraph("Σύνοψη\n\n",f); centerSynopsi.setAlignment(Element.ALIGN_CENTER); document.add(centerSynopsi); f.setSize(13); f.setStyle("normal"); document.add(new Paragraph(synopsi.getText().toString()+"\n\n",f)); f.setStyle("bold"); f.setSize(20); Paragraph centerModel = new Paragraph("Επιχειρηματικό Μοντέλο\n\n",f); centerModel.setAlignment(Element.ALIGN_CENTER); document.add(centerModel); f.setSize(16); document.add(new Paragraph("Ταυτότητα\n\n",f)); f.setSize(13); f.setStyle("normal"); SharedPreferences sharedPref = getSharedPreferences("businessModel", Context.MODE_PRIVATE); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Τόπος Εγκατάστασης: "+sharedPref.getString("ToposEgkastasis","")+ "\nΗμερομηνία Έναρξης: " + sharedPref.getString("DateEgkatastash","")+ "\nΜορφή Εταιρείας: "); switch(sharedPref.getInt("morfh", 0)) { case 1: stringBuilder.append("Ατομική Επιχείρηση"); break; case 2: stringBuilder.append("Συνεταιριστική Εταιρεία"); break; case 3: stringBuilder.append("Ανώνυμη Εταιρεία"); break; } stringBuilder.append("\n\nΤύπος Επιχείρησης:"); if(sharedPref.getBoolean("paragwgikh", false)) stringBuilder.append("\nΠαραγωγική"); if(sharedPref.getBoolean("emporikh", false)) stringBuilder.append("\nΕμπορική"); if(sharedPref.getBoolean("paroxh", false)) stringBuilder.append("\nΠαροχή υπηρεσιών"); if(sharedPref.getBoolean("franchise", false)) stringBuilder.append("\nFranchise"); if(sharedPref.getBoolean("distrubutor", false)) stringBuilder.append("\nDistributor"); if(sharedPref.getBoolean("alloTypos", false)) { stringBuilder.append("\nΆλλο: "); stringBuilder.append(sharedPref.getString("PerigrafiAllo","")); } stringBuilder.append("\n\nΠελάτες Επιχείρησης:"); if(sharedPref.getBoolean("idiotes", false)) stringBuilder.append("\nΙδιώτες"); if(sharedPref.getBoolean("epixeirhseis", false)) stringBuilder.append("\nΕπιχειρήσεις"); if(sharedPref.getBoolean("alloPelates", false)) { stringBuilder.append("\nΆλλο: "); stringBuilder.append(sharedPref.getString("PerigrafiAlloPelates","")); } String BusinessModel = stringBuilder.toString(); document.add(new Paragraph(BusinessModel,f)); f.setSize(16); f.setStyle("bold"); document.add(new Paragraph("\nΠεριγραφή\n\n",f)); f.setSize(13); f.setStyle("normal"); document.add(new Paragraph( sharedPref.getString("perigrafh", ""),f)); document.add(new Paragraph("\n\n")); SharedPreferences sharedTeamTabs = getSharedPreferences("TeamTabs", Context.MODE_PRIVATE); f.setStyle("bold"); f.setSize(20); Paragraph centerModel2 = new Paragraph("Ομάδα υλοποίησης και δοίκησης\n\n",f); centerModel2.setAlignment(Element.ALIGN_CENTER); document.add(centerModel2); f.setSize(16); document.add(new Paragraph("Διοικητές:\n",f)); f.setStyle("normal"); f.setSize(13); document.add(new Paragraph(sharedTeamTabs.getString("Dioikhtes","") + "\n",f)); f.setStyle("bold"); f.setSize(16); document.add(new Paragraph("Εργατικό Δυναμικό:\n",f)); f.setStyle("normal"); f.setSize(13); document.add(new Paragraph(sharedTeamTabs.getString("Ergates","") + "\n",f)); f.setStyle("bold"); f.setSize(15); document.add(new Paragraph("Συνολικό Κόστος Εργατικού Δυναμικού: " + sharedTeamTabs.getInt("Kostos",0) + "\n\n",f)); SharedPreferences shareEquipmentTabs = getSharedPreferences("equipmentTabs", Context.MODE_PRIVATE); f.setStyle("bold"); f.setSize(20); Paragraph centerModel3 = new Paragraph("Εγκαταστάσεις και Εξοπλισμός:\n",f); centerModel3.setAlignment(Element.ALIGN_CENTER); document.add(centerModel3); f.setStyle("normal"); f.setSize(13); document.add(new Paragraph(shareEquipmentTabs.getString("equipmentLista",""),f)); f.setStyle("bold"); f.setSize(15); document.add(new Paragraph("\nΣυνολικό Κόστος Εγκαταστάσεων και Εξοπλισμού: " + shareEquipmentTabs.getInt("sunolikaEksoda",0) + "\n\n\n",f)); SharedPreferences sharedProiontaTabs = getSharedPreferences("proiontaTabs", Context.MODE_PRIVATE); f.setStyle("bold"); f.setSize(20); Paragraph centerModel4 = new Paragraph("Προϊόντα ή Υπηρεσίες:\n",f); centerModel4.setAlignment(Element.ALIGN_CENTER); document.add(centerModel4); f.setStyle("normal"); f.setSize(13); document.add(new Paragraph(sharedProiontaTabs.getString("esodaProiontaLista","") + "\n",f)); f.setStyle("bold"); f.setSize(15); document.add(new Paragraph("Συνολικά Έσοδα Προϊόντων ή Υπηρεσιών: " + sharedProiontaTabs.getInt("sunolikaEsoda",0) + "\n",f)); document.close(); previewPdf(); } private void previewPdf() { Intent target = new Intent(Intent.ACTION_VIEW); target.setDataAndType(Uri.fromFile(pdfFile),"application/pdf"); target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); Intent intent = Intent.createChooser(target, "Open File"); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(this,"Download a PDF Viewer to see the generated PDF",Toast.LENGTH_SHORT).show(); } } @Override protected void onResume() { super.onResume(); reloadPage(); } public void reloadPage() { EditText synopsi = (EditText) findViewById(R.id.synopsh); ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar2); progressBar.setProgress(0); //removeFocus from editTexts this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); //βλέπω αν τα στοιχεία του businessModel αποθηκεύτηκαν για να συνεχίσει η πρόοδος.. SharedPreferences sharedBusinessModel = getSharedPreferences("businessModel", Context.MODE_PRIVATE); if(sharedBusinessModel.getBoolean("businessModelDone", false)) { businessPlanButton.setBackgroundColor(Color.GREEN); progressBar.setProgress(progressBar.getProgress()+1); } //βλέπω αν τα στοιχεία του proiontaTabs αποθηκεύτηκαν για να συνεχίσει η πρόοδος.. SharedPreferences sharedProionta = getSharedPreferences("proiontaTabs",Context.MODE_PRIVATE); if(sharedProionta.getBoolean("ProiontaTabsDone",false)){ proiontaButton.setBackgroundColor(Color.GREEN); progressBar.setProgress((progressBar.getProgress()+1)); } //βλέπω αν τα στοιχεία του TeamTabs αποθηκεύτηκαν για να συνεχίσει η πρόοδος.. SharedPreferences sharedTeamTabs = getSharedPreferences("TeamTabs", Context.MODE_PRIVATE); if(sharedTeamTabs.getBoolean("TeamTabsDone",false)){ workersButton.setBackgroundColor(Color.GREEN); progressBar.setProgress(progressBar.getProgress()+1); } //βλέπω αν<SUF> SharedPreferences sharedEquipmentTabs = getSharedPreferences("equipmentTabs", Context.MODE_PRIVATE); if(sharedEquipmentTabs.getBoolean("EquipmentTabsDone",false)){ proffesionalEquipmentButton.setBackgroundColor(Color.GREEN); progressBar.setProgress(progressBar.getProgress()+1); } SharedPreferences sharedSynopsi = getSharedPreferences("synopsi", Context.MODE_PRIVATE); if(!sharedSynopsi.getString("synopsiText","").isEmpty()) { synopsi.setText(sharedSynopsi.getString("synopsiText", "")); progressBar.setProgress(progressBar.getProgress() + 1); synopsiHasText=true; } saveButton.setEnabled(progressBar.getProgress()==5); } }
6723_12
package com.e.calculator; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; /** * Solution class επιλύει τις πράξεις και τροποποιεί το TvResult * Δεν έχει layout, χρησιμοποιείται μόνο από την MainActivity */ public class Solution { /** * Επιλύση των πράξεων * * Σπάει το textview TvPrakseis σε array τύπου String το οποίο περιλαμβάνει κάθε χαρακτήρα εκτός παρενθέσεων * Καλεί την doOps και παίρνει το αποτέλεσμα το οποίο τυπώνει */ public static void solve() { String eq = MainActivity.TvPrakseis.getText().toString(); if (eq.isEmpty()) { return; } // Αφαιρεί τις παρενθέσεις eq = eq.replaceAll("[()]", ""); // Βάζει σε ένα αλφαριθμητικό array τους χαρακτήρες // ?=[] κοιτάει τους χαρακτήρες που έπονται // ?<=[] κοιτάει τους προηγούμενους χαρακτήρες String[] parts = eq.split("(?=[/*+-])|(?<=[/*+-])"); // Αν η εξίσωση ξεκινάει με μείον το πρώτο στοιχείο είναι κενό ΣΕ ANDROID 9 MONO #NO_LOGIC // Το κάνουμε 0 αφού -12 == 0-12 if (parts[0].equals("")) { parts[0] = "0"; } // ΣΕ ANDROID 10 ΚΑΙ ΑΝΩ το πρώτο στοιχείο είναι μείον // Βάζουμε 0 στην αρχή και κάνουμε shift τα στοιχεία δεξιά if (parts[0].equals("-")) { String[] tmp = new String[parts.length + 1]; tmp[0] = "0"; System.arraycopy(parts, 0, tmp, 1, parts.length); parts = tmp.clone(); } // Για debug // System.out.println(Arrays.toString(parts)); double result; if (endsWithOp(parts)) { return; } else if (parts.length == 1) { result = Double.parseDouble(parts[0]); } else { result = doOps(parts); } // Για debug // System.out.println(result); displaySolution(String.valueOf(result)); } /** * Δέχεται ένα array τύπου String το οποίο περιέχει αριθμούς και operators * Το μετατρέπει σε arraylist τύπου String και κάνει τις πράξεις * Πρώτο σκαν αριστερά προς τα δεξιά πολλαπλασιασμοί και διαιρέσεις * Δεύτερο σκαν (αριστερά προς τα δεξιά πάλι) προσθέσεις και αφαιρέσεις * @param parts: το array τύπου String * @return το αποτέλεσμα των πράξεων double ακρίβειας */ private static double doOps(String[] parts) { ArrayList<String> arParts = new ArrayList<>(Arrays.asList(parts)); // Αν το μείον προηγείται από άλλο σύμβολο το συγχωνεύει με τον επόμενο αριθμό // πχ [12, *, -, 9] -> [12, *, -9.0] int i = 0; while (i < arParts.size()) { String e = arParts.get(i); boolean isOp = e.equals("+") || e.equals("-") || e.equals("*") || e.equals("/"); if (isOp) { if (arParts.get(i + 1).equals("-")) { arParts.set(i + 1, String.valueOf(Double.parseDouble(arParts.get(i + 2)) * (-1))); arParts.remove(i + 2); } } i++; } // Debug // System.out.println(arParts); // * / i = 1; while (i < arParts.size()) { double num1 = Double.parseDouble(arParts.get(i - 1)); String op = arParts.get(i); double num2 = Double.parseDouble(arParts.get(i + 1)); switch (op) { case "*" : arParts.set(i - 1, String.valueOf(num1 * num2)); arParts.remove(i); arParts.remove(i); break; case "/" : arParts.set(i - 1, String.valueOf(num1 / num2)); arParts.remove(i); arParts.remove(i); break; case "+": case "-": i+=2; break; } } // + - i = 1; while (i < arParts.size()) { double num1 = Double.parseDouble(arParts.get(i - 1)); String op = arParts.get(i); double num2 = Double.parseDouble(arParts.get(i + 1)); switch (op) { case "+": arParts.set(i - 1, String.valueOf(num1 + num2)); arParts.remove(i); arParts.remove(i); break; case "-": arParts.set(i - 1, String.valueOf(num1 - num2)); arParts.remove(i); arParts.remove(i); break; } } // Debug // System.out.println(arParts); return Double.parseDouble(arParts.get(0)); } /** * Δέχεται ένα array τύπου String και ελέγχει αν το τελευταίο στοιχείο είναι σύμβολο +, -, *, / * @param parts: array τύπου String * @return true αν ναι, false αλλιώς */ private static boolean endsWithOp(String[] parts) { return parts[parts.length - 1].equals("+") || parts[parts.length - 1].equals("-") || parts[parts.length - 1].equals("*") || parts[parts.length - 1].equals("/"); } /** * Τροποποιεί το TvResult * @param res: το αποτέλεσμα */ private static void displaySolution(String res) { // BigDecimal για να εξαλειφθεί το E notation try { MainActivity.TvResult.setText(new BigDecimal(res).toPlainString()); } // Περιπτώσεις 0/0 -> NaN και n/0 -> +-Infinity catch(NumberFormatException e) { MainActivity.TvResult.setText(res); } } }
eimon96/Calculator
Calculator/app/src/main/java/com/e/calculator/Solution.java
2,118
// Περιπτώσεις 0/0 -> NaN και n/0 -> +-Infinity
line_comment
el
package com.e.calculator; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; /** * Solution class επιλύει τις πράξεις και τροποποιεί το TvResult * Δεν έχει layout, χρησιμοποιείται μόνο από την MainActivity */ public class Solution { /** * Επιλύση των πράξεων * * Σπάει το textview TvPrakseis σε array τύπου String το οποίο περιλαμβάνει κάθε χαρακτήρα εκτός παρενθέσεων * Καλεί την doOps και παίρνει το αποτέλεσμα το οποίο τυπώνει */ public static void solve() { String eq = MainActivity.TvPrakseis.getText().toString(); if (eq.isEmpty()) { return; } // Αφαιρεί τις παρενθέσεις eq = eq.replaceAll("[()]", ""); // Βάζει σε ένα αλφαριθμητικό array τους χαρακτήρες // ?=[] κοιτάει τους χαρακτήρες που έπονται // ?<=[] κοιτάει τους προηγούμενους χαρακτήρες String[] parts = eq.split("(?=[/*+-])|(?<=[/*+-])"); // Αν η εξίσωση ξεκινάει με μείον το πρώτο στοιχείο είναι κενό ΣΕ ANDROID 9 MONO #NO_LOGIC // Το κάνουμε 0 αφού -12 == 0-12 if (parts[0].equals("")) { parts[0] = "0"; } // ΣΕ ANDROID 10 ΚΑΙ ΑΝΩ το πρώτο στοιχείο είναι μείον // Βάζουμε 0 στην αρχή και κάνουμε shift τα στοιχεία δεξιά if (parts[0].equals("-")) { String[] tmp = new String[parts.length + 1]; tmp[0] = "0"; System.arraycopy(parts, 0, tmp, 1, parts.length); parts = tmp.clone(); } // Για debug // System.out.println(Arrays.toString(parts)); double result; if (endsWithOp(parts)) { return; } else if (parts.length == 1) { result = Double.parseDouble(parts[0]); } else { result = doOps(parts); } // Για debug // System.out.println(result); displaySolution(String.valueOf(result)); } /** * Δέχεται ένα array τύπου String το οποίο περιέχει αριθμούς και operators * Το μετατρέπει σε arraylist τύπου String και κάνει τις πράξεις * Πρώτο σκαν αριστερά προς τα δεξιά πολλαπλασιασμοί και διαιρέσεις * Δεύτερο σκαν (αριστερά προς τα δεξιά πάλι) προσθέσεις και αφαιρέσεις * @param parts: το array τύπου String * @return το αποτέλεσμα των πράξεων double ακρίβειας */ private static double doOps(String[] parts) { ArrayList<String> arParts = new ArrayList<>(Arrays.asList(parts)); // Αν το μείον προηγείται από άλλο σύμβολο το συγχωνεύει με τον επόμενο αριθμό // πχ [12, *, -, 9] -> [12, *, -9.0] int i = 0; while (i < arParts.size()) { String e = arParts.get(i); boolean isOp = e.equals("+") || e.equals("-") || e.equals("*") || e.equals("/"); if (isOp) { if (arParts.get(i + 1).equals("-")) { arParts.set(i + 1, String.valueOf(Double.parseDouble(arParts.get(i + 2)) * (-1))); arParts.remove(i + 2); } } i++; } // Debug // System.out.println(arParts); // * / i = 1; while (i < arParts.size()) { double num1 = Double.parseDouble(arParts.get(i - 1)); String op = arParts.get(i); double num2 = Double.parseDouble(arParts.get(i + 1)); switch (op) { case "*" : arParts.set(i - 1, String.valueOf(num1 * num2)); arParts.remove(i); arParts.remove(i); break; case "/" : arParts.set(i - 1, String.valueOf(num1 / num2)); arParts.remove(i); arParts.remove(i); break; case "+": case "-": i+=2; break; } } // + - i = 1; while (i < arParts.size()) { double num1 = Double.parseDouble(arParts.get(i - 1)); String op = arParts.get(i); double num2 = Double.parseDouble(arParts.get(i + 1)); switch (op) { case "+": arParts.set(i - 1, String.valueOf(num1 + num2)); arParts.remove(i); arParts.remove(i); break; case "-": arParts.set(i - 1, String.valueOf(num1 - num2)); arParts.remove(i); arParts.remove(i); break; } } // Debug // System.out.println(arParts); return Double.parseDouble(arParts.get(0)); } /** * Δέχεται ένα array τύπου String και ελέγχει αν το τελευταίο στοιχείο είναι σύμβολο +, -, *, / * @param parts: array τύπου String * @return true αν ναι, false αλλιώς */ private static boolean endsWithOp(String[] parts) { return parts[parts.length - 1].equals("+") || parts[parts.length - 1].equals("-") || parts[parts.length - 1].equals("*") || parts[parts.length - 1].equals("/"); } /** * Τροποποιεί το TvResult * @param res: το αποτέλεσμα */ private static void displaySolution(String res) { // BigDecimal για να εξαλειφθεί το E notation try { MainActivity.TvResult.setText(new BigDecimal(res).toPlainString()); } // Περιπτώσεις 0/0<SUF> catch(NumberFormatException e) { MainActivity.TvResult.setText(res); } } }
385_22
package com.telis.patreopolis; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class BoardPanel extends JPanel { private BufferedImage image; BoardPanel(Tile[] tiles) { //BoxLayout(Container target, int axis) //Y_AXIS - Components are laid out vertically from top to bottom. setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // parameters of Flowlayout: align, horizontal gap, vertical gap JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0)); //parameters of Dimension (int width, int height) topPanel.setPreferredSize(new Dimension(0,90)); topPanel.add(tiles[20].getTilePanel()); topPanel.add(tiles[21].getTilePanel()); topPanel.add(tiles[22].getTilePanel()); topPanel.add(tiles[23].getTilePanel()); topPanel.add(tiles[24].getTilePanel()); topPanel.add(tiles[25].getTilePanel()); topPanel.add(tiles[26].getTilePanel()); topPanel.add(tiles[27].getTilePanel()); topPanel.add(tiles[28].getTilePanel()); topPanel.add(tiles[29].getTilePanel()); topPanel.add(tiles[30].getTilePanel()); //JPanel(LayoutManager layout) JPanel center = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0)); //GridLayout(int rows, int cols) JPanel leftPanel = new JPanel(new GridLayout(0,1)); leftPanel.add(tiles[19].getTilePanel()); leftPanel.add(tiles[18].getTilePanel()); leftPanel.add(tiles[17].getTilePanel()); leftPanel.add(tiles[16].getTilePanel()); leftPanel.add(tiles[15].getTilePanel()); leftPanel.add(tiles[14].getTilePanel()); leftPanel.add(tiles[13].getTilePanel()); leftPanel.add(tiles[12].getTilePanel()); leftPanel.add(tiles[11].getTilePanel()); //Creates a new JPanel with a double buffer and a flow layout. //BoxLayout(Container target, int axis) JPanel middlePanel = new JPanel(); middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS)); ImageIcon icon = new ImageIcon("1.png"); middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS)); middlePanel.setBorder(BorderFactory.createLineBorder(Color.black, 1)); try { image = ImageIO.read(new File("C:\\Users\\trian\\Documents\\NetBeansProjects\\ElGreco\\3t.png")); } catch(IOException ex){ex.printStackTrace();} /* logo JTextPane */ // JTextPane logo = new JTextPane(); // logo.setEditable(false); // JLabel logoText = new JLabel("El Greco: τα ταξίδια της ζωής και του έργου του", JLabel.CENTER); // // // logoText.setFont(new Font("Arial", Font.BOLD, 28)); // logo.setPreferredSize(new Dimension(808, 808)); // // String html_text = ""; // "<html>Κανόνες: " // + "<BR>- Κάθε παίκτης ξεκινάει παίρνοντας 150 δουκάτα από τη τράπεζα" // + "<BR>- Σε περίπτωση σωστής απάντησης περιηγείται το χώρο του εκάστοτε έργου. Αν η απάντηση είναι λάθος του αφαιρούνται 5 δουκάτα" // + "<BR>- Στην bonus ερώτηση προστίθενται 15 δουκάτα αν είναι σωστή η απάντηση αλλιώς μένει στην ίδια θέση" // + "<BR>- Στην superbonus ερώτηση περιηγείται τον αμέσως επόμενο χώρο για να δει το έργο αν η απάντηση είναι σωστή" // + "<BR>- Αλλιώς μένει εκεί που είναι. Κάθε παίκτης έχει δικαίωμα να απάντήσει μόνο σε μια superbonus ερώτηση στο παιχνίδι " // + "<BR>- Αν βρεθεί στη θέση υπουργείο πολιτισμού δέχεται οικονομική ενίσχυση 25 δουκάτων." // + "<BR>- Αν κάποιος παίκτης βρεθεί στη θέση 'Διάβασε το Βιβλίο κανονισμού επίσκεψης μουσείων και εκθεσιακών χώρων' " // + "<BR> οφείλει να μεταβεί στη θέση 'Βιβλίο κανονισμού επίσκεψης μουσείων και εκθεσιακών χώρων' και να μελετήσει το βιβλίο αυτό." // + "<BR>- Αν κάποιος παίκτης βρεθεί στη θέση 'Βιβλίο κανονισμού επίσκεψης μουσείων και εκθεσιακών χώρων' παραμένει στη θέση αυτή" // + "<BR> μέχρι τον επόμενο γύρο." // + "<BR>- Κάθε φορά που κάποιος παίκτης περνά από την 'Αφετηρία' προστίθενται στο λογαριασμό του 20 δουκάτα." // + "</HTML> "; ImageIcon image = new ImageIcon ("C:\\Users\\trian\\Documents\\NetBeansProjects\\ElGreco\\3t.png"); JLabel logoText2 = new JLabel(image, JLabel.CENTER); // JLabel logoText2 = new JLabel(html_text, JLabel.CENTER); // logo.insertComponent(logoText2); // logo.insertComponent(logoText); // StyledDocument doc = logo.getStyledDocument(); SimpleAttributeSet centerText = new SimpleAttributeSet(); StyleConstants.setAlignment(centerText, StyleConstants.ALIGN_CENTER); //public void insertString(int offset, String str, AttributeSet a) throws BadLocationException // try { // doc.insertString(0, "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + // "\n\n\n\n\n", centerText); // } catch (BadLocationException e) { // e.printStackTrace(); // } // doc.setParagraphAttributes(0, doc.getLength(), centerText, false); // public void setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace) middlePanel.add(logoText2); // middlePanel.add(logo); /* LOGO2 JTextPane */ // JTextPane logo2 = new JTextPane(); // logo2.setEditable(false); // JLabel logoText2 = new JLabel("" // + " Rules: " // + "\n" // + "monuments-> you pay money, \n" // + "command-> move forward to a position\n" // + "\nquestion-> you answer question and if right you move on to the next monument" // + "\nfree parking-> ", JLabel.CENTER); // logo2.setPreferredSize(new Dimension(898, 1038)); // logo2.insertComponent(logoText2); // StyledDocument doc2 = logo2.getStyledDocument(); // SimpleAttributeSet centerText2 = new SimpleAttributeSet(); // StyleConstants.setAlignment(centerText2, StyleConstants.ALIGN_CENTER); // try { // //public void insertString(int offset, String str, AttributeSet a) throws BadLocationException // doc2.insertString(0, "" + // "\n", centerText2); // } catch (BadLocationException e) { // e.printStackTrace(); // } // doc2.setParagraphAttributes(0, doc2.getLength(), centerText2, false); // middlePanel.add(logo2, BorderLayout.CENTER); JPanel rightPanel = new JPanel(new GridLayout(0,1)); rightPanel.add(tiles[31].getTilePanel()); rightPanel.add(tiles[32].getTilePanel()); rightPanel.add(tiles[33].getTilePanel()); rightPanel.add(tiles[34].getTilePanel()); rightPanel.add(tiles[35].getTilePanel()); rightPanel.add(tiles[36].getTilePanel()); rightPanel.add(tiles[37].getTilePanel()); rightPanel.add(tiles[38].getTilePanel()); rightPanel.add(tiles[39].getTilePanel()); center.add(leftPanel); center.add(middlePanel); center.add(rightPanel); JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT,0,-1)); bottomPanel.add(tiles[10].getTilePanel()); bottomPanel.add(tiles[9].getTilePanel()); bottomPanel.add(tiles[8].getTilePanel()); bottomPanel.add(tiles[7].getTilePanel()); bottomPanel.add(tiles[6].getTilePanel()); bottomPanel.add(tiles[5].getTilePanel()); bottomPanel.add(tiles[4].getTilePanel()); bottomPanel.add(tiles[3].getTilePanel()); bottomPanel.add(tiles[2].getTilePanel()); bottomPanel.add(tiles[1].getTilePanel()); bottomPanel.add(tiles[0].getTilePanel()); // JLabel testimg = new JLabel(new ImageIcon(getClass().getResource("2.png"))); // testimg.setLocation(-500, 300); add(topPanel); add(center); add(bottomPanel); // add(testimg); } }
ellak-monades-aristeias/ElGreco
src/com/telis/patreopolis/BoardPanel.java
3,057
// + "<BR> μέχρι τον επόμενο γύρο."
line_comment
el
package com.telis.patreopolis; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class BoardPanel extends JPanel { private BufferedImage image; BoardPanel(Tile[] tiles) { //BoxLayout(Container target, int axis) //Y_AXIS - Components are laid out vertically from top to bottom. setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // parameters of Flowlayout: align, horizontal gap, vertical gap JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0)); //parameters of Dimension (int width, int height) topPanel.setPreferredSize(new Dimension(0,90)); topPanel.add(tiles[20].getTilePanel()); topPanel.add(tiles[21].getTilePanel()); topPanel.add(tiles[22].getTilePanel()); topPanel.add(tiles[23].getTilePanel()); topPanel.add(tiles[24].getTilePanel()); topPanel.add(tiles[25].getTilePanel()); topPanel.add(tiles[26].getTilePanel()); topPanel.add(tiles[27].getTilePanel()); topPanel.add(tiles[28].getTilePanel()); topPanel.add(tiles[29].getTilePanel()); topPanel.add(tiles[30].getTilePanel()); //JPanel(LayoutManager layout) JPanel center = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0)); //GridLayout(int rows, int cols) JPanel leftPanel = new JPanel(new GridLayout(0,1)); leftPanel.add(tiles[19].getTilePanel()); leftPanel.add(tiles[18].getTilePanel()); leftPanel.add(tiles[17].getTilePanel()); leftPanel.add(tiles[16].getTilePanel()); leftPanel.add(tiles[15].getTilePanel()); leftPanel.add(tiles[14].getTilePanel()); leftPanel.add(tiles[13].getTilePanel()); leftPanel.add(tiles[12].getTilePanel()); leftPanel.add(tiles[11].getTilePanel()); //Creates a new JPanel with a double buffer and a flow layout. //BoxLayout(Container target, int axis) JPanel middlePanel = new JPanel(); middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS)); ImageIcon icon = new ImageIcon("1.png"); middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS)); middlePanel.setBorder(BorderFactory.createLineBorder(Color.black, 1)); try { image = ImageIO.read(new File("C:\\Users\\trian\\Documents\\NetBeansProjects\\ElGreco\\3t.png")); } catch(IOException ex){ex.printStackTrace();} /* logo JTextPane */ // JTextPane logo = new JTextPane(); // logo.setEditable(false); // JLabel logoText = new JLabel("El Greco: τα ταξίδια της ζωής και του έργου του", JLabel.CENTER); // // // logoText.setFont(new Font("Arial", Font.BOLD, 28)); // logo.setPreferredSize(new Dimension(808, 808)); // // String html_text = ""; // "<html>Κανόνες: " // + "<BR>- Κάθε παίκτης ξεκινάει παίρνοντας 150 δουκάτα από τη τράπεζα" // + "<BR>- Σε περίπτωση σωστής απάντησης περιηγείται το χώρο του εκάστοτε έργου. Αν η απάντηση είναι λάθος του αφαιρούνται 5 δουκάτα" // + "<BR>- Στην bonus ερώτηση προστίθενται 15 δουκάτα αν είναι σωστή η απάντηση αλλιώς μένει στην ίδια θέση" // + "<BR>- Στην superbonus ερώτηση περιηγείται τον αμέσως επόμενο χώρο για να δει το έργο αν η απάντηση είναι σωστή" // + "<BR>- Αλλιώς μένει εκεί που είναι. Κάθε παίκτης έχει δικαίωμα να απάντήσει μόνο σε μια superbonus ερώτηση στο παιχνίδι " // + "<BR>- Αν βρεθεί στη θέση υπουργείο πολιτισμού δέχεται οικονομική ενίσχυση 25 δουκάτων." // + "<BR>- Αν κάποιος παίκτης βρεθεί στη θέση 'Διάβασε το Βιβλίο κανονισμού επίσκεψης μουσείων και εκθεσιακών χώρων' " // + "<BR> οφείλει να μεταβεί στη θέση 'Βιβλίο κανονισμού επίσκεψης μουσείων και εκθεσιακών χώρων' και να μελετήσει το βιβλίο αυτό." // + "<BR>- Αν κάποιος παίκτης βρεθεί στη θέση 'Βιβλίο κανονισμού επίσκεψης μουσείων και εκθεσιακών χώρων' παραμένει στη θέση αυτή" // + "<BR><SUF> // + "<BR>- Κάθε φορά που κάποιος παίκτης περνά από την 'Αφετηρία' προστίθενται στο λογαριασμό του 20 δουκάτα." // + "</HTML> "; ImageIcon image = new ImageIcon ("C:\\Users\\trian\\Documents\\NetBeansProjects\\ElGreco\\3t.png"); JLabel logoText2 = new JLabel(image, JLabel.CENTER); // JLabel logoText2 = new JLabel(html_text, JLabel.CENTER); // logo.insertComponent(logoText2); // logo.insertComponent(logoText); // StyledDocument doc = logo.getStyledDocument(); SimpleAttributeSet centerText = new SimpleAttributeSet(); StyleConstants.setAlignment(centerText, StyleConstants.ALIGN_CENTER); //public void insertString(int offset, String str, AttributeSet a) throws BadLocationException // try { // doc.insertString(0, "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + // "\n\n\n\n\n", centerText); // } catch (BadLocationException e) { // e.printStackTrace(); // } // doc.setParagraphAttributes(0, doc.getLength(), centerText, false); // public void setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace) middlePanel.add(logoText2); // middlePanel.add(logo); /* LOGO2 JTextPane */ // JTextPane logo2 = new JTextPane(); // logo2.setEditable(false); // JLabel logoText2 = new JLabel("" // + " Rules: " // + "\n" // + "monuments-> you pay money, \n" // + "command-> move forward to a position\n" // + "\nquestion-> you answer question and if right you move on to the next monument" // + "\nfree parking-> ", JLabel.CENTER); // logo2.setPreferredSize(new Dimension(898, 1038)); // logo2.insertComponent(logoText2); // StyledDocument doc2 = logo2.getStyledDocument(); // SimpleAttributeSet centerText2 = new SimpleAttributeSet(); // StyleConstants.setAlignment(centerText2, StyleConstants.ALIGN_CENTER); // try { // //public void insertString(int offset, String str, AttributeSet a) throws BadLocationException // doc2.insertString(0, "" + // "\n", centerText2); // } catch (BadLocationException e) { // e.printStackTrace(); // } // doc2.setParagraphAttributes(0, doc2.getLength(), centerText2, false); // middlePanel.add(logo2, BorderLayout.CENTER); JPanel rightPanel = new JPanel(new GridLayout(0,1)); rightPanel.add(tiles[31].getTilePanel()); rightPanel.add(tiles[32].getTilePanel()); rightPanel.add(tiles[33].getTilePanel()); rightPanel.add(tiles[34].getTilePanel()); rightPanel.add(tiles[35].getTilePanel()); rightPanel.add(tiles[36].getTilePanel()); rightPanel.add(tiles[37].getTilePanel()); rightPanel.add(tiles[38].getTilePanel()); rightPanel.add(tiles[39].getTilePanel()); center.add(leftPanel); center.add(middlePanel); center.add(rightPanel); JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT,0,-1)); bottomPanel.add(tiles[10].getTilePanel()); bottomPanel.add(tiles[9].getTilePanel()); bottomPanel.add(tiles[8].getTilePanel()); bottomPanel.add(tiles[7].getTilePanel()); bottomPanel.add(tiles[6].getTilePanel()); bottomPanel.add(tiles[5].getTilePanel()); bottomPanel.add(tiles[4].getTilePanel()); bottomPanel.add(tiles[3].getTilePanel()); bottomPanel.add(tiles[2].getTilePanel()); bottomPanel.add(tiles[1].getTilePanel()); bottomPanel.add(tiles[0].getTilePanel()); // JLabel testimg = new JLabel(new ImageIcon(getClass().getResource("2.png"))); // testimg.setLocation(-500, 300); add(topPanel); add(center); add(bottomPanel); // add(testimg); } }
2910_45
import java.util.Arrays; // Priority Queue implementation with generic type T, where T extends Comparable<T> public class PQ<T extends Comparable<T>> { // Constants for default capacity and resize factor private static final int DEFAULT_CAPACITY = 10; private static final double DEFAULT_RESIZE = 0.75; // Array to store the heap elements private T[] minHeap; // Map elements to their indexes private int[] indexes; // Current size of the priority queue private int size; // Constructor to initialize the priority queue public PQ() { this.minHeap = (T[]) new Comparable[DEFAULT_CAPACITY]; this.indexes = new int[100]; this.size = 0; } // Method to insert an element into the priority queue public void insert(T element) { // Check if resizing is required if (size + 1 > minHeap.length * DEFAULT_RESIZE) { resize(); } // Insert the element at the end of the array minHeap[size] = element; // Update the index of the inserted element indexes[hash(element)] = size; size++; // Restore the heap property by moving the inserted element up the heap heapifyUp(size - 1); } // Method to get and remove the minimum element from the priority queue public T getmin() { // Remove and return the minimum element return remove(min()); } // Method to remove a specific element from the priority queue public T remove(T element) { int indexToRemove = indexOf(element); // Check if the element is not found or the index is out of bounds if (indexToRemove == -1 || indexToRemove >= size) { throw new IllegalArgumentException("Element not found in the priority queue"); } T removedT = minHeap[indexToRemove]; // If the element to remove is at the last index, simply decrement the size if (indexToRemove == size - 1) { size--; // Mark that the element no longer exists indexes[hash(removedT)] = -1; return removedT; } // Replace the element to remove with the last element in the array minHeap[indexToRemove] = minHeap[size - 1]; // Update the index of the moved element indexes[hash(minHeap[indexToRemove])] = indexToRemove; size--; // Restore the heap property if (indexToRemove < size) { heapifyDown(indexToRemove); heapifyUp(indexToRemove); } // Mark that the element no longer exists indexes[hash(removedT)] = -1; return removedT; } // Method to resize the minHeap array private void resize() { int newCapacity = minHeap.length * 2; T[] newMinHeap = (T[]) new Comparable[newCapacity]; // Copy elements from the old array to the new array for (int i = 0; i < size; i++) { newMinHeap[i] = minHeap[i]; } minHeap = newMinHeap; // Reassign indexes if necessary reassignIndexes(); } // Method to reassign indexes private void reassignIndexes() { // Initialize all indexes to -1 Arrays.fill(indexes, -1); // Use hash(element) as the index for each element in the heap for (int i = 0; i < size; i++) { indexes[hash(minHeap[i])] = i; } } // Method to check if the priority queue is empty public boolean isEmpty() { return size == 0; } // Method to calculate the hash value of an element private int hash(T element) { // Use the ID if the element is an instance of City if (element instanceof City) { return ((City) element).getID(); } // Otherwise, use the default hashCode return element.hashCode(); } // Method to get the index of an element in the priority queue private int indexOf(T element) { return indexes[hash(element)]; } // Method to heapify up the priority queue from a given index private void heapifyUp(int currentIndex) { T currentElement = minHeap[currentIndex]; while (currentIndex > 0) { int parentIndex = (currentIndex - 1) / 2; T parentElement = minHeap[parentIndex]; // If the current element is greater than or equal to its parent, break the loop if (currentElement.compareTo(parentElement) >= 0) { break; } // Swap the current element with its parent swap(currentIndex, parentIndex); // Move up to the parent index currentIndex = parentIndex; } } // Method to heapify down the priority queue from a given index private void heapifyDown(int currentIndex) { int leftChildIndex, rightChildIndex, smallestChildIndex; while (true) { leftChildIndex = 2 * currentIndex + 1; rightChildIndex = 2 * currentIndex + 2; smallestChildIndex = currentIndex; // Find the smallest child among left and right children if (leftChildIndex < size && minHeap[leftChildIndex].compareTo(minHeap[smallestChildIndex]) < 0) { smallestChildIndex = leftChildIndex; } if (rightChildIndex < size && minHeap[rightChildIndex].compareTo(minHeap[smallestChildIndex]) < 0) { smallestChildIndex = rightChildIndex; } // If the smallest child is not the current index, swap and continue if (smallestChildIndex != currentIndex) { swap(currentIndex, smallestChildIndex); currentIndex = smallestChildIndex; } else { // If the current element is smaller than its children, break the loop break; } } } // Method to swap elements at two given indices private void swap(int index1, int index2) { T temp = minHeap[index1]; minHeap[index1] = minHeap[index2]; minHeap[index2] = temp; // Update indexes for the swapped elements indexes[hash(minHeap[index1])] = index1; indexes[hash(minHeap[index2])] = index2; } // Method to get the size of the priority queue public int size() { return size; } // Method to get the minimum element in the priority queue public T min() { // Check if the priority queue is empty if (isEmpty()) { throw new IllegalStateException("Priority queue is empty"); } return minHeap[0]; } // η υλοποιηση τησ μεθοδου ειναι Ν δεν βρηκα πιο απλο και συντομο τροπο!!!!! public T getMax() { if (isEmpty()) { throw new IllegalStateException("Min Heap is empty"); } T maxItem = minHeap[0]; for (T item : minHeap) { if (item != null && item.compareTo(maxItem) > 0) { maxItem = item; } } return maxItem; } }
fanisvl/ds-assignment-2
src/PQ.java
1,619
// η υλοποιηση τησ μεθοδου ειναι Ν δεν βρηκα πιο απλο και συντομο τροπο!!!!!
line_comment
el
import java.util.Arrays; // Priority Queue implementation with generic type T, where T extends Comparable<T> public class PQ<T extends Comparable<T>> { // Constants for default capacity and resize factor private static final int DEFAULT_CAPACITY = 10; private static final double DEFAULT_RESIZE = 0.75; // Array to store the heap elements private T[] minHeap; // Map elements to their indexes private int[] indexes; // Current size of the priority queue private int size; // Constructor to initialize the priority queue public PQ() { this.minHeap = (T[]) new Comparable[DEFAULT_CAPACITY]; this.indexes = new int[100]; this.size = 0; } // Method to insert an element into the priority queue public void insert(T element) { // Check if resizing is required if (size + 1 > minHeap.length * DEFAULT_RESIZE) { resize(); } // Insert the element at the end of the array minHeap[size] = element; // Update the index of the inserted element indexes[hash(element)] = size; size++; // Restore the heap property by moving the inserted element up the heap heapifyUp(size - 1); } // Method to get and remove the minimum element from the priority queue public T getmin() { // Remove and return the minimum element return remove(min()); } // Method to remove a specific element from the priority queue public T remove(T element) { int indexToRemove = indexOf(element); // Check if the element is not found or the index is out of bounds if (indexToRemove == -1 || indexToRemove >= size) { throw new IllegalArgumentException("Element not found in the priority queue"); } T removedT = minHeap[indexToRemove]; // If the element to remove is at the last index, simply decrement the size if (indexToRemove == size - 1) { size--; // Mark that the element no longer exists indexes[hash(removedT)] = -1; return removedT; } // Replace the element to remove with the last element in the array minHeap[indexToRemove] = minHeap[size - 1]; // Update the index of the moved element indexes[hash(minHeap[indexToRemove])] = indexToRemove; size--; // Restore the heap property if (indexToRemove < size) { heapifyDown(indexToRemove); heapifyUp(indexToRemove); } // Mark that the element no longer exists indexes[hash(removedT)] = -1; return removedT; } // Method to resize the minHeap array private void resize() { int newCapacity = minHeap.length * 2; T[] newMinHeap = (T[]) new Comparable[newCapacity]; // Copy elements from the old array to the new array for (int i = 0; i < size; i++) { newMinHeap[i] = minHeap[i]; } minHeap = newMinHeap; // Reassign indexes if necessary reassignIndexes(); } // Method to reassign indexes private void reassignIndexes() { // Initialize all indexes to -1 Arrays.fill(indexes, -1); // Use hash(element) as the index for each element in the heap for (int i = 0; i < size; i++) { indexes[hash(minHeap[i])] = i; } } // Method to check if the priority queue is empty public boolean isEmpty() { return size == 0; } // Method to calculate the hash value of an element private int hash(T element) { // Use the ID if the element is an instance of City if (element instanceof City) { return ((City) element).getID(); } // Otherwise, use the default hashCode return element.hashCode(); } // Method to get the index of an element in the priority queue private int indexOf(T element) { return indexes[hash(element)]; } // Method to heapify up the priority queue from a given index private void heapifyUp(int currentIndex) { T currentElement = minHeap[currentIndex]; while (currentIndex > 0) { int parentIndex = (currentIndex - 1) / 2; T parentElement = minHeap[parentIndex]; // If the current element is greater than or equal to its parent, break the loop if (currentElement.compareTo(parentElement) >= 0) { break; } // Swap the current element with its parent swap(currentIndex, parentIndex); // Move up to the parent index currentIndex = parentIndex; } } // Method to heapify down the priority queue from a given index private void heapifyDown(int currentIndex) { int leftChildIndex, rightChildIndex, smallestChildIndex; while (true) { leftChildIndex = 2 * currentIndex + 1; rightChildIndex = 2 * currentIndex + 2; smallestChildIndex = currentIndex; // Find the smallest child among left and right children if (leftChildIndex < size && minHeap[leftChildIndex].compareTo(minHeap[smallestChildIndex]) < 0) { smallestChildIndex = leftChildIndex; } if (rightChildIndex < size && minHeap[rightChildIndex].compareTo(minHeap[smallestChildIndex]) < 0) { smallestChildIndex = rightChildIndex; } // If the smallest child is not the current index, swap and continue if (smallestChildIndex != currentIndex) { swap(currentIndex, smallestChildIndex); currentIndex = smallestChildIndex; } else { // If the current element is smaller than its children, break the loop break; } } } // Method to swap elements at two given indices private void swap(int index1, int index2) { T temp = minHeap[index1]; minHeap[index1] = minHeap[index2]; minHeap[index2] = temp; // Update indexes for the swapped elements indexes[hash(minHeap[index1])] = index1; indexes[hash(minHeap[index2])] = index2; } // Method to get the size of the priority queue public int size() { return size; } // Method to get the minimum element in the priority queue public T min() { // Check if the priority queue is empty if (isEmpty()) { throw new IllegalStateException("Priority queue is empty"); } return minHeap[0]; } // η υλοποιηση<SUF> public T getMax() { if (isEmpty()) { throw new IllegalStateException("Min Heap is empty"); } T maxItem = minHeap[0]; for (T item : minHeap) { if (item != null && item.compareTo(maxItem) > 0) { maxItem = item; } } return maxItem; } }
1834_25
package com.fivasim.antikythera; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.graphics.Bitmap; import android.opengl.GLU; import android.opengl.GLUtils; import android.opengl.GLSurfaceView.Renderer; import android.os.Build; import static com.fivasim.antikythera.Initial2.*; public class OpenGLRenderer2 implements Renderer { private Gear gears[] = new Gear[num_gears]; private Gear axles[] = new Gear[num_axles]; private Pointer pointers[] = new Pointer[num_pointers]; private Gear pointerbase = new Gear( new float[]{0f, 1.5f, 1f, 50f, 0f, 0f} ); private Plate plates[] = new Plate[2]; private static int framecount = 0; public static float curX = 0f; public static float curY = 0f; public static float curX1 = 0f; public static float curY1 = 0f; public static float curDist = 0f; public static int touchmode = 0; public static float angle = 0f; public static float fullrotate_x = 0f; public static float fullrotate_y = 0f; public static float fullrotate_z = 0f; public static float position_x = 0f; public static float position_y = 0f; public static float zoomfac = 0f; public static long timestamp = System.currentTimeMillis(); private Bitmap bitmap; public OpenGLRenderer2() { int i; // Initialize our gears. for (i=0;i<num_gears;i++) { gears[i] = new Gear(geardata[i]); } for (i=0;i<num_axles;i++) { axles[i] = new Gear(axledata[i]); } for (i=0;i<num_pointers;i++) { pointers[i] = new Pointer( pointer_len[i], pointer_pos[i]); } plates[0] = new Plate(60.0f, 40.0f, 25.0f); plates[1] = new Plate(60.0f, 40.0f,-41.0f); } /* * (non-Javadoc) * * @see * android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition * .khronos.opengles.GL10, javax.microedition.khronos.egl.EGLConfig) */ public void onSurfaceCreated(GL10 gl, EGLConfig config) { // Set the background color to black ( rgba ). gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Enable Smooth Shading, default not really needed. gl.glShadeModel(GL10.GL_SMOOTH); // Depth buffer setup. gl.glClearDepthf(1.0f); // Enables depth testing. gl.glEnable(GL10.GL_DEPTH_TEST); // The type of depth testing to do. gl.glDepthFunc(GL10.GL_LEQUAL); // Really nice perspective calculations. gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); //gl.glEnable(GL10.GL_DITHER); } /* * (non-Javadoc) * * @see * android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition. * khronos.opengles.GL10) */ public void onDrawFrame(GL10 gl) { if( Build.VERSION.SDK_INT >= 7 ){ framecount++; if (framecount == 10) { antikythera2.fps = (float)(framecount*1000)/(float)(System.currentTimeMillis()-timestamp); timestamp = System.currentTimeMillis(); framecount = 0; } else if (antikythera2.fps == 0f) { if (timestamp == 0) { timestamp = System.currentTimeMillis(); } else { framecount = 0; antikythera2.fps = (float)(1000f/(float)(System.currentTimeMillis()-timestamp) ); timestamp = System.currentTimeMillis(); } } } else { framecount++; if (framecount == 10) { antikythera2_nomulti.fps = (float)(framecount*1000)/(float)(System.currentTimeMillis()-timestamp); timestamp = System.currentTimeMillis(); framecount = 0; } else if (antikythera2.fps == 0f) { if (timestamp == 0) { timestamp = System.currentTimeMillis(); } else { framecount = 0; antikythera2_nomulti.fps = (float)(1000f/(float)(System.currentTimeMillis()-timestamp) ); timestamp = System.currentTimeMillis(); } } } //timestamp = System.currentTimeMillis(); double rmik=4.0; double rmeg, cosx; //double kentro_k1 = 0.0; //x=0, y=0 double kentro_k2 = gearpos[21][0] - gearpos[20][0]; //x=;, y=0 double kentro_k[] = {0.0, 0.0}; //κεντρο πυρρου k gl.glDisable(GL10.GL_LIGHTING); // Clears the screen and depth buffer. gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // Replace the current matrix with the identity matrix gl.glLoadIdentity(); // Translates 4 units into the screen. if (position_x > 100f) { position_x = 100f;} if (position_x <-100f) { position_x =-100f;} if (position_y > 100f) { position_y = 100f;} if (position_y <-100f) { position_y =-100f;} gl.glTranslatef(position_x, position_y, -120f + zoomfac); gl.glRotatef( fullrotate_x, 1f, 0f, 0f); gl.glRotatef( fullrotate_y, 0f, 1f, 0f); gl.glRotatef( fullrotate_z, 0f, 0f, 1f); // Draw our gears int i; for (i=0;i<num_gears;i++) { gl.glPushMatrix(); gl.glTranslatef(gearpos[i][0],gearpos[i][1], gearpos[i][2]); //Κέντρο γραναζιού if(i==num_gears-1) { //Αν το γρανάζι είναι η μανιβέλα να πάρει σωστή θέση (κάθετο στα υπόλοιπα) gl.glRotatef( 90f, 0.0f, 1.0f, 0.0f); } if((i==21)||(i==2)||(i==12)||(i==7))//Το γρανάζι του Ιππάρχου { kentro_k[0]= rmik * Math.cos((angle ) * M_PI / 180.0); kentro_k[1]= rmik * Math.sin((angle ) * M_PI / 180.0); //Απόσταση πύρρου με κέντρο k2 rmeg = Math.sqrt(Math.pow((kentro_k[0]-kentro_k2),2) + Math.pow(kentro_k[1],2)); //Ταχύτητα k2 = ταχύτητα πύρρου / απόσταση cosx = (rmeg*rmeg + rmik*rmik - kentro_k2*kentro_k2) / (2 * rmik * rmeg); if((i==21)||(i==2)){ gearpos[i][3] = (float)( (gearpos[20][3] * rmik * cosx) / (rmeg) ); if(i==21) { pointer_pos[1][3]= gearpos[i][3]; } } else { gearpos[i][3]= (float)( -(gearpos[20][3] * rmik * cosx) / (rmeg) ); } } if (!Preferences.rotate_backwards) { startangle[i] -= Preferences.rotation_speed * gearpos[i][3]; } else { startangle[i] += Preferences.rotation_speed * gearpos[i][3]; } gl.glRotatef( startangle[i], 0f, 0f, 1f); //Περιστροφή γραναζιού gears[i].draw(gl, (int)gearpos[i][4]); gl.glPopMatrix(); } //axles for (i=0;i<num_axles;i++) { gl.glPushMatrix(); if(axle_differential[i]!=0) { //Αν ανήκει στα διαφορικά γρανάζια του μηχανισμού Περιστροφή διαφορικού if(i==num_axles-1) {//Αν είναι το χερούλι της μανιβέλας gl.glTranslatef( axlepos[i-1][0], axlepos[i-1][1], axlepos[i-1][2]); //Κέντρο κύκλου περιστροφής if (!Preferences.rotate_backwards) { axle_differential_angle[i] -= Preferences.rotation_speed * axle_differential[i]; } else { axle_differential_angle[i] += Preferences.rotation_speed * axle_differential[i]; } gl.glRotatef( axle_differential_angle[i], 1.0f, 0.0f, 0.0f); } else { //Οποιόσδήποτε άλλος άξονας γραναζιού (ΙΠΠΑΡΧΟΣ Κ1) gl.glTranslatef( gearpos[20][0], gearpos[20][1], 0.0f); //Κέντρο κύκλου περιστροφής if (!Preferences.rotate_backwards) { axle_differential_angle[i] -= Preferences.rotation_speed * axle_differential[i]; } else { axle_differential_angle[i] += Preferences.rotation_speed * axle_differential[i]; } gl.glRotatef( axle_differential_angle[i], 0.0f, 0.0f, 1.0f); } } if(i==9) { gl.glTranslatef( 4f,0f, axlepos[i][2]); } //Κέντρο άξονα else { gl.glTranslatef(axlepos[i][0],axlepos[i][1], axlepos[i][2]);} //Κέντρο γραναζιού if(i>=num_axles-3) { //Αν είναι η μανιβέλα να πάρει σωστή θέση (κάθετο στα υπόλοιπα) gl.glRotatef( 90f, 0.0f, 1.0f, 0.0f); } if (!Preferences.rotate_backwards) { axle_angle[i] -= Preferences.rotation_speed * axlepos[i][3]; } else { axle_angle[i] += Preferences.rotation_speed * axlepos[i][3]; } gl.glRotatef( axle_angle[i], 0f, 0f, 1f); //Περιστροφή γραναζιού axles[i].draw(gl, (int)axlepos[i][4]); gl.glPopMatrix(); } //pointers for (i=0;i<num_pointers;i++) { gl.glPushMatrix(); gl.glTranslatef( pointer_pos[i][0], pointer_pos[i][1], pointer_pos[i][2]); //Κέντρο δείκτη //Περιστροφή δείκτη γύρω απ' τον άξονά του. Ο συντελεστής του angle είναι η ταχύτητα περιστροφής if (!Preferences.rotate_backwards) { pointer_angle[i] -= Preferences.rotation_speed * pointer_pos[i][3]; } else { pointer_angle[i] += Preferences.rotation_speed * pointer_pos[i][3]; } gl.glRotatef(pointer_angle[i] , 0.0f, 0.0f, 1.0f); pointers[i].draw(gl, (int)pointer_pos[i][4]); pointerbase.draw(gl, (int)pointer_pos[i][4]); gl.glPopMatrix(); } //plates if (Preferences.plate_visibility) { for (i=0;i<2;i++) { plates[i].draw(gl); } } if (!Preferences.rotate_backwards) { angle -= Preferences.rotation_speed; } else { angle += Preferences.rotation_speed; } } /* * (non-Javadoc) * * @see * android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition * .khronos.opengles.GL10, int, int) */ public void onSurfaceChanged(GL10 gl, int width, int height) { if (Preferences.plate_visibility) { if( Build.VERSION.SDK_INT >= 7 ){ bitmap = antikythera2.bitmap; } else { bitmap = antikythera2_nomulti.bitmap; } gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); gl.glDisable(GL10.GL_TEXTURE_2D); } // Sets the current view port to the new size. gl.glViewport(0, 0, width, height); // Select the projection matrix gl.glMatrixMode(GL10.GL_PROJECTION); // Reset the projection matrix gl.glLoadIdentity(); // Calculate the aspect ratio of the window GLU.gluPerspective(gl, 75.0f, (float) width / (float) height, 0.1f, 750.0f); // Select the modelview matrix gl.glMatrixMode(GL10.GL_MODELVIEW); // Reset the modelview matrix gl.glLoadIdentity(); } }
fivasim/Antikythera-Simulation
Antikythera/src/com/fivasim/antikythera/OpenGLRenderer2.java
4,392
//Οποιόσδήποτε άλλος άξονας γραναζιού (ΙΠΠΑΡΧΟΣ Κ1)
line_comment
el
package com.fivasim.antikythera; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.graphics.Bitmap; import android.opengl.GLU; import android.opengl.GLUtils; import android.opengl.GLSurfaceView.Renderer; import android.os.Build; import static com.fivasim.antikythera.Initial2.*; public class OpenGLRenderer2 implements Renderer { private Gear gears[] = new Gear[num_gears]; private Gear axles[] = new Gear[num_axles]; private Pointer pointers[] = new Pointer[num_pointers]; private Gear pointerbase = new Gear( new float[]{0f, 1.5f, 1f, 50f, 0f, 0f} ); private Plate plates[] = new Plate[2]; private static int framecount = 0; public static float curX = 0f; public static float curY = 0f; public static float curX1 = 0f; public static float curY1 = 0f; public static float curDist = 0f; public static int touchmode = 0; public static float angle = 0f; public static float fullrotate_x = 0f; public static float fullrotate_y = 0f; public static float fullrotate_z = 0f; public static float position_x = 0f; public static float position_y = 0f; public static float zoomfac = 0f; public static long timestamp = System.currentTimeMillis(); private Bitmap bitmap; public OpenGLRenderer2() { int i; // Initialize our gears. for (i=0;i<num_gears;i++) { gears[i] = new Gear(geardata[i]); } for (i=0;i<num_axles;i++) { axles[i] = new Gear(axledata[i]); } for (i=0;i<num_pointers;i++) { pointers[i] = new Pointer( pointer_len[i], pointer_pos[i]); } plates[0] = new Plate(60.0f, 40.0f, 25.0f); plates[1] = new Plate(60.0f, 40.0f,-41.0f); } /* * (non-Javadoc) * * @see * android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition * .khronos.opengles.GL10, javax.microedition.khronos.egl.EGLConfig) */ public void onSurfaceCreated(GL10 gl, EGLConfig config) { // Set the background color to black ( rgba ). gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Enable Smooth Shading, default not really needed. gl.glShadeModel(GL10.GL_SMOOTH); // Depth buffer setup. gl.glClearDepthf(1.0f); // Enables depth testing. gl.glEnable(GL10.GL_DEPTH_TEST); // The type of depth testing to do. gl.glDepthFunc(GL10.GL_LEQUAL); // Really nice perspective calculations. gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); //gl.glEnable(GL10.GL_DITHER); } /* * (non-Javadoc) * * @see * android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition. * khronos.opengles.GL10) */ public void onDrawFrame(GL10 gl) { if( Build.VERSION.SDK_INT >= 7 ){ framecount++; if (framecount == 10) { antikythera2.fps = (float)(framecount*1000)/(float)(System.currentTimeMillis()-timestamp); timestamp = System.currentTimeMillis(); framecount = 0; } else if (antikythera2.fps == 0f) { if (timestamp == 0) { timestamp = System.currentTimeMillis(); } else { framecount = 0; antikythera2.fps = (float)(1000f/(float)(System.currentTimeMillis()-timestamp) ); timestamp = System.currentTimeMillis(); } } } else { framecount++; if (framecount == 10) { antikythera2_nomulti.fps = (float)(framecount*1000)/(float)(System.currentTimeMillis()-timestamp); timestamp = System.currentTimeMillis(); framecount = 0; } else if (antikythera2.fps == 0f) { if (timestamp == 0) { timestamp = System.currentTimeMillis(); } else { framecount = 0; antikythera2_nomulti.fps = (float)(1000f/(float)(System.currentTimeMillis()-timestamp) ); timestamp = System.currentTimeMillis(); } } } //timestamp = System.currentTimeMillis(); double rmik=4.0; double rmeg, cosx; //double kentro_k1 = 0.0; //x=0, y=0 double kentro_k2 = gearpos[21][0] - gearpos[20][0]; //x=;, y=0 double kentro_k[] = {0.0, 0.0}; //κεντρο πυρρου k gl.glDisable(GL10.GL_LIGHTING); // Clears the screen and depth buffer. gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // Replace the current matrix with the identity matrix gl.glLoadIdentity(); // Translates 4 units into the screen. if (position_x > 100f) { position_x = 100f;} if (position_x <-100f) { position_x =-100f;} if (position_y > 100f) { position_y = 100f;} if (position_y <-100f) { position_y =-100f;} gl.glTranslatef(position_x, position_y, -120f + zoomfac); gl.glRotatef( fullrotate_x, 1f, 0f, 0f); gl.glRotatef( fullrotate_y, 0f, 1f, 0f); gl.glRotatef( fullrotate_z, 0f, 0f, 1f); // Draw our gears int i; for (i=0;i<num_gears;i++) { gl.glPushMatrix(); gl.glTranslatef(gearpos[i][0],gearpos[i][1], gearpos[i][2]); //Κέντρο γραναζιού if(i==num_gears-1) { //Αν το γρανάζι είναι η μανιβέλα να πάρει σωστή θέση (κάθετο στα υπόλοιπα) gl.glRotatef( 90f, 0.0f, 1.0f, 0.0f); } if((i==21)||(i==2)||(i==12)||(i==7))//Το γρανάζι του Ιππάρχου { kentro_k[0]= rmik * Math.cos((angle ) * M_PI / 180.0); kentro_k[1]= rmik * Math.sin((angle ) * M_PI / 180.0); //Απόσταση πύρρου με κέντρο k2 rmeg = Math.sqrt(Math.pow((kentro_k[0]-kentro_k2),2) + Math.pow(kentro_k[1],2)); //Ταχύτητα k2 = ταχύτητα πύρρου / απόσταση cosx = (rmeg*rmeg + rmik*rmik - kentro_k2*kentro_k2) / (2 * rmik * rmeg); if((i==21)||(i==2)){ gearpos[i][3] = (float)( (gearpos[20][3] * rmik * cosx) / (rmeg) ); if(i==21) { pointer_pos[1][3]= gearpos[i][3]; } } else { gearpos[i][3]= (float)( -(gearpos[20][3] * rmik * cosx) / (rmeg) ); } } if (!Preferences.rotate_backwards) { startangle[i] -= Preferences.rotation_speed * gearpos[i][3]; } else { startangle[i] += Preferences.rotation_speed * gearpos[i][3]; } gl.glRotatef( startangle[i], 0f, 0f, 1f); //Περιστροφή γραναζιού gears[i].draw(gl, (int)gearpos[i][4]); gl.glPopMatrix(); } //axles for (i=0;i<num_axles;i++) { gl.glPushMatrix(); if(axle_differential[i]!=0) { //Αν ανήκει στα διαφορικά γρανάζια του μηχανισμού Περιστροφή διαφορικού if(i==num_axles-1) {//Αν είναι το χερούλι της μανιβέλας gl.glTranslatef( axlepos[i-1][0], axlepos[i-1][1], axlepos[i-1][2]); //Κέντρο κύκλου περιστροφής if (!Preferences.rotate_backwards) { axle_differential_angle[i] -= Preferences.rotation_speed * axle_differential[i]; } else { axle_differential_angle[i] += Preferences.rotation_speed * axle_differential[i]; } gl.glRotatef( axle_differential_angle[i], 1.0f, 0.0f, 0.0f); } else { //Οποιόσδήποτε άλλος<SUF> gl.glTranslatef( gearpos[20][0], gearpos[20][1], 0.0f); //Κέντρο κύκλου περιστροφής if (!Preferences.rotate_backwards) { axle_differential_angle[i] -= Preferences.rotation_speed * axle_differential[i]; } else { axle_differential_angle[i] += Preferences.rotation_speed * axle_differential[i]; } gl.glRotatef( axle_differential_angle[i], 0.0f, 0.0f, 1.0f); } } if(i==9) { gl.glTranslatef( 4f,0f, axlepos[i][2]); } //Κέντρο άξονα else { gl.glTranslatef(axlepos[i][0],axlepos[i][1], axlepos[i][2]);} //Κέντρο γραναζιού if(i>=num_axles-3) { //Αν είναι η μανιβέλα να πάρει σωστή θέση (κάθετο στα υπόλοιπα) gl.glRotatef( 90f, 0.0f, 1.0f, 0.0f); } if (!Preferences.rotate_backwards) { axle_angle[i] -= Preferences.rotation_speed * axlepos[i][3]; } else { axle_angle[i] += Preferences.rotation_speed * axlepos[i][3]; } gl.glRotatef( axle_angle[i], 0f, 0f, 1f); //Περιστροφή γραναζιού axles[i].draw(gl, (int)axlepos[i][4]); gl.glPopMatrix(); } //pointers for (i=0;i<num_pointers;i++) { gl.glPushMatrix(); gl.glTranslatef( pointer_pos[i][0], pointer_pos[i][1], pointer_pos[i][2]); //Κέντρο δείκτη //Περιστροφή δείκτη γύρω απ' τον άξονά του. Ο συντελεστής του angle είναι η ταχύτητα περιστροφής if (!Preferences.rotate_backwards) { pointer_angle[i] -= Preferences.rotation_speed * pointer_pos[i][3]; } else { pointer_angle[i] += Preferences.rotation_speed * pointer_pos[i][3]; } gl.glRotatef(pointer_angle[i] , 0.0f, 0.0f, 1.0f); pointers[i].draw(gl, (int)pointer_pos[i][4]); pointerbase.draw(gl, (int)pointer_pos[i][4]); gl.glPopMatrix(); } //plates if (Preferences.plate_visibility) { for (i=0;i<2;i++) { plates[i].draw(gl); } } if (!Preferences.rotate_backwards) { angle -= Preferences.rotation_speed; } else { angle += Preferences.rotation_speed; } } /* * (non-Javadoc) * * @see * android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition * .khronos.opengles.GL10, int, int) */ public void onSurfaceChanged(GL10 gl, int width, int height) { if (Preferences.plate_visibility) { if( Build.VERSION.SDK_INT >= 7 ){ bitmap = antikythera2.bitmap; } else { bitmap = antikythera2_nomulti.bitmap; } gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); gl.glDisable(GL10.GL_TEXTURE_2D); } // Sets the current view port to the new size. gl.glViewport(0, 0, width, height); // Select the projection matrix gl.glMatrixMode(GL10.GL_PROJECTION); // Reset the projection matrix gl.glLoadIdentity(); // Calculate the aspect ratio of the window GLU.gluPerspective(gl, 75.0f, (float) width / (float) height, 0.1f, 750.0f); // Select the modelview matrix gl.glMatrixMode(GL10.GL_MODELVIEW); // Reset the modelview matrix gl.glLoadIdentity(); } }
7140_1
public class Seller extends User { private String sellerID; private double commissionRate; public Seller(String username, String name, String surname, String sellerID, double commissionRate, String password) { super(username, name, surname, "seller",password); this.sellerID = sellerID; this.commissionRate = commissionRate; } // Getters and setters for additional attributes public String getSellerID() { return sellerID; } public void setSellerID(String sellerID) { this.sellerID = sellerID; } public double getCommissionRate() { return commissionRate; } public void setCommissionRate(double commissionRate) { this.commissionRate = commissionRate; } // Additional methods public void registerNewClient(Client client) { // Λογική καταχώρησης νέου πελάτη System.out.println("Ο πωλητής " + username + " καταχώρησε τον πελάτη " + client.getUsername()); } public void issueInvoice(Client client, double amount) { // Λογική έκδοσης τιμολογίου System.out.println("Ο πωλητής " + username + " εξέδωσε τιμολόγιο ύψους " + amount + " στον πελάτη " + client.getUsername()); } public void changeClientPlan(Client client, String newPlan) { // Λογική αλλαγής προγράμματος πελάτη System.out.println("Ο πωλητής " + username + " άλλαξε το πρόγραμμα του πελάτη " + client.getUsername() + " σε " + newPlan); } }
foros7/ProgramatismosDiadiktioErgasia1
src/Seller.java
500
// Λογική καταχώρησης νέου πελάτη
line_comment
el
public class Seller extends User { private String sellerID; private double commissionRate; public Seller(String username, String name, String surname, String sellerID, double commissionRate, String password) { super(username, name, surname, "seller",password); this.sellerID = sellerID; this.commissionRate = commissionRate; } // Getters and setters for additional attributes public String getSellerID() { return sellerID; } public void setSellerID(String sellerID) { this.sellerID = sellerID; } public double getCommissionRate() { return commissionRate; } public void setCommissionRate(double commissionRate) { this.commissionRate = commissionRate; } // Additional methods public void registerNewClient(Client client) { // Λογική καταχώρησης<SUF> System.out.println("Ο πωλητής " + username + " καταχώρησε τον πελάτη " + client.getUsername()); } public void issueInvoice(Client client, double amount) { // Λογική έκδοσης τιμολογίου System.out.println("Ο πωλητής " + username + " εξέδωσε τιμολόγιο ύψους " + amount + " στον πελάτη " + client.getUsername()); } public void changeClientPlan(Client client, String newPlan) { // Λογική αλλαγής προγράμματος πελάτη System.out.println("Ο πωλητής " + username + " άλλαξε το πρόγραμμα του πελάτη " + client.getUsername() + " σε " + newPlan); } }
1263_13
package unipi.OOP.mathima5.anonymization; public class Main { /* Methods και Class που θα χρησιμοποιηθούν μέσα στην main. */ // Method doSomethingWithStudent() με argument ένα Student object. static void doSomethingWithStudent(Student s) { System.out.println(s); s.sayHello(); } // Static class SomeClass που κάνει extend την class Student και προσθέτει τη method sayHi_1(). static class SomeClass extends Student { void sayHi_1(){ System.out.println("Hi 1 from SomeClass"); } } // Method doSomethingWithAnyoneThatReads() με argument ένα IRead interface. static void doSomethingWithAnyoneThatReads(IRead reader){ reader.doRead("Java"); } /* Main method και χρήση anonymous classes and methods */ public static void main(String[] args) { // Δημιουργία του object s1 της class Student. Student s1 = new Student(); s1.am = "mppl1111"; doSomethingWithStudent(s1); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend την class Student και χρησιμοποιεί τον δεύτερο constructor της class Student. doSomethingWithStudent( new Student("mppl2222", "[email protected]") ); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend την class Student, χρησιμοποιεί τον δεύτερο constructor της και καλεί την method sayHello() της class Student. // Δεν μπορώ να κάνω χρήση της method doSomethingWithStudent() διότι δέχεται μόνο Student objects. new Student("mppl3333", "[email protected]").sayHello(); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend τη class SomeClass και καλεί τη method sayHi_1(). new SomeClass().sayHi_1(); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend την class Student, χρησιμοποιεί τον δεύτερο constructor της class Student και προσθέτει τη method sayHi_2(). // Δεν μπορώ να καλέσω τη method sayHi_2() καθώς το object που δημιουργείται είναι ανώνυμο, μέσω της doSomethingWithStudent με αποτέλεσμα να μην έχω τη δυνατότητα να καλέσω κάποια μέθοδο του object. doSomethingWithStudent( new Student("mppl4444", "[email protected]"){ void sayHi_2(){ System.out.println("Hi 2 from Student with AM: "+am+" and email: "+email); } } ); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend τη class Student, χρησιμοποιεί τον δεύτερο constructor της class Student, προσθέτει τη method sayHi_3() και τη χρησιμοποιεί. new Student("mppl5555", "[email protected]"){ void sayHi_3(){ System.out.println("Hi 3 from Student with AM: "+am+" and email: "+email); } }.sayHi_3(); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend την class Student, χρησιμοποιεί τον δεύτερο constructor της class Student, και κάνει override τη method sayHello(). doSomethingWithStudent( new Student("mppl6666", "[email protected]"){ @Override void sayHello(){ System.out.println("Extended Hello from Student with AM: "+am+" and email: "+email); } } ); // Το αντικείμενο s2 της κλάσεις Student. // Μπορούμε το s2 να χρησιμοποιηθεί ως argument στην method doSomethingWithAnyoneThatReads() γιατί η class Student κάνει implement το IREad interface. Student s2 = new Student(); doSomethingWithAnyoneThatReads(s2); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, η οποία κάνει implement το IRead interface. doSomethingWithAnyoneThatReads( new IRead() { @Override public void doRead(String text) { System.out.println("I am Student 2 that reads "+text); } } ); // Δημιουργία μεταβλητής που περιέχει ανώνυμο object, μιας ανώνυμης class, η οποία κάνει implement το IRead interface. IRead r1 = new IRead() { @Override public void doRead(String text) { System.out.println("I am Student 3 that reads "+text); } }; doSomethingWithAnyoneThatReads(r1); } }
fotistsiou/msc_informatics
2nd_semester/antikimenostrefis_programmatismos/mathima5/unipi/OOP/mathima5/anonymization/Main.java
1,740
// Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend την class Student, χρησιμοποιεί τον δεύτερο constructor της class Student, και κάνει override τη method sayHello().
line_comment
el
package unipi.OOP.mathima5.anonymization; public class Main { /* Methods και Class που θα χρησιμοποιηθούν μέσα στην main. */ // Method doSomethingWithStudent() με argument ένα Student object. static void doSomethingWithStudent(Student s) { System.out.println(s); s.sayHello(); } // Static class SomeClass που κάνει extend την class Student και προσθέτει τη method sayHi_1(). static class SomeClass extends Student { void sayHi_1(){ System.out.println("Hi 1 from SomeClass"); } } // Method doSomethingWithAnyoneThatReads() με argument ένα IRead interface. static void doSomethingWithAnyoneThatReads(IRead reader){ reader.doRead("Java"); } /* Main method και χρήση anonymous classes and methods */ public static void main(String[] args) { // Δημιουργία του object s1 της class Student. Student s1 = new Student(); s1.am = "mppl1111"; doSomethingWithStudent(s1); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend την class Student και χρησιμοποιεί τον δεύτερο constructor της class Student. doSomethingWithStudent( new Student("mppl2222", "[email protected]") ); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend την class Student, χρησιμοποιεί τον δεύτερο constructor της και καλεί την method sayHello() της class Student. // Δεν μπορώ να κάνω χρήση της method doSomethingWithStudent() διότι δέχεται μόνο Student objects. new Student("mppl3333", "[email protected]").sayHello(); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend τη class SomeClass και καλεί τη method sayHi_1(). new SomeClass().sayHi_1(); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend την class Student, χρησιμοποιεί τον δεύτερο constructor της class Student και προσθέτει τη method sayHi_2(). // Δεν μπορώ να καλέσω τη method sayHi_2() καθώς το object που δημιουργείται είναι ανώνυμο, μέσω της doSomethingWithStudent με αποτέλεσμα να μην έχω τη δυνατότητα να καλέσω κάποια μέθοδο του object. doSomethingWithStudent( new Student("mppl4444", "[email protected]"){ void sayHi_2(){ System.out.println("Hi 2 from Student with AM: "+am+" and email: "+email); } } ); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, που κάνει έμμεσα extend τη class Student, χρησιμοποιεί τον δεύτερο constructor της class Student, προσθέτει τη method sayHi_3() και τη χρησιμοποιεί. new Student("mppl5555", "[email protected]"){ void sayHi_3(){ System.out.println("Hi 3 from Student with AM: "+am+" and email: "+email); } }.sayHi_3(); // Δημιουργία ανώνυμου<SUF> doSomethingWithStudent( new Student("mppl6666", "[email protected]"){ @Override void sayHello(){ System.out.println("Extended Hello from Student with AM: "+am+" and email: "+email); } } ); // Το αντικείμενο s2 της κλάσεις Student. // Μπορούμε το s2 να χρησιμοποιηθεί ως argument στην method doSomethingWithAnyoneThatReads() γιατί η class Student κάνει implement το IREad interface. Student s2 = new Student(); doSomethingWithAnyoneThatReads(s2); // Δημιουργία ανώνυμου object, μιας ανώνυμης class, η οποία κάνει implement το IRead interface. doSomethingWithAnyoneThatReads( new IRead() { @Override public void doRead(String text) { System.out.println("I am Student 2 that reads "+text); } } ); // Δημιουργία μεταβλητής που περιέχει ανώνυμο object, μιας ανώνυμης class, η οποία κάνει implement το IRead interface. IRead r1 = new IRead() { @Override public void doRead(String text) { System.out.println("I am Student 3 that reads "+text); } }; doSomethingWithAnyoneThatReads(r1); } }
10602_0
package gr.aueb.cf.ch3; import java.util.Scanner; /** *Το πρόγραμμα λαμβάνει ένα έτος από το stdin * και ελέγχει αν το έτος είναι δίσεκτο. * * @author Grigoris */ public class LeapYear { public static void main(String[] args) { Scanner in = new Scanner(System.in); int year = 0; System.out.println("Please insert a year:"); year= in.nextInt(); if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){ System.out.printf("%d is a Leap Year",year); }else { System.out.printf("%d isn't a Leap Year", year); } } }
g11latsis/CodingFactoryTestBed
src/gr/aueb/cf/ch3/LeapYear.java
238
/** *Το πρόγραμμα λαμβάνει ένα έτος από το stdin * και ελέγχει αν το έτος είναι δίσεκτο. * * @author Grigoris */
block_comment
el
package gr.aueb.cf.ch3; import java.util.Scanner; /** *Το πρόγραμμα λαμβάνει<SUF>*/ public class LeapYear { public static void main(String[] args) { Scanner in = new Scanner(System.in); int year = 0; System.out.println("Please insert a year:"); year= in.nextInt(); if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){ System.out.printf("%d is a Leap Year",year); }else { System.out.printf("%d isn't a Leap Year", year); } } }
4974_0
/* Θέμα: Εργασία 1 Δικτυών Υπολογιστών Ονοματεπώνυμο: Κωνσταντόπουλος Γεώργιος ΑΕΜ: 8173 */ /* Main class where the magic happens. Other classes are used to * help organize the project and make it more readable */ import java.text.SimpleDateFormat; import java.util.Date; import ithakimodem.Modem; public class virtualModem{ public static void main(String[] param){ (new virtualModem()).rx(); } public void sendToModem(Modem modem, String command){ byte[] commandBytes = command.getBytes(); System.out.print("[+] Command Issued: "+command); System.out.println("[+] Bytes passed: "+commandBytes); System.out.print("\n"); modem.write(commandBytes); } public int getSpeed(){return 80000;} public void rx() { /* Request Codes Pool * from http://ithaki.eng.auth.gr/netlab/ */ imageCamera camera = new imageCamera(); gpsMap gps = new gpsMap(); echoPacket echo = new echoPacket(); Ack ack = new Ack(); Coords coordsFetch = new Coords(); Modem modem; modem = new Modem(); modem.setSpeed(getSpeed()); modem.setTimeout(2000); modem.open("ithaki"); final String echo_command = "E9895\r"; final String img_command = "M6213\r"; final String gps_command = "P4737=1000099\r"; final String noise_command = "G6041\r"; String gpsmapCoords=""; String gmaps_command = gps_command.substring(0, 5); final String ack_command = "Q6532\r"; boolean debugCamera = false; boolean debugNoise = false; boolean debugMaps = false; boolean debugGps = false; boolean debugCoords = false; boolean debugEcho = true; boolean debugAck = true; boolean imgSent = false; boolean gpsSent = false; boolean echoSent = false; boolean ackInfo = false; if (debugCamera) { //Camera image request try { String fileName = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss'.jpeg'").format(new Date()); imgSent = camera.Image(modem, img_command, imgSent, fileName); if (imgSent){ System.out.println("cameraNoNoise.jpeg file successfully written!\n"); } }catch (Exception x) { x.printStackTrace(); } } //Camera image request imgSent = false; if (debugNoise) { try { String fileName = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss'.jpeg'").format(new Date()); imgSent = camera.Image(modem, noise_command, imgSent, fileName); if (imgSent){ System.out.println("cameraNoise.jpeg file successfully written!\n"); } }catch (Exception x) { x.printStackTrace(); } } //Gps Request if (debugGps){ gpsSent = gps.Gps(modem, gps_command, gpsSent); String gps_command1 = "P4737R=1010099\r"; gpsSent = false; gpsSent = gps.Gps(modem, gps_command1, gpsSent); gps_command1 = "P4737R=1020099\r"; gpsSent = false; gpsSent = gps.Gps(modem, gps_command1, gpsSent); gps_command1 = "P4737R=1030099\r"; gpsSent = false; gpsSent = gps.Gps(modem, gps_command1, gpsSent); gps_command1 = "P4737R=1040099\r"; gpsSent = false; gpsSent = gps.Gps(modem, gps_command1, gpsSent); } if (gpsSent)System.out.println("GPS file with Coordinates succesffully written!"); //Echo request. if (debugEcho)echoSent = echo.Echo(modem, echo_command); if (echoSent)System.out.print("File with response times between each echo successfully written. " + "Import the .txt file's data to Matlab/Excel like software to convert to graph.\n"); //Modify gmaps_command to include 4 traces. if (debugCoords){ gpsmapCoords=coordsFetch.coords(); gmaps_command = gmaps_command+gpsmapCoords+"\r"; } else{ gmaps_command = gmaps_command+"\r"; } //Set imgSent to false from previous calls, use gmaps_command to get image with 4 traces on it. imgSent = false; if (debugMaps) { //Camera image request try { ; //System.out.println("[*] DEBUG: PRINTING GMAPS: "+gmaps_command); String fileName = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss'.jpeg'").format(new Date()); imgSent = camera.Image(modem, gmaps_command, imgSent, fileName); if (imgSent){ System.out.println("[+] gMaps.jpeg file successfully written!\n"); } }catch (Exception x) { x.printStackTrace(); } } //ackInfo = True if the xor matches the decimal number. If ackInfo is false, send NACK command. if (debugAck)ackInfo = ack.ackError(modem,ack_command,ackInfo); //Close connection System.out.println("Done! Exiting..."); modem.close(); } }
gakonst/University_Projects
Computer_Networks1/virtualModem.java
1,506
/* Θέμα: Εργασία 1 Δικτυών Υπολογιστών Ονοματεπώνυμο: Κωνσταντόπουλος Γεώργιος ΑΕΜ: 8173 */
block_comment
el
/* Θέμα: <SUF>*/ /* Main class where the magic happens. Other classes are used to * help organize the project and make it more readable */ import java.text.SimpleDateFormat; import java.util.Date; import ithakimodem.Modem; public class virtualModem{ public static void main(String[] param){ (new virtualModem()).rx(); } public void sendToModem(Modem modem, String command){ byte[] commandBytes = command.getBytes(); System.out.print("[+] Command Issued: "+command); System.out.println("[+] Bytes passed: "+commandBytes); System.out.print("\n"); modem.write(commandBytes); } public int getSpeed(){return 80000;} public void rx() { /* Request Codes Pool * from http://ithaki.eng.auth.gr/netlab/ */ imageCamera camera = new imageCamera(); gpsMap gps = new gpsMap(); echoPacket echo = new echoPacket(); Ack ack = new Ack(); Coords coordsFetch = new Coords(); Modem modem; modem = new Modem(); modem.setSpeed(getSpeed()); modem.setTimeout(2000); modem.open("ithaki"); final String echo_command = "E9895\r"; final String img_command = "M6213\r"; final String gps_command = "P4737=1000099\r"; final String noise_command = "G6041\r"; String gpsmapCoords=""; String gmaps_command = gps_command.substring(0, 5); final String ack_command = "Q6532\r"; boolean debugCamera = false; boolean debugNoise = false; boolean debugMaps = false; boolean debugGps = false; boolean debugCoords = false; boolean debugEcho = true; boolean debugAck = true; boolean imgSent = false; boolean gpsSent = false; boolean echoSent = false; boolean ackInfo = false; if (debugCamera) { //Camera image request try { String fileName = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss'.jpeg'").format(new Date()); imgSent = camera.Image(modem, img_command, imgSent, fileName); if (imgSent){ System.out.println("cameraNoNoise.jpeg file successfully written!\n"); } }catch (Exception x) { x.printStackTrace(); } } //Camera image request imgSent = false; if (debugNoise) { try { String fileName = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss'.jpeg'").format(new Date()); imgSent = camera.Image(modem, noise_command, imgSent, fileName); if (imgSent){ System.out.println("cameraNoise.jpeg file successfully written!\n"); } }catch (Exception x) { x.printStackTrace(); } } //Gps Request if (debugGps){ gpsSent = gps.Gps(modem, gps_command, gpsSent); String gps_command1 = "P4737R=1010099\r"; gpsSent = false; gpsSent = gps.Gps(modem, gps_command1, gpsSent); gps_command1 = "P4737R=1020099\r"; gpsSent = false; gpsSent = gps.Gps(modem, gps_command1, gpsSent); gps_command1 = "P4737R=1030099\r"; gpsSent = false; gpsSent = gps.Gps(modem, gps_command1, gpsSent); gps_command1 = "P4737R=1040099\r"; gpsSent = false; gpsSent = gps.Gps(modem, gps_command1, gpsSent); } if (gpsSent)System.out.println("GPS file with Coordinates succesffully written!"); //Echo request. if (debugEcho)echoSent = echo.Echo(modem, echo_command); if (echoSent)System.out.print("File with response times between each echo successfully written. " + "Import the .txt file's data to Matlab/Excel like software to convert to graph.\n"); //Modify gmaps_command to include 4 traces. if (debugCoords){ gpsmapCoords=coordsFetch.coords(); gmaps_command = gmaps_command+gpsmapCoords+"\r"; } else{ gmaps_command = gmaps_command+"\r"; } //Set imgSent to false from previous calls, use gmaps_command to get image with 4 traces on it. imgSent = false; if (debugMaps) { //Camera image request try { ; //System.out.println("[*] DEBUG: PRINTING GMAPS: "+gmaps_command); String fileName = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss'.jpeg'").format(new Date()); imgSent = camera.Image(modem, gmaps_command, imgSent, fileName); if (imgSent){ System.out.println("[+] gMaps.jpeg file successfully written!\n"); } }catch (Exception x) { x.printStackTrace(); } } //ackInfo = True if the xor matches the decimal number. If ackInfo is false, send NACK command. if (debugAck)ackInfo = ack.ackError(modem,ack_command,ackInfo); //Close connection System.out.println("Done! Exiting..."); modem.close(); } }
7235_2
package Classes; import Servlets.RegisterServlet; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class TeacherMapper implements User { //Inserts student information to database public void register(String id,String name,String surname,String password,String email,byte[] salt) throws SQLException { try{ Dbconnector con = new Dbconnector(); PreparedStatement st = con.connect().prepareStatement("INSERT INTO teachers (teacher_id,name,surname,password,email,salt) VALUES(?,?,?,?,?,?);"); st.setString(1, id); st.setString(2, name); st.setString(3, surname); st.setString(4, password); st.setString(5, email); st.setBytes(6, salt); st.executeUpdate(); st.close(); con.disconnect(); }catch(Exception e){ throw new SQLException("Teacher could not register"); } } //Checks user information public boolean login(String username,String password) throws SQLException { try{ Dbconnector con = new Dbconnector(); PreparedStatement sm = con.connect().prepareStatement("SELECT teacher_id, password, salt FROM teachers where teacher_id = '"+ username +"';"); ResultSet Rs1 = sm.executeQuery(); if(Rs1.next()) { byte[] salt = Rs1.getBytes("salt"); String securePassword = RegisterServlet.SecurePassword(password,salt); /*υπολογισμός του hashed&salted password με βάση τα στοιχεία του χρήστη(pass), και το salt της βάσης, αφού υπάρχει χρήστης με τέτοιο id*/ if(username.equals(Rs1.getString("teacher_id"))&&securePassword.equals(Rs1.getString("password"))) { //έλεγχος έγκυρου password και username con.disconnect(); return true; } }else{ return false; } }catch(Exception e){ throw new SQLException("Incorrect credentials"); } return false; } }
gazdimi/KSDNet
KSDNetWeb/src/Classes/TeacherMapper.java
526
/*υπολογισμός του hashed&salted password με βάση τα στοιχεία του χρήστη(pass), και το salt της βάσης, αφού υπάρχει χρήστης με τέτοιο id*/
block_comment
el
package Classes; import Servlets.RegisterServlet; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class TeacherMapper implements User { //Inserts student information to database public void register(String id,String name,String surname,String password,String email,byte[] salt) throws SQLException { try{ Dbconnector con = new Dbconnector(); PreparedStatement st = con.connect().prepareStatement("INSERT INTO teachers (teacher_id,name,surname,password,email,salt) VALUES(?,?,?,?,?,?);"); st.setString(1, id); st.setString(2, name); st.setString(3, surname); st.setString(4, password); st.setString(5, email); st.setBytes(6, salt); st.executeUpdate(); st.close(); con.disconnect(); }catch(Exception e){ throw new SQLException("Teacher could not register"); } } //Checks user information public boolean login(String username,String password) throws SQLException { try{ Dbconnector con = new Dbconnector(); PreparedStatement sm = con.connect().prepareStatement("SELECT teacher_id, password, salt FROM teachers where teacher_id = '"+ username +"';"); ResultSet Rs1 = sm.executeQuery(); if(Rs1.next()) { byte[] salt = Rs1.getBytes("salt"); String securePassword = RegisterServlet.SecurePassword(password,salt); /*υπολογισμός του hashed&salted<SUF>*/ if(username.equals(Rs1.getString("teacher_id"))&&securePassword.equals(Rs1.getString("password"))) { //έλεγχος έγκυρου password και username con.disconnect(); return true; } }else{ return false; } }catch(Exception e){ throw new SQLException("Incorrect credentials"); } return false; } }
13518_4
package com.example.webapp; import java.util.ArrayList; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * <p>SendMail class.</p> * * @author ismgroup52 * @version $Id: $1.0 */ public class SendMail { /** * <p>send.</p> * * @param from a {@link java.lang.String} object * @param host a {@link java.lang.String} object * @param port a {@link java.lang.String} object * @param customers a {@link java.util.ArrayList} object * @param subject a {@link java.lang.String} object * @param text a {@link java.lang.String} object */ public static void send(String from, String host, String port, ArrayList<Customer> customers, String subject, String text) { Properties props = new Properties(); // Read properties file. props.put("mail.smtp.user", from); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); //SecurityManager security = System.getSecurityManager(); try { Authenticator auth = new SMTPAuthenticator(); Session session = Session.getInstance(props, auth); MimeMessage msg = new MimeMessage(session); msg.setText(text, "UTF-8"); msg.setSubject(subject, "UTF-8"); msg.setFrom(new InternetAddress(from)); for (Customer cust : customers) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(cust.getEmail())); } //Runs in background (κερδίζει περίπου 10 sec) Thread send = new Thread(() -> { try { Transport.send(msg); } catch (MessagingException e) { throw new RuntimeException(e); } }); send.start(); //Transport.send(msg); } catch (Exception mex) { mex.printStackTrace(); } } public static class SMTPAuthenticator extends javax.mail.Authenticator { private final String user = ""; private final String pass = ""; public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pass); } } }
geoartop/Gsystems
src/main/java/com/example/webapp/SendMail.java
680
//Runs in background (κερδίζει περίπου 10 sec)
line_comment
el
package com.example.webapp; import java.util.ArrayList; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * <p>SendMail class.</p> * * @author ismgroup52 * @version $Id: $1.0 */ public class SendMail { /** * <p>send.</p> * * @param from a {@link java.lang.String} object * @param host a {@link java.lang.String} object * @param port a {@link java.lang.String} object * @param customers a {@link java.util.ArrayList} object * @param subject a {@link java.lang.String} object * @param text a {@link java.lang.String} object */ public static void send(String from, String host, String port, ArrayList<Customer> customers, String subject, String text) { Properties props = new Properties(); // Read properties file. props.put("mail.smtp.user", from); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); //SecurityManager security = System.getSecurityManager(); try { Authenticator auth = new SMTPAuthenticator(); Session session = Session.getInstance(props, auth); MimeMessage msg = new MimeMessage(session); msg.setText(text, "UTF-8"); msg.setSubject(subject, "UTF-8"); msg.setFrom(new InternetAddress(from)); for (Customer cust : customers) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(cust.getEmail())); } //Runs in<SUF> Thread send = new Thread(() -> { try { Transport.send(msg); } catch (MessagingException e) { throw new RuntimeException(e); } }); send.start(); //Transport.send(msg); } catch (Exception mex) { mex.printStackTrace(); } } public static class SMTPAuthenticator extends javax.mail.Authenticator { private final String user = ""; private final String pass = ""; public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pass); } } }
4101_11
package game; import javax.swing.SwingUtilities; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.Objects; /** * <p>Φόρτωση του παίκτη και εγγραφή των κινήσεών του στην οθόνη</p> * * @author Team Hack-You * @version 1.0 * @see Entity */ public class Player extends Entity { private int worldx, worldy; static final int speed = 2; private final GamePanel gp; private final KeyHandler keyH; private final int screenX; private final int screenY; /** * Coins collected from player */ private static int coinsCollected = 0; /** * Κινήσεις animation ήττας παίκτη */ private int timesPassed = 0; private String direction; //Μεταβλητές παίκτη private int spriteCounter = 0; private int spriteNum = 1; final Rectangle solidArea = new Rectangle(8, 32, 32, 16); final int solidAreaDefaultX = solidArea.x; final int solidAreaDefaultY = solidArea.y; private boolean collisionOn = false; private static final int outOfBoundsLimit = 15; /** * <p>Getter for the field <code>coinsCollected</code>.</p> * * @return an int */ public static int getCoinsCollected() { return coinsCollected; } /** * <p>Restores <code>coinsCollected</code> value.</p> */ public static void restoreCoinsCollected() { coinsCollected = 0; } /** * <p>Constructor for Player.</p> * * @param gp a {@link game.GamePanel} object * @param keyH a {@link game.KeyHandler} object */ public Player(GamePanel gp, KeyHandler keyH) { this.gp = gp; this.keyH = keyH; screenX = GamePanel.screenWidth / 2 - (GamePanel.tileSize / 2); screenY = GamePanel.screenHeight / 2 - (GamePanel.tileSize / 2); setDefaultValues(); } /** * <p>Καθορισμός αρχικής θέσης παίκτη</p> */ private void setDefaultValues() { worldx = 100; worldy = 50; direction = "down"; } /** * <p>Ανανέωση κίνησης παίκτη</p> */ public void update() { if (keyH.keyIsPressed()) { if (keyH.getUpPressed()) { direction = "up"; } else if (keyH.getDownPressed()) { direction = "down"; } else if (keyH.getLeftPressed()) { direction = "left"; } else { direction = "right"; } collisionOn = false; gp.collisionCheck.checkTile(this); int objIndex = gp.collisionCheck.checkObject(this, true); interact(objIndex); //If collision is false only then can player move on if (!collisionOn) { switch (direction) { case "up": //Εξασφαλίζει ότι ο παίκτης δε θα βγει out of bounds if (worldy < outOfBoundsLimit) { break; } worldy -= speed; break; case "down": worldy += speed; break; case "left": worldx -= speed; break; default: worldx += speed; break; } } spriteCounter++; if (spriteCounter > 5) { if (spriteNum < 9) { spriteNum++; } else { spriteNum = 1; } spriteCounter = 0; } } } /** * <p>Σταθεροποίηση κίνησης παίκτη</p> */ void stabilizePlayer() { keyH.stopMovement(); } /** * <p>Διαχείριση interactions του παίκτη με αντικείμενα μέσα στο παιχνίδι</p> * * @param index θέση του παίκτη στον χάρτη */ private void interact(int index) { if (index != 999) { String objectName = gp.obj.get(index).getName(); if (ButtonSetter.getPlaySound()) { gp.obj.get(index).playSE(); } if (Objects.equals(objectName, "Question")) { //Για να μην κολλήσει το progressBar και η ροή του παιχνιδιού gp.labyrinthFrame.stopBar(); gp.setGameState(GamePanel.pauseState); gp.keyH.setQuizTrig(true); SwingUtilities.invokeLater(() -> new Quiz(gp)); gp.obj.set(index, null); } //Τερματισμός παιχνιδιού σε περίπτωση νίκης if (Objects.equals(objectName, "Exit")) { gp.setGameState(GamePanel.endState); } //Προσθήκη χρόνου (ίσως και πόντων) όταν ο παίκτης βρίσκει coins if (Objects.equals(objectName, "Coin")) { coinsCollected++; gp.obj.set(index, null); } } } /** * <p>Απεικόνιση "θανάτου" παίκτη</p> * * @param g2 a {@link java.awt.Graphics2D} object */ public void drawDeathAnimation(Graphics2D g2) { BufferedImage image; image = death[timesPassed]; setValues(g2, image); } /** * <p>setValues.</p> * * @param g2 a {@link Graphics2D} object * @param image a {@link BufferedImage} object */ private void setValues(Graphics2D g2, BufferedImage image) { int x1 = screenX; int y1 = screenY; if (screenX > worldx) { x1 = worldx; } if (screenY > worldy) { y1 = worldy; } int rightOffsetValue1 = GamePanel.screenWidth - screenX; if (rightOffsetValue1 > gp.WorldWidth - worldx) { x1 = GamePanel.screenWidth - (gp.WorldWidth - worldx); } int bottomOffsetValue1 = GamePanel.screenHeight - screenY; if (bottomOffsetValue1 > gp.WorldHeight - worldy) { y1 = GamePanel.screenHeight - (gp.WorldHeight - worldy); } g2.drawImage(image, x1, y1, null); } /** * <p>draw.</p> * * @param g2 a {@link java.awt.Graphics2D} object */ public void draw(Graphics2D g2) { if (gp.labyrinthFrame.getHasLost()) { drawDeathAnimation(g2); timesPassed++; return; } BufferedImage image; switch (direction) { case "up": image = up[spriteNum - 1]; break; case "down": image = down[spriteNum - 1]; break; case "left": image = left[spriteNum - 1]; break; default: image = right[spriteNum - 1]; break; } setValues(g2, image); } /** * <p>Getter for the field <code>worldx</code>.</p> * * @return an int */ public int getWorldx() { return worldx; } /** * <p>Getter for the field <code>worldy</code>.</p> * * @return an int */ public int getWorldy() { return worldy; } /** * <p>Getter for the field <code>direction</code>.</p> * * @return a {@link java.lang.String} object */ public String getDirection() { return direction; } /** * <p>Setter for the field <code>collisionOn</code>.</p> * * @param collisionOn a boolean */ public void setCollisionOn(boolean collisionOn) { this.collisionOn = collisionOn; } /** * <p>Getter for the field <code>screenX</code>.</p> * * @return an int */ public int getScreenX() { return screenX; } /** * <p>Getter for the field <code>screenY</code>.</p> * * @return an int */ public int getScreenY() { return screenY; } }
geoartop/Hack-You
Maven/src/main/java/game/Player.java
2,284
/** * <p>Διαχείριση interactions του παίκτη με αντικείμενα μέσα στο παιχνίδι</p> * * @param index θέση του παίκτη στον χάρτη */
block_comment
el
package game; import javax.swing.SwingUtilities; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.Objects; /** * <p>Φόρτωση του παίκτη και εγγραφή των κινήσεών του στην οθόνη</p> * * @author Team Hack-You * @version 1.0 * @see Entity */ public class Player extends Entity { private int worldx, worldy; static final int speed = 2; private final GamePanel gp; private final KeyHandler keyH; private final int screenX; private final int screenY; /** * Coins collected from player */ private static int coinsCollected = 0; /** * Κινήσεις animation ήττας παίκτη */ private int timesPassed = 0; private String direction; //Μεταβλητές παίκτη private int spriteCounter = 0; private int spriteNum = 1; final Rectangle solidArea = new Rectangle(8, 32, 32, 16); final int solidAreaDefaultX = solidArea.x; final int solidAreaDefaultY = solidArea.y; private boolean collisionOn = false; private static final int outOfBoundsLimit = 15; /** * <p>Getter for the field <code>coinsCollected</code>.</p> * * @return an int */ public static int getCoinsCollected() { return coinsCollected; } /** * <p>Restores <code>coinsCollected</code> value.</p> */ public static void restoreCoinsCollected() { coinsCollected = 0; } /** * <p>Constructor for Player.</p> * * @param gp a {@link game.GamePanel} object * @param keyH a {@link game.KeyHandler} object */ public Player(GamePanel gp, KeyHandler keyH) { this.gp = gp; this.keyH = keyH; screenX = GamePanel.screenWidth / 2 - (GamePanel.tileSize / 2); screenY = GamePanel.screenHeight / 2 - (GamePanel.tileSize / 2); setDefaultValues(); } /** * <p>Καθορισμός αρχικής θέσης παίκτη</p> */ private void setDefaultValues() { worldx = 100; worldy = 50; direction = "down"; } /** * <p>Ανανέωση κίνησης παίκτη</p> */ public void update() { if (keyH.keyIsPressed()) { if (keyH.getUpPressed()) { direction = "up"; } else if (keyH.getDownPressed()) { direction = "down"; } else if (keyH.getLeftPressed()) { direction = "left"; } else { direction = "right"; } collisionOn = false; gp.collisionCheck.checkTile(this); int objIndex = gp.collisionCheck.checkObject(this, true); interact(objIndex); //If collision is false only then can player move on if (!collisionOn) { switch (direction) { case "up": //Εξασφαλίζει ότι ο παίκτης δε θα βγει out of bounds if (worldy < outOfBoundsLimit) { break; } worldy -= speed; break; case "down": worldy += speed; break; case "left": worldx -= speed; break; default: worldx += speed; break; } } spriteCounter++; if (spriteCounter > 5) { if (spriteNum < 9) { spriteNum++; } else { spriteNum = 1; } spriteCounter = 0; } } } /** * <p>Σταθεροποίηση κίνησης παίκτη</p> */ void stabilizePlayer() { keyH.stopMovement(); } /** * <p>Διαχείριση interactions του<SUF>*/ private void interact(int index) { if (index != 999) { String objectName = gp.obj.get(index).getName(); if (ButtonSetter.getPlaySound()) { gp.obj.get(index).playSE(); } if (Objects.equals(objectName, "Question")) { //Για να μην κολλήσει το progressBar και η ροή του παιχνιδιού gp.labyrinthFrame.stopBar(); gp.setGameState(GamePanel.pauseState); gp.keyH.setQuizTrig(true); SwingUtilities.invokeLater(() -> new Quiz(gp)); gp.obj.set(index, null); } //Τερματισμός παιχνιδιού σε περίπτωση νίκης if (Objects.equals(objectName, "Exit")) { gp.setGameState(GamePanel.endState); } //Προσθήκη χρόνου (ίσως και πόντων) όταν ο παίκτης βρίσκει coins if (Objects.equals(objectName, "Coin")) { coinsCollected++; gp.obj.set(index, null); } } } /** * <p>Απεικόνιση "θανάτου" παίκτη</p> * * @param g2 a {@link java.awt.Graphics2D} object */ public void drawDeathAnimation(Graphics2D g2) { BufferedImage image; image = death[timesPassed]; setValues(g2, image); } /** * <p>setValues.</p> * * @param g2 a {@link Graphics2D} object * @param image a {@link BufferedImage} object */ private void setValues(Graphics2D g2, BufferedImage image) { int x1 = screenX; int y1 = screenY; if (screenX > worldx) { x1 = worldx; } if (screenY > worldy) { y1 = worldy; } int rightOffsetValue1 = GamePanel.screenWidth - screenX; if (rightOffsetValue1 > gp.WorldWidth - worldx) { x1 = GamePanel.screenWidth - (gp.WorldWidth - worldx); } int bottomOffsetValue1 = GamePanel.screenHeight - screenY; if (bottomOffsetValue1 > gp.WorldHeight - worldy) { y1 = GamePanel.screenHeight - (gp.WorldHeight - worldy); } g2.drawImage(image, x1, y1, null); } /** * <p>draw.</p> * * @param g2 a {@link java.awt.Graphics2D} object */ public void draw(Graphics2D g2) { if (gp.labyrinthFrame.getHasLost()) { drawDeathAnimation(g2); timesPassed++; return; } BufferedImage image; switch (direction) { case "up": image = up[spriteNum - 1]; break; case "down": image = down[spriteNum - 1]; break; case "left": image = left[spriteNum - 1]; break; default: image = right[spriteNum - 1]; break; } setValues(g2, image); } /** * <p>Getter for the field <code>worldx</code>.</p> * * @return an int */ public int getWorldx() { return worldx; } /** * <p>Getter for the field <code>worldy</code>.</p> * * @return an int */ public int getWorldy() { return worldy; } /** * <p>Getter for the field <code>direction</code>.</p> * * @return a {@link java.lang.String} object */ public String getDirection() { return direction; } /** * <p>Setter for the field <code>collisionOn</code>.</p> * * @param collisionOn a boolean */ public void setCollisionOn(boolean collisionOn) { this.collisionOn = collisionOn; } /** * <p>Getter for the field <code>screenX</code>.</p> * * @return an int */ public int getScreenX() { return screenX; } /** * <p>Getter for the field <code>screenY</code>.</p> * * @return an int */ public int getScreenY() { return screenY; } }
3730_0
import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class Client { public static void main(String[] args) { try { //το δεύτερο argument είναι πάντα το ποιά λειτουργία θα εκτελεστεί String leitourgia=args[2]; // connect to the RMI registry Registry rmiRegistry = LocateRegistry.getRegistry(Integer.parseInt(args[1])); // get reference for remote object Accountholder stub = (Accountholder) rmiRegistry.lookup(args[0]); //ανάλογα με το τι θέλουμε να κάνουμε καλείται η κατάλληλη λειτουργία if(leitourgia.equals("1")) { System.out.println(stub.CreateAccount(args[3])); } if(leitourgia.equals("2")) { System.out.println(stub.ShowAccounts(args[3])); } if(leitourgia.equals("3")) { //εδώ ενώνουμε όλα τα arguments λόγω της ύπαρξης κενών για τα μηνύματα String a=""; for(int i=5;i<args.length;i++) { if(i!=5) { a += " " + args[i]; } else { a+=args[i]; } } System.out.println(stub.SendMessage(args[3],args[4],a)); } if(leitourgia.equals("4")) { System.out.print(stub.ShowInbox(args[3])); } if(leitourgia.equals("5")) { System.out.print(stub.ReadMessage(args[3],args[4])); } if(leitourgia.equals("6")) { System.out.print(stub.DeleteMessage(args[3],args[4])); } } catch (Exception e) { System.out.println(e); } } }
geor999/DigitalCommunicationsProject
3691_dimitrios_georgantis/src/Client.java
572
//το δεύτερο argument είναι πάντα το ποιά λειτουργία θα εκτελεστεί
line_comment
el
import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class Client { public static void main(String[] args) { try { //το δεύτερο<SUF> String leitourgia=args[2]; // connect to the RMI registry Registry rmiRegistry = LocateRegistry.getRegistry(Integer.parseInt(args[1])); // get reference for remote object Accountholder stub = (Accountholder) rmiRegistry.lookup(args[0]); //ανάλογα με το τι θέλουμε να κάνουμε καλείται η κατάλληλη λειτουργία if(leitourgia.equals("1")) { System.out.println(stub.CreateAccount(args[3])); } if(leitourgia.equals("2")) { System.out.println(stub.ShowAccounts(args[3])); } if(leitourgia.equals("3")) { //εδώ ενώνουμε όλα τα arguments λόγω της ύπαρξης κενών για τα μηνύματα String a=""; for(int i=5;i<args.length;i++) { if(i!=5) { a += " " + args[i]; } else { a+=args[i]; } } System.out.println(stub.SendMessage(args[3],args[4],a)); } if(leitourgia.equals("4")) { System.out.print(stub.ShowInbox(args[3])); } if(leitourgia.equals("5")) { System.out.print(stub.ReadMessage(args[3],args[4])); } if(leitourgia.equals("6")) { System.out.print(stub.DeleteMessage(args[3],args[4])); } } catch (Exception e) { System.out.println(e); } } }
7704_1
package com.example.foodys; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { public static final String DBNAME = "Login.db"; public DBHelper(Context context) { super(context, "Login.db", null, 1); } //Δημιουργώ μια database με usernames και password με χρήση sqlite @Override public void onCreate(SQLiteDatabase MyDB) { MyDB.execSQL("create Table users(username TEXT primary key, password TEXT)"); } @Override public void onUpgrade(SQLiteDatabase MyDB, int i, int i1) { MyDB.execSQL("drop Table if exists users"); } //Προθέτω values στον πίνακα public Boolean insertData(String username, String password){ SQLiteDatabase MyDB = this.getWritableDatabase(); ContentValues contentValues= new ContentValues(); contentValues.put("username", username); contentValues.put("password", password); long result = MyDB.insert("users", null, contentValues); if(result==-1) return false; else return true; } //Τσεκάρω αν υπάρχει το username στον πίνακα public Boolean checkusername(String username) { SQLiteDatabase MyDB = this.getWritableDatabase(); Cursor cursor = MyDB.rawQuery("Select * from users where username = ?", new String[]{username}); if (cursor.getCount() > 0) return true; else return false; } //Τσεκάρω αν υπάρχει το username και το password στον πίνακα public Boolean checkusernamepassword(String username, String password){ SQLiteDatabase MyDB = this.getWritableDatabase(); Cursor cursor = MyDB.rawQuery("Select * from users where username = ? and password = ?", new String[] {username,password}); if(cursor.getCount()>0) return true; else return false; } }
geor999/Foodys-Android-App
app/src/main/java/com/example/foodys/DBHelper.java
539
//Προθέτω values στον πίνακα
line_comment
el
package com.example.foodys; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { public static final String DBNAME = "Login.db"; public DBHelper(Context context) { super(context, "Login.db", null, 1); } //Δημιουργώ μια database με usernames και password με χρήση sqlite @Override public void onCreate(SQLiteDatabase MyDB) { MyDB.execSQL("create Table users(username TEXT primary key, password TEXT)"); } @Override public void onUpgrade(SQLiteDatabase MyDB, int i, int i1) { MyDB.execSQL("drop Table if exists users"); } //Προθέτω values<SUF> public Boolean insertData(String username, String password){ SQLiteDatabase MyDB = this.getWritableDatabase(); ContentValues contentValues= new ContentValues(); contentValues.put("username", username); contentValues.put("password", password); long result = MyDB.insert("users", null, contentValues); if(result==-1) return false; else return true; } //Τσεκάρω αν υπάρχει το username στον πίνακα public Boolean checkusername(String username) { SQLiteDatabase MyDB = this.getWritableDatabase(); Cursor cursor = MyDB.rawQuery("Select * from users where username = ?", new String[]{username}); if (cursor.getCount() > 0) return true; else return false; } //Τσεκάρω αν υπάρχει το username και το password στον πίνακα public Boolean checkusernamepassword(String username, String password){ SQLiteDatabase MyDB = this.getWritableDatabase(); Cursor cursor = MyDB.rawQuery("Select * from users where username = ? and password = ?", new String[] {username,password}); if(cursor.getCount()>0) return true; else return false; } }
1862_6
package com.example.uManage.activity_classes; import static androidx.constraintlayout.helper.widget.MotionEffect.TAG; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.provider.OpenableColumns; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.example.uManage.R; import com.example.uManage.database.WorkersDatabase; import java.io.ByteArrayOutputStream; public class AddWorker extends AppCompatActivity { public Uri selectedImage; Button button; ImageButton imageButton; TextView textView; ImageView img; EditText name; EditText age; EditText salary; WorkersDatabase db; String name1; String username; int age1; int salary1; int t = 0; //χρησιμοποιώ Launcher για την είσοδο στην συλλογή, όταν η συλλογή κλείσει τότε κάνω μετατροπές στο αποτέλεσμα που πήρα και αποθηκεύω την φωτογραφία σε ένα αόρατο Imageview ActivityResultLauncher<Intent> Launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult result) { if (result.getResultCode() == RESULT_OK && result.getData() != null) { t = 1; selectedImage = result.getData().getData(); Cursor returnCursor = getContentResolver().query(selectedImage, null, null, null, null); int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); returnCursor.moveToFirst(); //αρχικοποιώ το textview με το όνομα της φωτογραφίας που χρησιμοποίησα textView.setText(returnCursor.getString(nameIndex)); textView.setVisibility(View.VISIBLE); img.setImageURI(selectedImage); Log.d(TAG, "onActivityResult: " + img); } } } ); @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.addworker_tab); //παίρνω σαν extra το όνομα της εταιρίας για να κάνω τις εισαγωγές στην βάση if (getIntent().getExtras() != null) { Bundle extras = getIntent().getExtras(); username = extras.getString("name"); } //init τα components textView = findViewById(R.id.camera_text_add_tab); imageButton = findViewById(R.id.camera_add_tab); img = findViewById(R.id.image_for_bitmap_add_tab); button = findViewById(R.id.button_add_tab); name = findViewById(R.id.person_name_add_tab); age = findViewById(R.id.age_add_tab); salary = findViewById(R.id.salary_add_tab); //δημιουργώ instance της βάσης εργαζόμενων db = new WorkersDatabase(this); //savedInstanceState σε περίπτωση που γυρίσει η οθόνη ή κλείσουμε προσωρινά την εφαρμογή χωρίς να την τερματίσουμε if (savedInstanceState != null) { name.setText(savedInstanceState.getString("wname")); age.setText(savedInstanceState.getString("wage")); salary.setText(savedInstanceState.getString("wsalary")); if (savedInstanceState.getParcelable("wimguri") != null) { selectedImage = savedInstanceState.getParcelable("wimguri"); img.setImageURI(selectedImage); textView.setText(savedInstanceState.getString("wimgname")); textView.setVisibility(View.VISIBLE); t = 1; } } super.onCreate(savedInstanceState); //onclicklistener για το imagebutton που οδηγεί στην συλλογη imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sunarthsh(); } }); //onclicklistener για το addbutton που αν όλοι οι έλεγχοι είναι οκ κάνει εισαγωγή του εργαζόμενου στην βάση button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (name.getText().toString().equals("") || age.getText().toString().equals("") || salary.getText().toString().equals("")) { Toast.makeText(AddWorker.this, "Please fill all the gaps!", Toast.LENGTH_SHORT).show(); } else { if (Integer.parseInt(age.getText().toString()) <= 17) { Toast.makeText(AddWorker.this, "Age must be higher than 17!", Toast.LENGTH_SHORT).show(); } else { //μετατρέπω την εικόνα σε byte[] για να την αποθηκεύσω στην βάση byte[] image = bitmaptobyte(); name1 = name.getText().toString(); age1 = Integer.parseInt(age.getText().toString()); salary1 = Integer.parseInt(salary.getText().toString()); db.addEntry(name1, age1, salary1, textView.getText().toString(), image, username); finish(); } } } }); } //η διαδικασία μετατροπής της εικόνας σε byte[] private byte[] bitmaptobyte() { byte[] image = null; if (t == 1) { Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap(); int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth())); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true); scaled.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream); image = byteArrayOutputStream.toByteArray(); } else { textView.setText(""); } return image; } @Override public void onSaveInstanceState(@NonNull Bundle outState) { Log.d(TAG, "onSaveInstanceState: " + selectedImage); outState.putString("wname", name.getText().toString()); outState.putString("wage", String.valueOf(age.getText())); outState.putString("wsalary", String.valueOf(salary.getText())); outState.putParcelable("wimguri", selectedImage); outState.putString("wimgname", textView.getText().toString()); super.onSaveInstanceState(outState); } private ActivityResultLauncher<String> requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> { if (isGranted) { // Permission is granted. Continue the action or workflow in your // app. } else { // Explain to the user that the feature is unavailable because the // features requires a permission that the user has denied. At the // same time, respect the user's decision. Don't link to system // settings in an effort to convince the user to change their // decision. } }); private void sunarthsh() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // You can use the API that requires the permission. Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); Launcher.launch(intent); } else { // You can directly ask for the permission. // The registered ActivityResultCallback gets the result of this request. requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE); } } }
geor999/uManage-Android-App
app/src/main/java/com/example/uManage/activity_classes/AddWorker.java
2,270
//onclicklistener για το imagebutton που οδηγεί στην συλλογη
line_comment
el
package com.example.uManage.activity_classes; import static androidx.constraintlayout.helper.widget.MotionEffect.TAG; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.provider.OpenableColumns; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.example.uManage.R; import com.example.uManage.database.WorkersDatabase; import java.io.ByteArrayOutputStream; public class AddWorker extends AppCompatActivity { public Uri selectedImage; Button button; ImageButton imageButton; TextView textView; ImageView img; EditText name; EditText age; EditText salary; WorkersDatabase db; String name1; String username; int age1; int salary1; int t = 0; //χρησιμοποιώ Launcher για την είσοδο στην συλλογή, όταν η συλλογή κλείσει τότε κάνω μετατροπές στο αποτέλεσμα που πήρα και αποθηκεύω την φωτογραφία σε ένα αόρατο Imageview ActivityResultLauncher<Intent> Launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult result) { if (result.getResultCode() == RESULT_OK && result.getData() != null) { t = 1; selectedImage = result.getData().getData(); Cursor returnCursor = getContentResolver().query(selectedImage, null, null, null, null); int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); returnCursor.moveToFirst(); //αρχικοποιώ το textview με το όνομα της φωτογραφίας που χρησιμοποίησα textView.setText(returnCursor.getString(nameIndex)); textView.setVisibility(View.VISIBLE); img.setImageURI(selectedImage); Log.d(TAG, "onActivityResult: " + img); } } } ); @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.addworker_tab); //παίρνω σαν extra το όνομα της εταιρίας για να κάνω τις εισαγωγές στην βάση if (getIntent().getExtras() != null) { Bundle extras = getIntent().getExtras(); username = extras.getString("name"); } //init τα components textView = findViewById(R.id.camera_text_add_tab); imageButton = findViewById(R.id.camera_add_tab); img = findViewById(R.id.image_for_bitmap_add_tab); button = findViewById(R.id.button_add_tab); name = findViewById(R.id.person_name_add_tab); age = findViewById(R.id.age_add_tab); salary = findViewById(R.id.salary_add_tab); //δημιουργώ instance της βάσης εργαζόμενων db = new WorkersDatabase(this); //savedInstanceState σε περίπτωση που γυρίσει η οθόνη ή κλείσουμε προσωρινά την εφαρμογή χωρίς να την τερματίσουμε if (savedInstanceState != null) { name.setText(savedInstanceState.getString("wname")); age.setText(savedInstanceState.getString("wage")); salary.setText(savedInstanceState.getString("wsalary")); if (savedInstanceState.getParcelable("wimguri") != null) { selectedImage = savedInstanceState.getParcelable("wimguri"); img.setImageURI(selectedImage); textView.setText(savedInstanceState.getString("wimgname")); textView.setVisibility(View.VISIBLE); t = 1; } } super.onCreate(savedInstanceState); //onclicklistener για<SUF> imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sunarthsh(); } }); //onclicklistener για το addbutton που αν όλοι οι έλεγχοι είναι οκ κάνει εισαγωγή του εργαζόμενου στην βάση button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (name.getText().toString().equals("") || age.getText().toString().equals("") || salary.getText().toString().equals("")) { Toast.makeText(AddWorker.this, "Please fill all the gaps!", Toast.LENGTH_SHORT).show(); } else { if (Integer.parseInt(age.getText().toString()) <= 17) { Toast.makeText(AddWorker.this, "Age must be higher than 17!", Toast.LENGTH_SHORT).show(); } else { //μετατρέπω την εικόνα σε byte[] για να την αποθηκεύσω στην βάση byte[] image = bitmaptobyte(); name1 = name.getText().toString(); age1 = Integer.parseInt(age.getText().toString()); salary1 = Integer.parseInt(salary.getText().toString()); db.addEntry(name1, age1, salary1, textView.getText().toString(), image, username); finish(); } } } }); } //η διαδικασία μετατροπής της εικόνας σε byte[] private byte[] bitmaptobyte() { byte[] image = null; if (t == 1) { Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap(); int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth())); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true); scaled.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream); image = byteArrayOutputStream.toByteArray(); } else { textView.setText(""); } return image; } @Override public void onSaveInstanceState(@NonNull Bundle outState) { Log.d(TAG, "onSaveInstanceState: " + selectedImage); outState.putString("wname", name.getText().toString()); outState.putString("wage", String.valueOf(age.getText())); outState.putString("wsalary", String.valueOf(salary.getText())); outState.putParcelable("wimguri", selectedImage); outState.putString("wimgname", textView.getText().toString()); super.onSaveInstanceState(outState); } private ActivityResultLauncher<String> requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> { if (isGranted) { // Permission is granted. Continue the action or workflow in your // app. } else { // Explain to the user that the feature is unavailable because the // features requires a permission that the user has denied. At the // same time, respect the user's decision. Don't link to system // settings in an effort to convince the user to change their // decision. } }); private void sunarthsh() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // You can use the API that requires the permission. Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); Launcher.launch(intent); } else { // You can directly ask for the permission. // The registered ActivityResultCallback gets the result of this request. requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE); } } }
58_12
/* This file is part of Arcadeflex. Arcadeflex is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Arcadeflex is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Arcadeflex. If not, see <http://www.gnu.org/licenses/>. */ package arcadeflex.v036.converter; /** * * @author george */ public class machineConvert { static final int machine_mem_read=20; static final int machine_mem_write=21; static final int machine_init=22; static final int machine_interrupt=25; public static void ConvertMachine() { Convertor.inpos = 0;//position of pointer inside the buffers Convertor.outpos = 0; boolean only_once_flag=false;//gia na baleis to header mono mia fora boolean line_change_flag=false; int type=0; int l=0; int k=0; label0: do { if(Convertor.inpos >= Convertor.inbuf.length)//an to megethos einai megalitero spase to loop { break; } char c = sUtil.getChar(); //pare ton character if(line_change_flag) { for(int i1 = 0; i1 < k; i1++) { sUtil.putString("\t"); } line_change_flag = false; } switch(c) { case 35: // '#' if(!sUtil.getToken("#include"))//an den einai #include min to trexeis { break; } sUtil.skipLine(); if(!only_once_flag)//trekse auto to komati mono otan bris to proto include { only_once_flag = true; sUtil.putString("/*\r\n"); sUtil.putString(" * ported to v" + Convertor.mameversion + "\r\n"); sUtil.putString(" * using automatic conversion tool v" + Convertor.convertorversion + "\r\n"); /*sUtil.putString(" * converted at : " + Convertor.timenow() + "\r\n");*/ sUtil.putString(" *\r\n"); sUtil.putString(" *\r\n"); sUtil.putString(" *\r\n"); sUtil.putString(" */ \r\n"); sUtil.putString("package machine;\r\n"); sUtil.putString("\r\n"); sUtil.putString((new StringBuilder()).append("public class ").append(Convertor.className).append("\r\n").toString()); sUtil.putString("{\r\n"); k=1; line_change_flag = true; } continue; case 10: // '\n' Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++]; line_change_flag = true; continue; case 45: // '-' char c3 = sUtil.getNextChar(); if(c3 != '>') { break; } Convertor.outbuf[Convertor.outpos++] = '.'; Convertor.inpos += 2; continue; case 105: // 'i' int i = Convertor.inpos; if(sUtil.getToken("if")) { sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = i; break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.getChar() == '&') { Convertor.inpos++; sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); Convertor.token[0] = (new StringBuilder()).append("(").append(Convertor.token[0]).append(" & ").append(Convertor.token[1]).append(")").toString(); } if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } sUtil.putString((new StringBuilder()).append("if (").append(Convertor.token[0]).append(" != 0)").toString()); continue; } if(!sUtil.getToken("int")) { break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = i; break; } sUtil.skipSpace(); if(sUtil.getToken("void"))//an to soma tis function einai (void) { if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } if(Convertor.token[0].contains("_interrupt")) { sUtil.putString((new StringBuilder()).append("public static InterruptPtr ").append(Convertor.token[0]).append(" = new InterruptPtr() { public int handler() ").toString()); type = machine_interrupt; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } } if(sUtil.getToken("int")) { sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } sUtil.skipSpace(); if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0) { sUtil.putString((new StringBuilder()).append("public static ReadHandlerPtr ").append(Convertor.token[0]).append(" = new ReadHandlerPtr() { public int handler(int ").append(Convertor.token[1]).append(")").toString()); type = machine_mem_read; l = -1; continue label0; } } Convertor.inpos = i; break; case 118: // 'v' int j = Convertor.inpos; if(!sUtil.getToken("void")) { break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(sUtil.getToken("void"))//an to soma tis function einai (void) { if(sUtil.parseChar() != ')') { Convertor.inpos = j; break; } if(Convertor.token[0].contains("init_machine")) { sUtil.putString((new StringBuilder()).append("public static InitMachinePtr ").append(Convertor.token[0]).append(" = new InitMachinePtr() { public void handler() ").toString()); type = machine_init; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } } if(!sUtil.getToken("int")) { Convertor.inpos = j; break; } sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ',') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(!sUtil.getToken("int")) { Convertor.inpos = j; break; } sUtil.skipSpace(); Convertor.token[2] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ')') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0 && Convertor.token[2].length()>0) { sUtil.putString((new StringBuilder()).append("public static WriteHandlerPtr ").append(Convertor.token[0]).append(" = new WriteHandlerPtr() { public void handler(int ").append(Convertor.token[1]).append(", int ").append(Convertor.token[2]).append(")").toString()); type = machine_mem_write; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } Convertor.inpos = j; break; case 123: // '{' l++; break; case 125: // '}' l--; if(type != machine_mem_read && type != machine_mem_write && type!=machine_init && type!=machine_interrupt || l != -1) { break; } sUtil.putString("} };"); Convertor.inpos++; type = -1; continue; } Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++];//grapse to inputbuffer sto output }while(true); if(only_once_flag) { sUtil.putString("}\r\n"); } } }
georgemoralis/arcadeflex
0.36/converter/src/main/java/arcadeflex/v036/converter/machineConvert.java
2,433
//ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση
line_comment
el
/* This file is part of Arcadeflex. Arcadeflex is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Arcadeflex is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Arcadeflex. If not, see <http://www.gnu.org/licenses/>. */ package arcadeflex.v036.converter; /** * * @author george */ public class machineConvert { static final int machine_mem_read=20; static final int machine_mem_write=21; static final int machine_init=22; static final int machine_interrupt=25; public static void ConvertMachine() { Convertor.inpos = 0;//position of pointer inside the buffers Convertor.outpos = 0; boolean only_once_flag=false;//gia na baleis to header mono mia fora boolean line_change_flag=false; int type=0; int l=0; int k=0; label0: do { if(Convertor.inpos >= Convertor.inbuf.length)//an to megethos einai megalitero spase to loop { break; } char c = sUtil.getChar(); //pare ton character if(line_change_flag) { for(int i1 = 0; i1 < k; i1++) { sUtil.putString("\t"); } line_change_flag = false; } switch(c) { case 35: // '#' if(!sUtil.getToken("#include"))//an den einai #include min to trexeis { break; } sUtil.skipLine(); if(!only_once_flag)//trekse auto to komati mono otan bris to proto include { only_once_flag = true; sUtil.putString("/*\r\n"); sUtil.putString(" * ported to v" + Convertor.mameversion + "\r\n"); sUtil.putString(" * using automatic conversion tool v" + Convertor.convertorversion + "\r\n"); /*sUtil.putString(" * converted at : " + Convertor.timenow() + "\r\n");*/ sUtil.putString(" *\r\n"); sUtil.putString(" *\r\n"); sUtil.putString(" *\r\n"); sUtil.putString(" */ \r\n"); sUtil.putString("package machine;\r\n"); sUtil.putString("\r\n"); sUtil.putString((new StringBuilder()).append("public class ").append(Convertor.className).append("\r\n").toString()); sUtil.putString("{\r\n"); k=1; line_change_flag = true; } continue; case 10: // '\n' Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++]; line_change_flag = true; continue; case 45: // '-' char c3 = sUtil.getNextChar(); if(c3 != '>') { break; } Convertor.outbuf[Convertor.outpos++] = '.'; Convertor.inpos += 2; continue; case 105: // 'i' int i = Convertor.inpos; if(sUtil.getToken("if")) { sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = i; break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.getChar() == '&') { Convertor.inpos++; sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); Convertor.token[0] = (new StringBuilder()).append("(").append(Convertor.token[0]).append(" & ").append(Convertor.token[1]).append(")").toString(); } if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } sUtil.putString((new StringBuilder()).append("if (").append(Convertor.token[0]).append(" != 0)").toString()); continue; } if(!sUtil.getToken("int")) { break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = i; break; } sUtil.skipSpace(); if(sUtil.getToken("void"))//an to soma tis function einai (void) { if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } if(Convertor.token[0].contains("_interrupt")) { sUtil.putString((new StringBuilder()).append("public static InterruptPtr ").append(Convertor.token[0]).append(" = new InterruptPtr() { public int handler() ").toString()); type = machine_interrupt; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } } if(sUtil.getToken("int")) { sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } sUtil.skipSpace(); if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0) { sUtil.putString((new StringBuilder()).append("public static ReadHandlerPtr ").append(Convertor.token[0]).append(" = new ReadHandlerPtr() { public int handler(int ").append(Convertor.token[1]).append(")").toString()); type = machine_mem_read; l = -1; continue label0; } } Convertor.inpos = i; break; case 118: // 'v' int j = Convertor.inpos; if(!sUtil.getToken("void")) { break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(sUtil.getToken("void"))//an to soma tis function einai (void) { if(sUtil.parseChar() != ')') { Convertor.inpos = j; break; } if(Convertor.token[0].contains("init_machine")) { sUtil.putString((new StringBuilder()).append("public static InitMachinePtr ").append(Convertor.token[0]).append(" = new InitMachinePtr() { public void handler() ").toString()); type = machine_init; l = -1; continue label0; //ξαναργυρνα στην<SUF> } } if(!sUtil.getToken("int")) { Convertor.inpos = j; break; } sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ',') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(!sUtil.getToken("int")) { Convertor.inpos = j; break; } sUtil.skipSpace(); Convertor.token[2] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ')') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0 && Convertor.token[2].length()>0) { sUtil.putString((new StringBuilder()).append("public static WriteHandlerPtr ").append(Convertor.token[0]).append(" = new WriteHandlerPtr() { public void handler(int ").append(Convertor.token[1]).append(", int ").append(Convertor.token[2]).append(")").toString()); type = machine_mem_write; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } Convertor.inpos = j; break; case 123: // '{' l++; break; case 125: // '}' l--; if(type != machine_mem_read && type != machine_mem_write && type!=machine_init && type!=machine_interrupt || l != -1) { break; } sUtil.putString("} };"); Convertor.inpos++; type = -1; continue; } Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++];//grapse to inputbuffer sto output }while(true); if(only_once_flag) { sUtil.putString("}\r\n"); } } }
9685_1
/* * copyright 2013-2021 * codebb.gr * ProtoERP - Open source invocing program * [email protected] */ /* * Changelog * ========= * 02/04/2021 (gmoralis) - Προσθήκη συντελεστών Φ.Π.Α. * 31/03/2021 (gmoralis) - Προσθήκη μονάδων μέτρησης * 29/03/2021 (gmoralis) - Διαχωρισμός μενού απο το κεντρικό παράθυρο */ package gr.codebb.protoerp.generic; import gr.codebb.ctl.CbbDetachableTab; import gr.codebb.ctl.CbbDetachableTabPane; import gr.codebb.lib.util.AlertDlgHelper; import gr.codebb.lib.util.FxmlUtil; import gr.codebb.protoerp.settings.internetSettings.MitrooPassView; import gr.codebb.protoerp.settings.internetSettings.MyDataPassView; import gr.codebb.protoerp.tables.measurementUnits.MeasurementUnitsListView; import gr.codebb.protoerp.tables.vat.VatListView; import java.net.URL; import java.util.Optional; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.MenuBar; /** * FXML Controller class * * @author snow */ public class MainMenuView implements Initializable { @FXML private MenuBar menuBar; private CbbDetachableTabPane mainDetachPane; public void setMainDetachPane(CbbDetachableTabPane mainDetachPane) { this.mainDetachPane = mainDetachPane; } private void showAsTab(Node frm, String label) { final CbbDetachableTab tab = new CbbDetachableTab(label); tab.setClosable(true); tab.setContent(frm); mainDetachPane.getTabs().add(tab); mainDetachPane.getSelectionModel().select(tab); /** Workaround for TabPane memory leak */ tab.setOnClosed( new EventHandler<Event>() { @Override public void handle(Event t) { tab.setContent(null); } }); mainDetachPane.getSelectionModel().selectLast(); } @Override public void initialize(URL url, ResourceBundle rb) {} @FXML private void onMitrooCodes(ActionEvent event) { FxmlUtil.LoadResult<MitrooPassView> getDetailView = FxmlUtil.load("/fxml/settings/internetServices/MitrooPass.fxml"); Alert alert = AlertDlgHelper.saveDialog( "Κωδικοί Μητρώου", getDetailView.getParent(), menuBar.getScene().getWindow()); getDetailView.getController().companyLoad(); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { if (getDetailView.getController() != null) { getDetailView.getController().save(); } } } @FXML private void onMyDataCodes(ActionEvent event) { FxmlUtil.LoadResult<MyDataPassView> getDetailView = FxmlUtil.load("/fxml/settings/internetServices/MyDataPass.fxml"); Alert alert = AlertDlgHelper.saveDialog( "Κωδικοί MyData", getDetailView.getParent(), menuBar.getScene().getWindow()); getDetailView.getController().companyPassLoad(); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { if (getDetailView.getController() != null) { getDetailView.getController().save(); } } } @FXML private void onMeasureUnits(ActionEvent event) { FxmlUtil.LoadResult<MeasurementUnitsListView> getListView = FxmlUtil.load("/fxml/tables/measurementUnits/MeasurementUnitsListView.fxml"); Node measure = (Node) getListView.getParent(); showAsTab(measure, "Μονάδες Μέτρησης"); } @FXML private void onVat(ActionEvent event) { FxmlUtil.LoadResult<VatListView> getListView = FxmlUtil.load("/fxml/tables/vat/VatListView.fxml"); Node measure = (Node) getListView.getParent(); showAsTab(measure, "Συντελεστές Φ.Π.Α."); } @FXML private void onInvoiceSeries(ActionEvent event) {} @FXML private void onInitTables(ActionEvent event) {} }
georgemoralis/protoERP
src/main/java/gr/codebb/protoerp/generic/MainMenuView.java
1,236
/* * Changelog * ========= * 02/04/2021 (gmoralis) - Προσθήκη συντελεστών Φ.Π.Α. * 31/03/2021 (gmoralis) - Προσθήκη μονάδων μέτρησης * 29/03/2021 (gmoralis) - Διαχωρισμός μενού απο το κεντρικό παράθυρο */
block_comment
el
/* * copyright 2013-2021 * codebb.gr * ProtoERP - Open source invocing program * [email protected] */ /* * Changelog *<SUF>*/ package gr.codebb.protoerp.generic; import gr.codebb.ctl.CbbDetachableTab; import gr.codebb.ctl.CbbDetachableTabPane; import gr.codebb.lib.util.AlertDlgHelper; import gr.codebb.lib.util.FxmlUtil; import gr.codebb.protoerp.settings.internetSettings.MitrooPassView; import gr.codebb.protoerp.settings.internetSettings.MyDataPassView; import gr.codebb.protoerp.tables.measurementUnits.MeasurementUnitsListView; import gr.codebb.protoerp.tables.vat.VatListView; import java.net.URL; import java.util.Optional; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.MenuBar; /** * FXML Controller class * * @author snow */ public class MainMenuView implements Initializable { @FXML private MenuBar menuBar; private CbbDetachableTabPane mainDetachPane; public void setMainDetachPane(CbbDetachableTabPane mainDetachPane) { this.mainDetachPane = mainDetachPane; } private void showAsTab(Node frm, String label) { final CbbDetachableTab tab = new CbbDetachableTab(label); tab.setClosable(true); tab.setContent(frm); mainDetachPane.getTabs().add(tab); mainDetachPane.getSelectionModel().select(tab); /** Workaround for TabPane memory leak */ tab.setOnClosed( new EventHandler<Event>() { @Override public void handle(Event t) { tab.setContent(null); } }); mainDetachPane.getSelectionModel().selectLast(); } @Override public void initialize(URL url, ResourceBundle rb) {} @FXML private void onMitrooCodes(ActionEvent event) { FxmlUtil.LoadResult<MitrooPassView> getDetailView = FxmlUtil.load("/fxml/settings/internetServices/MitrooPass.fxml"); Alert alert = AlertDlgHelper.saveDialog( "Κωδικοί Μητρώου", getDetailView.getParent(), menuBar.getScene().getWindow()); getDetailView.getController().companyLoad(); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { if (getDetailView.getController() != null) { getDetailView.getController().save(); } } } @FXML private void onMyDataCodes(ActionEvent event) { FxmlUtil.LoadResult<MyDataPassView> getDetailView = FxmlUtil.load("/fxml/settings/internetServices/MyDataPass.fxml"); Alert alert = AlertDlgHelper.saveDialog( "Κωδικοί MyData", getDetailView.getParent(), menuBar.getScene().getWindow()); getDetailView.getController().companyPassLoad(); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { if (getDetailView.getController() != null) { getDetailView.getController().save(); } } } @FXML private void onMeasureUnits(ActionEvent event) { FxmlUtil.LoadResult<MeasurementUnitsListView> getListView = FxmlUtil.load("/fxml/tables/measurementUnits/MeasurementUnitsListView.fxml"); Node measure = (Node) getListView.getParent(); showAsTab(measure, "Μονάδες Μέτρησης"); } @FXML private void onVat(ActionEvent event) { FxmlUtil.LoadResult<VatListView> getListView = FxmlUtil.load("/fxml/tables/vat/VatListView.fxml"); Node measure = (Node) getListView.getParent(); showAsTab(measure, "Συντελεστές Φ.Π.Α."); } @FXML private void onInvoiceSeries(ActionEvent event) {} @FXML private void onInitTables(ActionEvent event) {} }
5525_15
package gr.aueb.CIP2014.graphs; import gr.aueb.CIP2014.graphics.Rendering; import gr.aueb.CIP2014.misc.IO; import gr.aueb.CIP2014.misc.MathMethods; import gr.aueb.CIP2014.misc.StringFormatting; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.TreeMap; import javax.swing.JOptionPane; import org.apache.commons.io.FileUtils; import org.neo4j.graphalgo.CostEvaluator; import org.neo4j.graphalgo.GraphAlgoFactory; import org.neo4j.graphalgo.PathFinder; import org.neo4j.graphalgo.WeightedPath; import org.neo4j.graphalgo.impl.util.DoubleEvaluator; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipExpander; import org.neo4j.graphdb.RelationshipType; import org.neo4j.kernel.Traversal; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.impls.neo4j.Neo4jGraph; import com.tinkerpop.blueprints.impls.neo4j.Neo4jVertex; import com.tinkerpop.blueprints.oupls.jung.GraphJung; public class BasicGraph { enum CIRelationships implements RelationshipType { PHYSICAL, INFORMATIONAL } Neo4jGraph graph; // CI_impact is Impact table with range: [1, 5] // CI_likelihood is Likelihood table with range: [0.1, 1] public void createGraph(int number, int[][] CI_impact, double[][] CI_likelihood) { String path = "CIP_graph.db"; File dir = new File(path); try { FileUtils.deleteDirectory(dir); } catch (IOException e1) { e1.printStackTrace(); } graph = new Neo4jGraph(path); // Create a TREEMAP Object containing all CIs generated TreeMap<String, Neo4jVertex> CIs = new TreeMap<String, Neo4jVertex>(); // Create random CIs and fill them with information CIs = createRandomCIsWithInfo(number, CIs, graph); // Create random connections between CIs createRandomConnectionsToCIs(number, CI_impact, CI_likelihood, CIs); long graphAnalysisStart = System.currentTimeMillis(); // Get all paths and export them to Excel file if (!allPathsToExcel(CIs)) { JOptionPane.showMessageDialog(null, "ERROR: Excel: Paths were not exported"); System.exit(-1); } // Get the cheapest path for inverseRisk using Dijkstra algorithm. // This is the maximum-weight path for normal Risk. PathFinder<WeightedPath> finder = mydijkstra( Traversal.expanderForAllTypes(Direction.OUTGOING), //PathExpander.(CIRelationships.PHYSICAL, Direction.BOTH ), new DoubleEvaluator("inverseRisk")); WeightedPath p = minPathofAllDijkstraPaths(CIs, finder); System.out.println("START: " + p.startNode() + " END: " + p.endNode()); // Get the weight of the path detected as maximum-weight path. System.out.println(p); for ( Relationship rel : p.relationships()) { Node node1 = rel.getStartNode(); node1.setProperty("maxPath", true); Node node2 = rel.getEndNode(); node2.setProperty("maxPath", true); rel.setProperty("maxPath", true); } graph.commit(); // Render created graph online Rendering render = new Rendering(); render.visualize(new GraphJung<Neo4jGraph>(graph)); // Compute total time spent to analyze paths in graph long graphAnalysisEnd = System.currentTimeMillis(); float totalAnalysisTime = (float)(graphAnalysisEnd - graphAnalysisStart) / 1000f; JOptionPane.showMessageDialog(null, "Graph Analysis Time: " + totalAnalysisTime + " seconds"); //graph.shutdown(); } /**************************************************************************** * Create random CIs, fill them with info and, thus, form the graph * ****************************************************************************/ private TreeMap<String, Neo4jVertex> createRandomCIsWithInfo (int number, TreeMap<String, Neo4jVertex> CIs, Neo4jGraph graph) { /* Generate a list of CI_SECTORS and randomly choose one for each CI * * ============================================================ * Critical Infrastructure Sectors - USA Homeland Security List * (https://www.dhs.gov/critical-infrastructure-sectors) * ============================================================ * PPD-21 identifies 16 critical infrastructure sectors: * * - Chemical Sector * - Commercial Facilities Sector * - Communications Sector * - Critical Manufacturing Sector * - Dams Sector * - Defense Industrial Base Sector * - Emergency Services Sector * - Energy Sector * - Financial Services Sector * - Food and Agriculture Sector * - Government Facilities Sector * - Healthcare and Public Health Sector * - Information Technology Sector * - Nuclear Reactors, Materials, and Waste Sector * - Transportation Systems Sector * - Water and Waste-water Systems Sector */ List<String> randomSector = new LinkedList<String>(); randomSector.add("Chemical"); randomSector.add("Commercial Facilities"); randomSector.add("Communications"); randomSector.add("Critical Manufacturing"); randomSector.add("Dams"); randomSector.add("Defense Industrial Base"); randomSector.add("Emergency Services"); randomSector.add("Energy"); randomSector.add("Financial Services"); randomSector.add("Food and Agriculture"); randomSector.add("Government Facilities"); randomSector.add("Healthcare and Public Health"); randomSector.add("Information Technology"); randomSector.add("Nuclear Reactors, Materials, and Waste"); randomSector.add("Transportation Systems"); randomSector.add("Water and Wastewater Systems"); // Create random CIs for (int i=0; i<number; i++) { Neo4jVertex ci = (Neo4jVertex) graph.addVertex(null); ci.setProperty("CI_ID", ("CI_"+(i+1))); Collections.shuffle(randomSector); ci.setProperty("ci_sector", randomSector.get(0)); ci.setProperty("ci_subsector", "NULL"); String substation_id = ci.getProperty("CI_ID")+"-"+Integer.toString(i+1); ci.setProperty("substation_id", substation_id); //Μορφή "CI-ID"-X όπου Χ αύξοντας αριθμός ci.setProperty("substation_Name", "CI_Name_"+(i+1)); ci.setProperty("CI_OPERATOR", ("Infrastructure_"+(i+1))); ci.setProperty("location_latitude", "15"); ci.setProperty("location_longtitude", "51"); ci.setProperty("maxPath", false); CIs.put("CI_"+i, ci); } return CIs; } /**************************************************************************** * Create random connections between CIs and, thus, form the graph * * * * The weight of each edge is: Risk = Likelihood * Impact. * * According to CIP-2013, the Cascading Risk is: C_Risk = Sum(Risk) of all * * Risks in edges of a given path. * ****************************************************************************/ private void createRandomConnectionsToCIs (int number, int[][] CI_impact, double[][] CI_likelihood, TreeMap<String, Neo4jVertex> CIs) { Random intRandom = new Random(); int numOfEdgesPerGraph; for (int i=0; i<number; i++) { numOfEdgesPerGraph = intRandom.nextInt(3 - 1 + 1) + 1; for (int j=0; j<numOfEdgesPerGraph; j++) { // Randomly choose another CI to create an Edge in graph int ciToConnect = intRandom.nextInt((number-1) - 0 + 1) + 0; //number-1 so as not to produce a '10', since CI_9 is the last one if number is 10 // Don't connect a CI to itself while (ciToConnect == i) ciToConnect = intRandom.nextInt((number-1) - 0 + 1) + 0; try { Node n1 = CIs.get("CI_"+i).getRawVertex(); Node n2 = CIs.get("CI_"+ciToConnect).getRawVertex(); double risk = CI_impact[i][ciToConnect] * CI_likelihood[i][ciToConnect]; // Different way to create Edges using TinkerPop // Edge e = graph.addEdge(null, CIs.get("CI_"+i), CIs.get("CI_"+ciToConnect), ("Risk="+Double.toString(risk))); Relationship e = (n1).createRelationshipTo(n2, CIRelationships.PHYSICAL); e.setProperty("isActive", 1); e.setProperty("impact", (double)(CI_impact[i][ciToConnect])); e.setProperty("likelihood", (double)(CI_likelihood[i][ciToConnect])); // We will use an "inverseRisk" property, since searching for the maximum weight path, // is the path with the smallest negative weight (negation of the normal Risk values). e.setProperty("risk", risk); e.setProperty("inverseRisk", -risk); // A flag to use for the max-weight path when determined e.setProperty("maxPath", false); } catch(NullPointerException e) { System.out.println("NullPointerException in: BasicGraph.createGraph() | Instruction: graph.addEdge()"); } } } } /**************************************************************************** * Get all paths in the graph and export them to an Excel (.xls) file * ****************************************************************************/ private boolean allPathsToExcel(TreeMap<String, Neo4jVertex> CIs) { List<String> pathList = new ArrayList<String>(); List<WP> allPathsWithWeight = new ArrayList<WP>(); PathFinder<Path> finder = GraphAlgoFactory.allPaths(Traversal.expanderForAllTypes(Direction.OUTGOING), 5); for(Map.Entry<String,Neo4jVertex> entry1 : CIs.entrySet()) { Neo4jVertex startvertex = entry1.getValue(); // For each node, check paths to all other nodes for(Map.Entry<String,Neo4jVertex> entry2 : CIs.entrySet()) { Neo4jVertex endvertex = entry2.getValue(); // Get ALL paths between 2 nodes if (!startvertex.equals(endvertex)) { for (Path allPaths : finder.findAllPaths(startvertex.getRawVertex(), endvertex.getRawVertex())) { StringFormatting s = new StringFormatting(); s.setThePath(allPaths); String p = s.renderAndCalculateWeight(allPaths, "substation_id", "cRisk"); s.setStringListPath(p); allPathsWithWeight.add(s.addWP()); // Add object with weight and path to sort and get the maximum one } } } } // Sort all possible paths according to weight (double value) Collections.sort(allPathsWithWeight, new Comparator<WP>() { @Override public int compare(WP c1, WP c2) { return Double.compare(c1.getWeight(), c2.getWeight()); } }); WP maxWP = allPathsWithWeight.get(allPathsWithWeight.size()-1); System.out.println("Sorted max path: " + maxWP.getPath() + " Weight: " + maxWP.getWeight()); // Write all paths found to file try { IO.writeBuffered(allPathsWithWeight, 8192); JOptionPane.showMessageDialog(null, "All paths were saved to Excel at the user's Temporary Directory" + "\n(Usually in: C:\\Users\\*USERNAME*\\AppData\\Local\\Temp)"); }catch (IOException z) { System.err.println("ERROR: while writing Excel files"); } return true; } /**************************************************************************** * Call a custom implemented Dijkstra based on org.neo4j.examples.dijkstra * ****************************************************************************/ public static PathFinder<WeightedPath> mydijkstra( RelationshipExpander expander, CostEvaluator<Double> costEvaluator ) { return new MyDijkstra( expander, costEvaluator ); } /******************************************************************************** * Find the cheapest (dijkstra) path for each Vertex. * * This path is the maximum weight path since actual Edge weights are inversed. * * (weight = 1/actual_weight) * * ******************************************************************************/ private WeightedPath minPathofAllDijkstraPaths(TreeMap<String, Neo4jVertex> CIs, PathFinder<WeightedPath> finder) { TreeMap<String, WeightedPath> paths = new TreeMap<String, WeightedPath>(); long index = 1; for(Map.Entry<String,Neo4jVertex> entry1 : CIs.entrySet()) { Neo4jVertex startvertex = entry1.getValue(); for(Map.Entry<String,Neo4jVertex> entry2 : CIs.entrySet()) { String key = Long.toString(index); // Create a key for each path based on a counter index++; Neo4jVertex endvertex = entry2.getValue(); WeightedPath p = finder.findSinglePath( startvertex.getRawVertex(), endvertex.getRawVertex()); if ( p != null && !startvertex.equals(endvertex)) paths.put(key, p); // FIXED: KEYS must not get replaced when same nodes are being analyzed } } String maxkey = null; double max = 0; for(Map.Entry<String,WeightedPath> entry : paths.entrySet()) { WeightedPath tempP = entry.getValue(); if (tempP != null) { double temp = tempP.weight(); if (max > temp) { // Since we are searching for the maximum weight path, i.e. the path with the smallest negative weight max = temp; // (smallest negative = biggest positive weight if you change the sign maxkey = entry.getKey(); } } } WeightedPath p = null; try { p = paths.get(maxkey); }catch(NullPointerException z) { // If no paths were found in this random graph, then exit the program JOptionPane.showMessageDialog(null, "DIJKSTRA: ERROR: The random graph does not contain any paths with the desired depth"); System.exit(-1); } return p; } }
geostergiop/CIDA
CIP2014/src/gr/aueb/CIP2014/graphs/BasicGraph.java
3,786
//Μορφή "CI-ID"-X όπου Χ αύξοντας αριθμός
line_comment
el
package gr.aueb.CIP2014.graphs; import gr.aueb.CIP2014.graphics.Rendering; import gr.aueb.CIP2014.misc.IO; import gr.aueb.CIP2014.misc.MathMethods; import gr.aueb.CIP2014.misc.StringFormatting; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.TreeMap; import javax.swing.JOptionPane; import org.apache.commons.io.FileUtils; import org.neo4j.graphalgo.CostEvaluator; import org.neo4j.graphalgo.GraphAlgoFactory; import org.neo4j.graphalgo.PathFinder; import org.neo4j.graphalgo.WeightedPath; import org.neo4j.graphalgo.impl.util.DoubleEvaluator; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipExpander; import org.neo4j.graphdb.RelationshipType; import org.neo4j.kernel.Traversal; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.impls.neo4j.Neo4jGraph; import com.tinkerpop.blueprints.impls.neo4j.Neo4jVertex; import com.tinkerpop.blueprints.oupls.jung.GraphJung; public class BasicGraph { enum CIRelationships implements RelationshipType { PHYSICAL, INFORMATIONAL } Neo4jGraph graph; // CI_impact is Impact table with range: [1, 5] // CI_likelihood is Likelihood table with range: [0.1, 1] public void createGraph(int number, int[][] CI_impact, double[][] CI_likelihood) { String path = "CIP_graph.db"; File dir = new File(path); try { FileUtils.deleteDirectory(dir); } catch (IOException e1) { e1.printStackTrace(); } graph = new Neo4jGraph(path); // Create a TREEMAP Object containing all CIs generated TreeMap<String, Neo4jVertex> CIs = new TreeMap<String, Neo4jVertex>(); // Create random CIs and fill them with information CIs = createRandomCIsWithInfo(number, CIs, graph); // Create random connections between CIs createRandomConnectionsToCIs(number, CI_impact, CI_likelihood, CIs); long graphAnalysisStart = System.currentTimeMillis(); // Get all paths and export them to Excel file if (!allPathsToExcel(CIs)) { JOptionPane.showMessageDialog(null, "ERROR: Excel: Paths were not exported"); System.exit(-1); } // Get the cheapest path for inverseRisk using Dijkstra algorithm. // This is the maximum-weight path for normal Risk. PathFinder<WeightedPath> finder = mydijkstra( Traversal.expanderForAllTypes(Direction.OUTGOING), //PathExpander.(CIRelationships.PHYSICAL, Direction.BOTH ), new DoubleEvaluator("inverseRisk")); WeightedPath p = minPathofAllDijkstraPaths(CIs, finder); System.out.println("START: " + p.startNode() + " END: " + p.endNode()); // Get the weight of the path detected as maximum-weight path. System.out.println(p); for ( Relationship rel : p.relationships()) { Node node1 = rel.getStartNode(); node1.setProperty("maxPath", true); Node node2 = rel.getEndNode(); node2.setProperty("maxPath", true); rel.setProperty("maxPath", true); } graph.commit(); // Render created graph online Rendering render = new Rendering(); render.visualize(new GraphJung<Neo4jGraph>(graph)); // Compute total time spent to analyze paths in graph long graphAnalysisEnd = System.currentTimeMillis(); float totalAnalysisTime = (float)(graphAnalysisEnd - graphAnalysisStart) / 1000f; JOptionPane.showMessageDialog(null, "Graph Analysis Time: " + totalAnalysisTime + " seconds"); //graph.shutdown(); } /**************************************************************************** * Create random CIs, fill them with info and, thus, form the graph * ****************************************************************************/ private TreeMap<String, Neo4jVertex> createRandomCIsWithInfo (int number, TreeMap<String, Neo4jVertex> CIs, Neo4jGraph graph) { /* Generate a list of CI_SECTORS and randomly choose one for each CI * * ============================================================ * Critical Infrastructure Sectors - USA Homeland Security List * (https://www.dhs.gov/critical-infrastructure-sectors) * ============================================================ * PPD-21 identifies 16 critical infrastructure sectors: * * - Chemical Sector * - Commercial Facilities Sector * - Communications Sector * - Critical Manufacturing Sector * - Dams Sector * - Defense Industrial Base Sector * - Emergency Services Sector * - Energy Sector * - Financial Services Sector * - Food and Agriculture Sector * - Government Facilities Sector * - Healthcare and Public Health Sector * - Information Technology Sector * - Nuclear Reactors, Materials, and Waste Sector * - Transportation Systems Sector * - Water and Waste-water Systems Sector */ List<String> randomSector = new LinkedList<String>(); randomSector.add("Chemical"); randomSector.add("Commercial Facilities"); randomSector.add("Communications"); randomSector.add("Critical Manufacturing"); randomSector.add("Dams"); randomSector.add("Defense Industrial Base"); randomSector.add("Emergency Services"); randomSector.add("Energy"); randomSector.add("Financial Services"); randomSector.add("Food and Agriculture"); randomSector.add("Government Facilities"); randomSector.add("Healthcare and Public Health"); randomSector.add("Information Technology"); randomSector.add("Nuclear Reactors, Materials, and Waste"); randomSector.add("Transportation Systems"); randomSector.add("Water and Wastewater Systems"); // Create random CIs for (int i=0; i<number; i++) { Neo4jVertex ci = (Neo4jVertex) graph.addVertex(null); ci.setProperty("CI_ID", ("CI_"+(i+1))); Collections.shuffle(randomSector); ci.setProperty("ci_sector", randomSector.get(0)); ci.setProperty("ci_subsector", "NULL"); String substation_id = ci.getProperty("CI_ID")+"-"+Integer.toString(i+1); ci.setProperty("substation_id", substation_id); //Μορφή "CI-ID"-X<SUF> ci.setProperty("substation_Name", "CI_Name_"+(i+1)); ci.setProperty("CI_OPERATOR", ("Infrastructure_"+(i+1))); ci.setProperty("location_latitude", "15"); ci.setProperty("location_longtitude", "51"); ci.setProperty("maxPath", false); CIs.put("CI_"+i, ci); } return CIs; } /**************************************************************************** * Create random connections between CIs and, thus, form the graph * * * * The weight of each edge is: Risk = Likelihood * Impact. * * According to CIP-2013, the Cascading Risk is: C_Risk = Sum(Risk) of all * * Risks in edges of a given path. * ****************************************************************************/ private void createRandomConnectionsToCIs (int number, int[][] CI_impact, double[][] CI_likelihood, TreeMap<String, Neo4jVertex> CIs) { Random intRandom = new Random(); int numOfEdgesPerGraph; for (int i=0; i<number; i++) { numOfEdgesPerGraph = intRandom.nextInt(3 - 1 + 1) + 1; for (int j=0; j<numOfEdgesPerGraph; j++) { // Randomly choose another CI to create an Edge in graph int ciToConnect = intRandom.nextInt((number-1) - 0 + 1) + 0; //number-1 so as not to produce a '10', since CI_9 is the last one if number is 10 // Don't connect a CI to itself while (ciToConnect == i) ciToConnect = intRandom.nextInt((number-1) - 0 + 1) + 0; try { Node n1 = CIs.get("CI_"+i).getRawVertex(); Node n2 = CIs.get("CI_"+ciToConnect).getRawVertex(); double risk = CI_impact[i][ciToConnect] * CI_likelihood[i][ciToConnect]; // Different way to create Edges using TinkerPop // Edge e = graph.addEdge(null, CIs.get("CI_"+i), CIs.get("CI_"+ciToConnect), ("Risk="+Double.toString(risk))); Relationship e = (n1).createRelationshipTo(n2, CIRelationships.PHYSICAL); e.setProperty("isActive", 1); e.setProperty("impact", (double)(CI_impact[i][ciToConnect])); e.setProperty("likelihood", (double)(CI_likelihood[i][ciToConnect])); // We will use an "inverseRisk" property, since searching for the maximum weight path, // is the path with the smallest negative weight (negation of the normal Risk values). e.setProperty("risk", risk); e.setProperty("inverseRisk", -risk); // A flag to use for the max-weight path when determined e.setProperty("maxPath", false); } catch(NullPointerException e) { System.out.println("NullPointerException in: BasicGraph.createGraph() | Instruction: graph.addEdge()"); } } } } /**************************************************************************** * Get all paths in the graph and export them to an Excel (.xls) file * ****************************************************************************/ private boolean allPathsToExcel(TreeMap<String, Neo4jVertex> CIs) { List<String> pathList = new ArrayList<String>(); List<WP> allPathsWithWeight = new ArrayList<WP>(); PathFinder<Path> finder = GraphAlgoFactory.allPaths(Traversal.expanderForAllTypes(Direction.OUTGOING), 5); for(Map.Entry<String,Neo4jVertex> entry1 : CIs.entrySet()) { Neo4jVertex startvertex = entry1.getValue(); // For each node, check paths to all other nodes for(Map.Entry<String,Neo4jVertex> entry2 : CIs.entrySet()) { Neo4jVertex endvertex = entry2.getValue(); // Get ALL paths between 2 nodes if (!startvertex.equals(endvertex)) { for (Path allPaths : finder.findAllPaths(startvertex.getRawVertex(), endvertex.getRawVertex())) { StringFormatting s = new StringFormatting(); s.setThePath(allPaths); String p = s.renderAndCalculateWeight(allPaths, "substation_id", "cRisk"); s.setStringListPath(p); allPathsWithWeight.add(s.addWP()); // Add object with weight and path to sort and get the maximum one } } } } // Sort all possible paths according to weight (double value) Collections.sort(allPathsWithWeight, new Comparator<WP>() { @Override public int compare(WP c1, WP c2) { return Double.compare(c1.getWeight(), c2.getWeight()); } }); WP maxWP = allPathsWithWeight.get(allPathsWithWeight.size()-1); System.out.println("Sorted max path: " + maxWP.getPath() + " Weight: " + maxWP.getWeight()); // Write all paths found to file try { IO.writeBuffered(allPathsWithWeight, 8192); JOptionPane.showMessageDialog(null, "All paths were saved to Excel at the user's Temporary Directory" + "\n(Usually in: C:\\Users\\*USERNAME*\\AppData\\Local\\Temp)"); }catch (IOException z) { System.err.println("ERROR: while writing Excel files"); } return true; } /**************************************************************************** * Call a custom implemented Dijkstra based on org.neo4j.examples.dijkstra * ****************************************************************************/ public static PathFinder<WeightedPath> mydijkstra( RelationshipExpander expander, CostEvaluator<Double> costEvaluator ) { return new MyDijkstra( expander, costEvaluator ); } /******************************************************************************** * Find the cheapest (dijkstra) path for each Vertex. * * This path is the maximum weight path since actual Edge weights are inversed. * * (weight = 1/actual_weight) * * ******************************************************************************/ private WeightedPath minPathofAllDijkstraPaths(TreeMap<String, Neo4jVertex> CIs, PathFinder<WeightedPath> finder) { TreeMap<String, WeightedPath> paths = new TreeMap<String, WeightedPath>(); long index = 1; for(Map.Entry<String,Neo4jVertex> entry1 : CIs.entrySet()) { Neo4jVertex startvertex = entry1.getValue(); for(Map.Entry<String,Neo4jVertex> entry2 : CIs.entrySet()) { String key = Long.toString(index); // Create a key for each path based on a counter index++; Neo4jVertex endvertex = entry2.getValue(); WeightedPath p = finder.findSinglePath( startvertex.getRawVertex(), endvertex.getRawVertex()); if ( p != null && !startvertex.equals(endvertex)) paths.put(key, p); // FIXED: KEYS must not get replaced when same nodes are being analyzed } } String maxkey = null; double max = 0; for(Map.Entry<String,WeightedPath> entry : paths.entrySet()) { WeightedPath tempP = entry.getValue(); if (tempP != null) { double temp = tempP.weight(); if (max > temp) { // Since we are searching for the maximum weight path, i.e. the path with the smallest negative weight max = temp; // (smallest negative = biggest positive weight if you change the sign maxkey = entry.getKey(); } } } WeightedPath p = null; try { p = paths.get(maxkey); }catch(NullPointerException z) { // If no paths were found in this random graph, then exit the program JOptionPane.showMessageDialog(null, "DIJKSTRA: ERROR: The random graph does not contain any paths with the desired depth"); System.exit(-1); } return p; } }
7085_14
package com.getout.component; import com.getout.service.IndexMap; import com.getout.service.WordFrequencyBatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.io.IOException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.*; @Service public class ScheduledTasks { @Autowired private WordFrequencyBatch wordFrequencyBatch; @Autowired private IndexMap indexMap; public ScheduledTasks(WordFrequencyBatch wordFrequencyBatch) { this.wordFrequencyBatch = wordFrequencyBatch; } ; // @Scheduled(cron = "0 05 18 * * *") // public void scheduleKeywordCountTask() { //// logger.info("Starting scheduled task for keyword count..."); // // Use indexName and toIndex here // } public void scheduleKeywordCountTask( List<String> keywords,String fromIndex,String toIndex, String startDate, String endDate ) { System.out.println("Index = " + fromIndex); System.out.println("Keywords = " + keywords); System.out.println("EndIndex = " + toIndex); System.out.println("startDate = " + startDate); System.out.println("endDate = " + endDate); ExecutorService executorService = Executors.newFixedThreadPool(4); List<Future<KeywordResult>> futures = new ArrayList<>(); for (String keyword : keywords) { final String currentKeyword = keyword; Callable<KeywordResult> task = () -> { try { // System.out.println("Keyword " + keyword ); Map<LocalDate, Integer> resultMap = wordFrequencyBatch.searchKeywordFrequency(fromIndex, toIndex, currentKeyword, startDate, endDate); return new KeywordResult(currentKeyword, resultMap); } catch (Exception e) { // logger.error("Error processing keyword: " + currentKeyword, e); return new KeywordResult(currentKeyword, Collections.emptyMap()); } }; futures.add(executorService.submit(task)); } for (Future<KeywordResult> future : futures) { try { KeywordResult result = future.get(); Map<LocalDate, Integer> resultMap = result.getFrequencyMap(); if (!resultMap.isEmpty()) { indexMap.indexSortedMap(fromIndex, new TreeMap<>(resultMap), result.getKeyword(), toIndex); } // logger.info("Result for keyword '" + result.getKeyword() + "': " + resultMap); } catch (InterruptedException | ExecutionException e) { // logger.error("Error retrieving keyword count result", e); } catch (IOException e) { throw new RuntimeException(e); } } executorService.shutdown(); // logger.info("Finished scheduled task for keyword count."); } } // @Scheduled(cron = "0 53 21 * * *") // public void scheduleTopicCountTask() { // logger.info("Starting scheduled task for keyword count..."); // // // Define the topics and their associated keywords // Map<String, List<String>> topicKeywords = new HashMap<>(); // topicKeywords.put("Μεταναστευτικό", Arrays.asList("μετανάστης", "διακινητής")); // topicKeywords.put("Οικονομία", Arrays.asList("ευρώ", "τράπεζα")); // // add more topics and their associated keywords... // // // Calculate the time frame for the search // DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; // LocalDateTime now = LocalDateTime.now(); // String endDate = now.format(formatter); // String startDate = now.minusDays(30).format(formatter); // // System.out.println("Start date: " + startDate); // System.out.println("End date: " + endDate); // // // Initialize an ExecutorService with a fixed number of threads // int numberOfThreads = 4; // Adjust this value according to your system's capabilities // ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads); // // // Prepare a list of futures // List<Future<Map<LocalDate, Integer>>> futures = new ArrayList<>(); // // // Search for keyword counts within the specified time frame using multiple threads // for (Map.Entry<String, List<String>> entry : topicKeywords.entrySet()) { // String topic = entry.getKey(); // List<String> keywords = entry.getValue(); // // Callable<Map<LocalDate, Integer>> task = () -> { // try { // return wordFrequencyBatch.searchTopicFrequency("norconex2","norconex2_counts", topic, keywords, 500, startDate, endDate); // } catch (Exception e) { // logger.error("Error processing keywords for topic: " + topic, e); // return Collections.emptyMap(); // } // }; // futures.add(executorService.submit(task)); // } // // // Wait for all tasks to complete and print the results // for (Future<Map<LocalDate, Integer>> future : futures) { // try { // Map<LocalDate, Integer> resultMap = future.get(); // logger.info("Result: " + resultMap); // } catch (InterruptedException | ExecutionException e) { // logger.error("Error retrieving keyword count result", e); // } // } // // // Shutdown the ExecutorService // executorService.shutdown(); // // logger.info("Finished scheduled task for keyword count."); // }
giannisni/newstracker-full
verse/src/main/java/com/getout/component/ScheduledTasks.java
1,411
// topicKeywords.put("Μεταναστευτικό", Arrays.asList("μετανάστης", "διακινητής"));
line_comment
el
package com.getout.component; import com.getout.service.IndexMap; import com.getout.service.WordFrequencyBatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.io.IOException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.*; @Service public class ScheduledTasks { @Autowired private WordFrequencyBatch wordFrequencyBatch; @Autowired private IndexMap indexMap; public ScheduledTasks(WordFrequencyBatch wordFrequencyBatch) { this.wordFrequencyBatch = wordFrequencyBatch; } ; // @Scheduled(cron = "0 05 18 * * *") // public void scheduleKeywordCountTask() { //// logger.info("Starting scheduled task for keyword count..."); // // Use indexName and toIndex here // } public void scheduleKeywordCountTask( List<String> keywords,String fromIndex,String toIndex, String startDate, String endDate ) { System.out.println("Index = " + fromIndex); System.out.println("Keywords = " + keywords); System.out.println("EndIndex = " + toIndex); System.out.println("startDate = " + startDate); System.out.println("endDate = " + endDate); ExecutorService executorService = Executors.newFixedThreadPool(4); List<Future<KeywordResult>> futures = new ArrayList<>(); for (String keyword : keywords) { final String currentKeyword = keyword; Callable<KeywordResult> task = () -> { try { // System.out.println("Keyword " + keyword ); Map<LocalDate, Integer> resultMap = wordFrequencyBatch.searchKeywordFrequency(fromIndex, toIndex, currentKeyword, startDate, endDate); return new KeywordResult(currentKeyword, resultMap); } catch (Exception e) { // logger.error("Error processing keyword: " + currentKeyword, e); return new KeywordResult(currentKeyword, Collections.emptyMap()); } }; futures.add(executorService.submit(task)); } for (Future<KeywordResult> future : futures) { try { KeywordResult result = future.get(); Map<LocalDate, Integer> resultMap = result.getFrequencyMap(); if (!resultMap.isEmpty()) { indexMap.indexSortedMap(fromIndex, new TreeMap<>(resultMap), result.getKeyword(), toIndex); } // logger.info("Result for keyword '" + result.getKeyword() + "': " + resultMap); } catch (InterruptedException | ExecutionException e) { // logger.error("Error retrieving keyword count result", e); } catch (IOException e) { throw new RuntimeException(e); } } executorService.shutdown(); // logger.info("Finished scheduled task for keyword count."); } } // @Scheduled(cron = "0 53 21 * * *") // public void scheduleTopicCountTask() { // logger.info("Starting scheduled task for keyword count..."); // // // Define the topics and their associated keywords // Map<String, List<String>> topicKeywords = new HashMap<>(); // topicKeywords.put("Μεταναστευτικό", Arrays.asList("μετανάστης",<SUF> // topicKeywords.put("Οικονομία", Arrays.asList("ευρώ", "τράπεζα")); // // add more topics and their associated keywords... // // // Calculate the time frame for the search // DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; // LocalDateTime now = LocalDateTime.now(); // String endDate = now.format(formatter); // String startDate = now.minusDays(30).format(formatter); // // System.out.println("Start date: " + startDate); // System.out.println("End date: " + endDate); // // // Initialize an ExecutorService with a fixed number of threads // int numberOfThreads = 4; // Adjust this value according to your system's capabilities // ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads); // // // Prepare a list of futures // List<Future<Map<LocalDate, Integer>>> futures = new ArrayList<>(); // // // Search for keyword counts within the specified time frame using multiple threads // for (Map.Entry<String, List<String>> entry : topicKeywords.entrySet()) { // String topic = entry.getKey(); // List<String> keywords = entry.getValue(); // // Callable<Map<LocalDate, Integer>> task = () -> { // try { // return wordFrequencyBatch.searchTopicFrequency("norconex2","norconex2_counts", topic, keywords, 500, startDate, endDate); // } catch (Exception e) { // logger.error("Error processing keywords for topic: " + topic, e); // return Collections.emptyMap(); // } // }; // futures.add(executorService.submit(task)); // } // // // Wait for all tasks to complete and print the results // for (Future<Map<LocalDate, Integer>> future : futures) { // try { // Map<LocalDate, Integer> resultMap = future.get(); // logger.info("Result: " + resultMap); // } catch (InterruptedException | ExecutionException e) { // logger.error("Error retrieving keyword count result", e); // } // } // // // Shutdown the ExecutorService // executorService.shutdown(); // // logger.info("Finished scheduled task for keyword count."); // }
38_16
/** * */ package pathfinding; import java.awt.Point; import java.util.ArrayList; import java.util.LinkedList; import java.util.Random; /** * @author anagno * */ public class PSO { public PSO(Point start, Point goal, Map map, int population) { map_ = map; start_ = map_.getNode(start); goal_ = map_.getNode(goal); population_ = population; particles_ = new Particle[population_]; //TODO } public LinkedList<Node> findPath() { calculatePSO(); LinkedList<Node> solution = new LinkedList<Node>(); solution.addAll(global_best_.getPosition()); return solution; } // Να βρω καλύτερο όνομα. Κατ' ουσία ειναι η κύρια μέθοδος public void calculatePSO() { initializePopulation(); global_best_ = particles_[0]; for (int idx=1; idx<population_; ++idx) { //if (particles_[i].position<pbest) // particles_[i].pbest = current position if (particles_[idx].getFitness() < global_best_.getFitness() ) { global_best_ = particles_[idx]; } // compute velocity // u_p(t) = u_p(t-1) +c1*rand_1(pbest(t-1) - x(t-1)) +c2*rand_2(gbest(t-1) - x(t-2)) //w=inertia factor // update position // x(t) = x(t-1) + u_p(t) } } // Function that initializes the population public void initializePopulation() { for (int idx = 0; idx <population_; ) { ArrayList<Node> possible_solution = new ArrayList<Node>(); ArrayList<Node> used_nodes = new ArrayList<Node>(); possible_solution.add(start_); used_nodes.add(start_); BEGIN_OF_SOLUTION: while(true) { Node current_node = possible_solution.get(possible_solution.size() - 1), next_node; // Άμα δεν υπάρχουν ακμες αφαιρούμε το κόμβο και τον προσθέτουμε στους χρησιμοποιημένους και πάμε // ένα βήμα πίσω. // Θεωρητικά δεν πρέπει να χρησιμοποιηθεί ο κώδικας μιας και ελέγχουμε αν ειναι // εμπόδιο στον κώδικα (μόνο αν είναι εμπόδιο ο κόμβος δεν έχει ακμές) -- ΔΕΝ ΙΣΧΥΕΙ !!! // Αφαίρεσα τον κώδικα που ελέγχει για εμπόδια διότι έδεινε χειρότερες λύσεις ... // ΔΕΝ ΕΧΩ ΙΔΕΑ ΓΙΑ ΠΟΙΟ ΛΟΓΟ !!! if (current_node.getEdges() == null) { used_nodes.add(current_node); possible_solution.remove(possible_solution.size() - 1); break BEGIN_OF_SOLUTION; } //Γιατί άμα την αφαιρέσω απ` ευθείας, επειδή είναι δείκτης φεύγει για πάντα !!! @SuppressWarnings("unchecked") ArrayList<Node> edges = (ArrayList<Node>) current_node.getEdges().clone(); // Διαλέγουμε τον επόμενο κόμβο εδώ while(edges.size()>=0) { // Έχουμε χρησιμοποιήσει όλες τις ενναλακτικές και δεν μπορούμε να πάμε κάπου αλλου άρα πάμε πίσω. if (edges.isEmpty() ) { possible_solution.remove(possible_solution.size() - 1); break; } // Διαλέγουμε έναν κόμβο στην τύχη int rand_number = randInt(0, edges.size()-1); next_node = edges.remove(rand_number); // next_node.isObstacle() || . Εναλακτικά θα μπορούσαμε να βάλουμε και αυτό μέσα αλλά για κάποιο λόγο // χωρίς αυτό η λύση είναι καλύτερη. // Άμα διαλέξουμε κάποιο κόμβο που έχουμε ήδη χρησιμοποιήσει προχωράμε if( used_nodes.contains(next_node)) { continue; } //Τον τοποθετούμε στους χρησιμοποιημένους για να μην τον ξαναχρησιμοποιήσουμε used_nodes.add(next_node); // Άμα ο επόμενος κόμβος δεν περιλαμβάνεται στην λύση τον προσθέτουμε και συνεχίζουμε if (!possible_solution.contains(next_node)) { possible_solution.add(next_node); // Άμα είναι ίσος με τον τελικό κόμβο τότε βρήκαμε την λύση if(next_node.equals(goal_)) { break BEGIN_OF_SOLUTION; } // Υπάρχουν κύκλοι στην λύση άρα δεν μας κάνει. Κανονικά δεν πρέπει να συμβεί !!! if(possible_solution.size()>= ( (map_.getHeight()*map_.getWidth()) -1) ) { break BEGIN_OF_SOLUTION; } } break; } } // Άμα έχουμε ως τελευταίο κόμβο την λύση τότε την προσθέτουμε την λύση στα σωματίδια. if (possible_solution.get(possible_solution.size() - 1) == goal_) { particles_[idx] = new Particle(possible_solution); ++idx; used_nodes.clear(); } } } //http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java public static int randInt(int min, int max) { // NOTE: Usually this should be a field rather than a method // variable so that it is not re-seeded every call. Random rand = new Random(); // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int random_num = rand.nextInt((max - min) + 1) + min; return random_num; } // The variables for representing the goal point and the start point private Node goal_, start_; // The population of the PSO private int population_; // The actual populations of particles private Particle[] particles_; // The current gbest private Particle global_best_; // The map that is used private final Map map_; private class Particle { public Particle(ArrayList<Node> solution) { position_ = new Position(solution); personal_best_ = position_; fitness_ = calculateFitness(position_); } public ArrayList<Node> getPosition() { return position_.getPosition(); } public double getFitness() { return fitness_; } public void updatePosition(ArrayList<Node> position) { position_.update(position); fitness_ = calculateFitness (position_); if( calculateFitness(personal_best_) > fitness_) { personal_best_ = position_; } } private double calculateFitness(Position position) { return (double) position.getPosition().size(); } private Position position_; //private velocity_; // The current pbest private Position personal_best_; private double fitness_; private class Position { public Position(ArrayList<Node> position) { solution_ = position; } public ArrayList<Node> getPosition() { return solution_; } public void update(ArrayList<Node> new_solution) { solution_ = new_solution; } private ArrayList<Node> solution_; } //private class Velocity //{ // Θα πρέπει να μπουν μάλλον δύο είδη κινήσεων. // Το ένα θα είναι ανεξάρτητο και θα λαμβένει υπόψιν μόνο την τωρινή // θέση του σωματιδίου ενώ το άλλο θα λαμβάνει υπόψιν // και το pbset και το gbest // private Node first_node; // private Node second_node; //} } }
giokats/PathFinding
src/pathfinding/PSO.java
2,647
// next_node.isObstacle() || . Εναλακτικά θα μπορούσαμε να βάλουμε και αυτό μέσα αλλά για κάποιο λόγο
line_comment
el
/** * */ package pathfinding; import java.awt.Point; import java.util.ArrayList; import java.util.LinkedList; import java.util.Random; /** * @author anagno * */ public class PSO { public PSO(Point start, Point goal, Map map, int population) { map_ = map; start_ = map_.getNode(start); goal_ = map_.getNode(goal); population_ = population; particles_ = new Particle[population_]; //TODO } public LinkedList<Node> findPath() { calculatePSO(); LinkedList<Node> solution = new LinkedList<Node>(); solution.addAll(global_best_.getPosition()); return solution; } // Να βρω καλύτερο όνομα. Κατ' ουσία ειναι η κύρια μέθοδος public void calculatePSO() { initializePopulation(); global_best_ = particles_[0]; for (int idx=1; idx<population_; ++idx) { //if (particles_[i].position<pbest) // particles_[i].pbest = current position if (particles_[idx].getFitness() < global_best_.getFitness() ) { global_best_ = particles_[idx]; } // compute velocity // u_p(t) = u_p(t-1) +c1*rand_1(pbest(t-1) - x(t-1)) +c2*rand_2(gbest(t-1) - x(t-2)) //w=inertia factor // update position // x(t) = x(t-1) + u_p(t) } } // Function that initializes the population public void initializePopulation() { for (int idx = 0; idx <population_; ) { ArrayList<Node> possible_solution = new ArrayList<Node>(); ArrayList<Node> used_nodes = new ArrayList<Node>(); possible_solution.add(start_); used_nodes.add(start_); BEGIN_OF_SOLUTION: while(true) { Node current_node = possible_solution.get(possible_solution.size() - 1), next_node; // Άμα δεν υπάρχουν ακμες αφαιρούμε το κόμβο και τον προσθέτουμε στους χρησιμοποιημένους και πάμε // ένα βήμα πίσω. // Θεωρητικά δεν πρέπει να χρησιμοποιηθεί ο κώδικας μιας και ελέγχουμε αν ειναι // εμπόδιο στον κώδικα (μόνο αν είναι εμπόδιο ο κόμβος δεν έχει ακμές) -- ΔΕΝ ΙΣΧΥΕΙ !!! // Αφαίρεσα τον κώδικα που ελέγχει για εμπόδια διότι έδεινε χειρότερες λύσεις ... // ΔΕΝ ΕΧΩ ΙΔΕΑ ΓΙΑ ΠΟΙΟ ΛΟΓΟ !!! if (current_node.getEdges() == null) { used_nodes.add(current_node); possible_solution.remove(possible_solution.size() - 1); break BEGIN_OF_SOLUTION; } //Γιατί άμα την αφαιρέσω απ` ευθείας, επειδή είναι δείκτης φεύγει για πάντα !!! @SuppressWarnings("unchecked") ArrayList<Node> edges = (ArrayList<Node>) current_node.getEdges().clone(); // Διαλέγουμε τον επόμενο κόμβο εδώ while(edges.size()>=0) { // Έχουμε χρησιμοποιήσει όλες τις ενναλακτικές και δεν μπορούμε να πάμε κάπου αλλου άρα πάμε πίσω. if (edges.isEmpty() ) { possible_solution.remove(possible_solution.size() - 1); break; } // Διαλέγουμε έναν κόμβο στην τύχη int rand_number = randInt(0, edges.size()-1); next_node = edges.remove(rand_number); // next_node.isObstacle() ||<SUF> // χωρίς αυτό η λύση είναι καλύτερη. // Άμα διαλέξουμε κάποιο κόμβο που έχουμε ήδη χρησιμοποιήσει προχωράμε if( used_nodes.contains(next_node)) { continue; } //Τον τοποθετούμε στους χρησιμοποιημένους για να μην τον ξαναχρησιμοποιήσουμε used_nodes.add(next_node); // Άμα ο επόμενος κόμβος δεν περιλαμβάνεται στην λύση τον προσθέτουμε και συνεχίζουμε if (!possible_solution.contains(next_node)) { possible_solution.add(next_node); // Άμα είναι ίσος με τον τελικό κόμβο τότε βρήκαμε την λύση if(next_node.equals(goal_)) { break BEGIN_OF_SOLUTION; } // Υπάρχουν κύκλοι στην λύση άρα δεν μας κάνει. Κανονικά δεν πρέπει να συμβεί !!! if(possible_solution.size()>= ( (map_.getHeight()*map_.getWidth()) -1) ) { break BEGIN_OF_SOLUTION; } } break; } } // Άμα έχουμε ως τελευταίο κόμβο την λύση τότε την προσθέτουμε την λύση στα σωματίδια. if (possible_solution.get(possible_solution.size() - 1) == goal_) { particles_[idx] = new Particle(possible_solution); ++idx; used_nodes.clear(); } } } //http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java public static int randInt(int min, int max) { // NOTE: Usually this should be a field rather than a method // variable so that it is not re-seeded every call. Random rand = new Random(); // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int random_num = rand.nextInt((max - min) + 1) + min; return random_num; } // The variables for representing the goal point and the start point private Node goal_, start_; // The population of the PSO private int population_; // The actual populations of particles private Particle[] particles_; // The current gbest private Particle global_best_; // The map that is used private final Map map_; private class Particle { public Particle(ArrayList<Node> solution) { position_ = new Position(solution); personal_best_ = position_; fitness_ = calculateFitness(position_); } public ArrayList<Node> getPosition() { return position_.getPosition(); } public double getFitness() { return fitness_; } public void updatePosition(ArrayList<Node> position) { position_.update(position); fitness_ = calculateFitness (position_); if( calculateFitness(personal_best_) > fitness_) { personal_best_ = position_; } } private double calculateFitness(Position position) { return (double) position.getPosition().size(); } private Position position_; //private velocity_; // The current pbest private Position personal_best_; private double fitness_; private class Position { public Position(ArrayList<Node> position) { solution_ = position; } public ArrayList<Node> getPosition() { return solution_; } public void update(ArrayList<Node> new_solution) { solution_ = new_solution; } private ArrayList<Node> solution_; } //private class Velocity //{ // Θα πρέπει να μπουν μάλλον δύο είδη κινήσεων. // Το ένα θα είναι ανεξάρτητο και θα λαμβένει υπόψιν μόνο την τωρινή // θέση του σωματιδίου ενώ το άλλο θα λαμβάνει υπόψιν // και το pbset και το gbest // private Node first_node; // private Node second_node; //} } }
1268_5
/* * 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 algorithmscourse; import java.util.ArrayList; import java.util.Scanner; /** * * @author MANOS */ public class AlgorithmsCourse { /** * @param args the command line arguments */ public static void main(String[] args) { //αρχή λειτουργίας Α ///*όταν το τρέχω όλο μαζί μου βγάζει error το Scanner οπότε τρέχω πρώτα την λειτουργία Α System.out.println("Quick Hull Test");//και έχω σε σχόλια την λειτουργία Β και μετά το αντίθετο Point A; Point B; QuickHull qh; ArrayList<Point> p; try (Scanner sc = new Scanner(System.in)) { System.out.println("Enter the number of points"); int N = sc.nextInt(); ArrayList<Point> points = new ArrayList<>(); System.out.println("Give me the coordinates of the starting position"); int Sx = sc.nextInt(); int Sy = sc.nextInt(); A = new Point(Sx,Sy); System.out.println("Give me the treasure's position"); int Tx = sc.nextInt(); int Ty = sc.nextInt(); B = new Point(Tx,Ty); points.add(0,A); points.add(1,B); System.out.println("Enter the coordinates of the rest points: <x> <y>"); for (int i = 2; i < N; i++) { int x = sc.nextInt(); int y = sc.nextInt(); Point e = new Point(x, y); points.add(i, e); } qh = new QuickHull(); p = qh.quickHull(points); System.out .println("The points in the Convex hull using Quick Hull are: "); for (Point p1 : p) { System.out.println("(" + p1.getX() + ", " + p1.getY() + ")"); } } qh.calculateBestPathDistance(p, A, B); //τέλος λειτουργίας Α*/ ///*αρχή λειτουργίας Β Scanner input = new Scanner(System.in); Scale sl = new Scale(); System.out.println("Give me the number of diamonds "); int number = input.nextInt(); sl.printWeightings(sl.zygaria(number)); //τέλος λειτουργίας Β*/ } }
gionanide/University_codingProjects
Algorithms/QuickHull/AlgorithmsCourse.java
723
//και έχω σε σχόλια την λειτουργία Β και μετά το αντίθετο
line_comment
el
/* * 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 algorithmscourse; import java.util.ArrayList; import java.util.Scanner; /** * * @author MANOS */ public class AlgorithmsCourse { /** * @param args the command line arguments */ public static void main(String[] args) { //αρχή λειτουργίας Α ///*όταν το τρέχω όλο μαζί μου βγάζει error το Scanner οπότε τρέχω πρώτα την λειτουργία Α System.out.println("Quick Hull Test");//και έχω<SUF> Point A; Point B; QuickHull qh; ArrayList<Point> p; try (Scanner sc = new Scanner(System.in)) { System.out.println("Enter the number of points"); int N = sc.nextInt(); ArrayList<Point> points = new ArrayList<>(); System.out.println("Give me the coordinates of the starting position"); int Sx = sc.nextInt(); int Sy = sc.nextInt(); A = new Point(Sx,Sy); System.out.println("Give me the treasure's position"); int Tx = sc.nextInt(); int Ty = sc.nextInt(); B = new Point(Tx,Ty); points.add(0,A); points.add(1,B); System.out.println("Enter the coordinates of the rest points: <x> <y>"); for (int i = 2; i < N; i++) { int x = sc.nextInt(); int y = sc.nextInt(); Point e = new Point(x, y); points.add(i, e); } qh = new QuickHull(); p = qh.quickHull(points); System.out .println("The points in the Convex hull using Quick Hull are: "); for (Point p1 : p) { System.out.println("(" + p1.getX() + ", " + p1.getY() + ")"); } } qh.calculateBestPathDistance(p, A, B); //τέλος λειτουργίας Α*/ ///*αρχή λειτουργίας Β Scanner input = new Scanner(System.in); Scale sl = new Scale(); System.out.println("Give me the number of diamonds "); int number = input.nextInt(); sl.printWeightings(sl.zygaria(number)); //τέλος λειτουργίας Β*/ } }
1978_0
package com.ots.trainingapi.global.utils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class TextUtils { private static final Logger logger = LogManager.getLogger(TextUtils.class); /** * Μετατροπή του δοθέντος αλφαριθμητικού σε κεφαλαία. Η μέθοδος φροντίζει για * την αφαίρεση των τόνων από τα ελληνικά φωνήεντα. * * @param text - Το αλφαριθμητικό προς μετατροπή * @return Το αλφαριθμητικό με κεφαλαία γράμματα και χωρίς τόνους */ public static String toUpperCaseGreekSupport(String text) { if (text == null) { return null; } else { text = text.toUpperCase(); text = text.replace("Ά", "Α"); text = text.replace("Έ", "Ε"); text = text.replace("Ή", "Η"); text = text.replace("Ί", "Ι"); text = text.replace("Ό", "Ο"); text = text.replace("Ύ", "Υ"); text = text.replace("Ώ", "Ω"); return text; } } /** * Μετατροπή του δοθέντος αλφαριθμητικού σε κεφαλαία αφαιρώντας σημεία στίξης. * Η μέθοδος φροντίζει για την αφαίρεση των τόνων και των διαλυτικών από τα * ελληνικά φωνήεντα. * * @param text - Το αλφαριθμητικό προς μετατροπή * @return Το αλφαριθμητικό με κεφαλαία γράμματα και χωρίς τόνους και * διαλυτικά */ public static String toUpperCaseGreekSupportExtended(String text) { return toUpperCaseGreekSupportExtended(text, false); } public static String toUpperCaseGreekSupportExtended(String text, boolean removeApostrophes) { if (text == null) { return null; } else { text = text.replace("ΐ", "ϊ"); text = text.replace("ΰ", "ϋ"); text = text.toUpperCase(); text = text.replace("Ά", "Α"); text = text.replace("Έ", "Ε"); text = text.replace("Ή", "Η"); text = text.replace("Ί", "Ι"); text = text.replace("Ϊ", "Ι"); text = text.replace("Ό", "Ο"); text = text.replace("Ύ", "Υ"); text = text.replace("Ϋ", "Υ"); text = text.replace("Ώ", "Ω"); //Αντικατάσταση αποστρόφων if (removeApostrophes) { text = text.replace("'", ""); text = text.replace("`", ""); text = text.replace("΄", ""); } return text; } } /** * Concatenation των στοιχείων μιας λίστας από strings σε ένα string. Τα * στοιχεία διαχωρίζονται με το δοθέν διαχωριστικό. */ public static String concatListToString(List<String> list, String separator) { if (list == null || list.isEmpty()) { return null; } String output = ""; for (String element : list) { output += element + separator; } output = output.substring(0, output.length() - separator.length()); return output; } /** * Παραγωγή λίστας με τιμές Long από ένα string αριθμών διαχωρισμένων με * κόμμα. */ public static List<Long> createListOfLongFromCommaSeparatedString(String input) { //Η λίστα που θα επιστραφεί List<Long> list = new ArrayList<Long>(); if (input == null || input.isEmpty()) { return list; } input = input.replaceAll(" ", ""); //Διαχωρισμός του string String[] splitResults = input.split(","); try { for (String splitResult : splitResults) { //Μετατροπή του υποstring σε long και προσθήκη στη λίστα Long value = Long.valueOf(splitResult); list.add(value); } } catch (NumberFormatException e) { System.err.println(e.getMessage()); logger.error(e.getMessage()); } return list; } /** * Έλεγχος αν δύο strings είναι όμοια. Λαμβάνονται υπόψη και οι null τιμές. Αν * είναι και τα δύο null, τότε θεωρούνται όμοια. Επίσης λαμβάνονται υπόψη τα * κενά strings και οι boolean τιμές false. */ public static Boolean stringsAreEqual(String s1, String s2) { if (s1 != null && (s1.isEmpty() || s1.equals("false"))) { s1 = null; } if (s2 != null && (s2.isEmpty() || s2.equals("false"))) { s2 = null; } if (s1 == null && s2 == null) { return true; } else if (s1 == null && s2 != null) { return false; } else if (s1 != null && s2 == null) { return false; } else { return s1.equals(s2); } } /** * Έλεγχος αν δύο strings είναι όμοια ή το πρώτο περιέχει το δεύτερο. * Λαμβάνονται υπόψη και οι null τιμές. Αν είναι και τα δύο null, τότε * θεωρούνται όμοια. Επίσης λαμβάνονται υπόψη τα κενά strings και οι boolean * τιμές false. */ public static Boolean equalsOrContains(String s1, String s2) { if (s1 != null && (s1.isEmpty() || s1.equals("false"))) { s1 = null; } if (s2 != null && (s2.isEmpty() || s2.equals("false"))) { s2 = null; } if (s1 == null && s2 == null) { return true; } else if (s1 == null && s2 != null) { return false; } else if (s1 != null && s2 == null) { return false; } else if (s1.equals(s2)) { return true; } else { return s1.equals(s2) || s1.contains(s2); } } /** * Έλεγχος αν ένα string είναι null ή κενό */ public static Boolean stringIsBlank(String s) { return s == null || s.isEmpty(); } /** * Έλεγχος εάν ένα string είναι null ή κενό (trimmed) Πρόκειται για τη * StringUtils.isEmpty() συν τον έλεγχο του trim() * * @param s * @return */ public static Boolean isEmpty(String s) { return s == null || s.length() == 0 || s.trim().length() == 0; } /** * */ public static String nl2space(String text) { return text != null ? text.replace("\r\n", " ").replace("\n", " ").replace("\r", " ") : null; } public static String getPersonFullName(String firstName, String lastName, boolean startWithLastName) { String fullName = ""; if (startWithLastName) { fullName = (StringUtils.isEmpty(lastName) ? "" : lastName) + (StringUtils.isEmpty(firstName) ? "" : " " + firstName); } else { fullName = (StringUtils.isEmpty(firstName) ? "" : firstName) + (StringUtils.isEmpty(lastName) ? "" : " " + lastName); } fullName = StringUtils.trim(fullName); return fullName; } public static String truncate(String value, int length) { if (value != null && value.length() > length) { return value.substring(0, length - 5) + "..."; } else { return value; } } /** * Κανονικοποίηση (μετατροπή) αλφαριθμητικού πεδίου τύπου ΤΚ Αφαίρεση κάποιων * χαρακτήρων [" ", "-", "/"] * * @param text * @return */ public static String normalizeTk(String text) { if (text == null) { return null; } else { text = text.replace(" ", ""); text = text.replace("-", ""); text = text.replace("/", ""); return text; } } /** * Αν το δεδομένο string είναι null ή κενό, τότε επιστρέφεται br tag. Αλλιώς, * το string επιστρέφεται όπως είναι. */ public static String normalizeGridString(String s, boolean forExcel, boolean first) { if (s == null || isEmpty(s)) { return forExcel || first ? "" : "<br/>"; } else { return s; } } /** * Αν το δεδομένο string είναι null, επιστροφή ενός κενού string, αλλιώς * επιστροφή του εαυτού του */ public static String nullToEmpty(String s) { return (s == null) ? "" : s; } /** * Μετατροπή των ελληνικών χαρακτήρων του δοθέντος αλφαριθμητικού σε μοτίβο * regex. Η μέθοδος φροντίζει μόνο για τους ελληνικούς χαρακτήρες μαζί με τα * σύμβολα _ και %. * * @param text - Το αλφαριθμητικό προς μετατροπή * @return Το αλφαριθμητικό με τους ελληνικούς χαρακτήρες σε μοτίβο regex */ public static String changeGreekCharactersToRegex(String text) { String regex = ""; if (text == null) { return null; } else { //Μετατροπή του δοθέντος αλφαριθμητικού ώστε να ελεγχθούν λιγότεροι χαρακτήρες String textUpperCase = toUpperCaseGreekSupportExtended(text); textUpperCase = changeLatinCharactersToRegex(textUpperCase); for (int i = 0, textUpperCaseSize = textUpperCase.length(); i < textUpperCaseSize; i++) { char character = textUpperCase.charAt(i); switch (character) { case 'Α': regex = regex.concat("[άαΆΑ]"); break; case 'Β': regex = regex.concat("[βΒ]"); break; case 'Γ': regex = regex.concat("[γΓ]"); break; case 'Δ': regex = regex.concat("[δΔ]"); break; case 'Ε': regex = regex.concat("[έεΈΕ]"); break; case 'Ζ': regex = regex.concat("[ζΖ]"); break; case 'Η': regex = regex.concat("[ήηΉΗ]"); break; case 'Θ': regex = regex.concat("[θΘ]"); break; case 'Ι': regex = regex.concat("[ϊίΐιΊΪΙ]"); break; case 'Κ': regex = regex.concat("[κΚ]"); break; case 'Λ': regex = regex.concat("[λΛ]"); break; case 'Μ': regex = regex.concat("[μΜ]"); break; case 'Ν': regex = regex.concat("[νΝ]"); break; case 'Ξ': regex = regex.concat("[ξΞ]"); break; case 'Ο': regex = regex.concat("[όοΌΟ]"); break; case 'Π': regex = regex.concat("[πΠ]"); break; case 'Ρ': regex = regex.concat("[ρΡ]"); break; case 'Σ': regex = regex.concat("[ςσΣ]"); break; case 'Τ': regex = regex.concat("[τΤ]"); break; case 'Υ': regex = regex.concat("[ύϋΰυΎΫΥ]"); break; case 'Φ': regex = regex.concat("[φΦ]"); break; case 'Χ': regex = regex.concat("[χΧ]"); break; case 'Ψ': regex = regex.concat("[ψΨ]"); break; case 'Ω': regex = regex.concat("[ώωΏΩ]"); break; case '_': regex = regex.concat("."); break; case '%': regex = regex.concat(".*"); break; default: regex = regex.concat(String.valueOf(character)); //TODO: add support for English ; } } } return regex; } public static String changeLatinCharactersToRegex(String text) { String regex = ""; if (text == null) { return null; } else { for (int i = 0, textSize = text.length(); i < textSize; i++) { char character = text.charAt(i); switch (character) { case 'A': regex = regex.concat("[Aa]"); break; case 'B': regex = regex.concat("[Bb]"); break; case 'C': regex = regex.concat("[Cc]"); break; case 'D': regex = regex.concat("[Dd]"); break; case 'E': regex = regex.concat("[Ee]"); break; case 'F': regex = regex.concat("[Ff]"); break; case 'G': regex = regex.concat("[Gg]"); break; case 'H': regex = regex.concat("[Hh]"); break; case 'I': regex = regex.concat("[Ii]"); break; case 'J': regex = regex.concat("[Jj]"); break; case 'K': regex = regex.concat("[Kk]"); break; case 'L': regex = regex.concat("[Ll]"); break; case 'M': regex = regex.concat("[Mm]"); break; case 'N': regex = regex.concat("[Nn]"); break; case 'O': regex = regex.concat("[Oo]"); break; case 'P': regex = regex.concat("[Pp]"); break; case 'Q': regex = regex.concat("[Qq]"); break; case 'R': regex = regex.concat("[Rr]"); break; case 'S': regex = regex.concat("[Ss]"); break; case 'T': regex = regex.concat("[Tt]"); break; case 'U': regex = regex.concat("[Uu]"); break; case 'V': regex = regex.concat("[Vv]"); break; case 'W': regex = regex.concat("[Ww]"); break; case 'X': regex = regex.concat("[Xx]"); break; case 'Y': regex = regex.concat("[Yy]"); break; case 'Z': regex = regex.concat("[Zz]"); break; default: regex = regex.concat(String.valueOf(character)); //TODO: add support for English ; } } } return regex; } public static String generateID(){ return UUID.randomUUID().toString(); } }
gkalathas/Angular-Spring-boot
trainingapi/src/main/java/com/ots/trainingapi/global/utils/TextUtils.java
4,544
/** * Μετατροπή του δοθέντος αλφαριθμητικού σε κεφαλαία. Η μέθοδος φροντίζει για * την αφαίρεση των τόνων από τα ελληνικά φωνήεντα. * * @param text - Το αλφαριθμητικό προς μετατροπή * @return Το αλφαριθμητικό με κεφαλαία γράμματα και χωρίς τόνους */
block_comment
el
package com.ots.trainingapi.global.utils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class TextUtils { private static final Logger logger = LogManager.getLogger(TextUtils.class); /** * Μετατροπή του δοθέντος<SUF>*/ public static String toUpperCaseGreekSupport(String text) { if (text == null) { return null; } else { text = text.toUpperCase(); text = text.replace("Ά", "Α"); text = text.replace("Έ", "Ε"); text = text.replace("Ή", "Η"); text = text.replace("Ί", "Ι"); text = text.replace("Ό", "Ο"); text = text.replace("Ύ", "Υ"); text = text.replace("Ώ", "Ω"); return text; } } /** * Μετατροπή του δοθέντος αλφαριθμητικού σε κεφαλαία αφαιρώντας σημεία στίξης. * Η μέθοδος φροντίζει για την αφαίρεση των τόνων και των διαλυτικών από τα * ελληνικά φωνήεντα. * * @param text - Το αλφαριθμητικό προς μετατροπή * @return Το αλφαριθμητικό με κεφαλαία γράμματα και χωρίς τόνους και * διαλυτικά */ public static String toUpperCaseGreekSupportExtended(String text) { return toUpperCaseGreekSupportExtended(text, false); } public static String toUpperCaseGreekSupportExtended(String text, boolean removeApostrophes) { if (text == null) { return null; } else { text = text.replace("ΐ", "ϊ"); text = text.replace("ΰ", "ϋ"); text = text.toUpperCase(); text = text.replace("Ά", "Α"); text = text.replace("Έ", "Ε"); text = text.replace("Ή", "Η"); text = text.replace("Ί", "Ι"); text = text.replace("Ϊ", "Ι"); text = text.replace("Ό", "Ο"); text = text.replace("Ύ", "Υ"); text = text.replace("Ϋ", "Υ"); text = text.replace("Ώ", "Ω"); //Αντικατάσταση αποστρόφων if (removeApostrophes) { text = text.replace("'", ""); text = text.replace("`", ""); text = text.replace("΄", ""); } return text; } } /** * Concatenation των στοιχείων μιας λίστας από strings σε ένα string. Τα * στοιχεία διαχωρίζονται με το δοθέν διαχωριστικό. */ public static String concatListToString(List<String> list, String separator) { if (list == null || list.isEmpty()) { return null; } String output = ""; for (String element : list) { output += element + separator; } output = output.substring(0, output.length() - separator.length()); return output; } /** * Παραγωγή λίστας με τιμές Long από ένα string αριθμών διαχωρισμένων με * κόμμα. */ public static List<Long> createListOfLongFromCommaSeparatedString(String input) { //Η λίστα που θα επιστραφεί List<Long> list = new ArrayList<Long>(); if (input == null || input.isEmpty()) { return list; } input = input.replaceAll(" ", ""); //Διαχωρισμός του string String[] splitResults = input.split(","); try { for (String splitResult : splitResults) { //Μετατροπή του υποstring σε long και προσθήκη στη λίστα Long value = Long.valueOf(splitResult); list.add(value); } } catch (NumberFormatException e) { System.err.println(e.getMessage()); logger.error(e.getMessage()); } return list; } /** * Έλεγχος αν δύο strings είναι όμοια. Λαμβάνονται υπόψη και οι null τιμές. Αν * είναι και τα δύο null, τότε θεωρούνται όμοια. Επίσης λαμβάνονται υπόψη τα * κενά strings και οι boolean τιμές false. */ public static Boolean stringsAreEqual(String s1, String s2) { if (s1 != null && (s1.isEmpty() || s1.equals("false"))) { s1 = null; } if (s2 != null && (s2.isEmpty() || s2.equals("false"))) { s2 = null; } if (s1 == null && s2 == null) { return true; } else if (s1 == null && s2 != null) { return false; } else if (s1 != null && s2 == null) { return false; } else { return s1.equals(s2); } } /** * Έλεγχος αν δύο strings είναι όμοια ή το πρώτο περιέχει το δεύτερο. * Λαμβάνονται υπόψη και οι null τιμές. Αν είναι και τα δύο null, τότε * θεωρούνται όμοια. Επίσης λαμβάνονται υπόψη τα κενά strings και οι boolean * τιμές false. */ public static Boolean equalsOrContains(String s1, String s2) { if (s1 != null && (s1.isEmpty() || s1.equals("false"))) { s1 = null; } if (s2 != null && (s2.isEmpty() || s2.equals("false"))) { s2 = null; } if (s1 == null && s2 == null) { return true; } else if (s1 == null && s2 != null) { return false; } else if (s1 != null && s2 == null) { return false; } else if (s1.equals(s2)) { return true; } else { return s1.equals(s2) || s1.contains(s2); } } /** * Έλεγχος αν ένα string είναι null ή κενό */ public static Boolean stringIsBlank(String s) { return s == null || s.isEmpty(); } /** * Έλεγχος εάν ένα string είναι null ή κενό (trimmed) Πρόκειται για τη * StringUtils.isEmpty() συν τον έλεγχο του trim() * * @param s * @return */ public static Boolean isEmpty(String s) { return s == null || s.length() == 0 || s.trim().length() == 0; } /** * */ public static String nl2space(String text) { return text != null ? text.replace("\r\n", " ").replace("\n", " ").replace("\r", " ") : null; } public static String getPersonFullName(String firstName, String lastName, boolean startWithLastName) { String fullName = ""; if (startWithLastName) { fullName = (StringUtils.isEmpty(lastName) ? "" : lastName) + (StringUtils.isEmpty(firstName) ? "" : " " + firstName); } else { fullName = (StringUtils.isEmpty(firstName) ? "" : firstName) + (StringUtils.isEmpty(lastName) ? "" : " " + lastName); } fullName = StringUtils.trim(fullName); return fullName; } public static String truncate(String value, int length) { if (value != null && value.length() > length) { return value.substring(0, length - 5) + "..."; } else { return value; } } /** * Κανονικοποίηση (μετατροπή) αλφαριθμητικού πεδίου τύπου ΤΚ Αφαίρεση κάποιων * χαρακτήρων [" ", "-", "/"] * * @param text * @return */ public static String normalizeTk(String text) { if (text == null) { return null; } else { text = text.replace(" ", ""); text = text.replace("-", ""); text = text.replace("/", ""); return text; } } /** * Αν το δεδομένο string είναι null ή κενό, τότε επιστρέφεται br tag. Αλλιώς, * το string επιστρέφεται όπως είναι. */ public static String normalizeGridString(String s, boolean forExcel, boolean first) { if (s == null || isEmpty(s)) { return forExcel || first ? "" : "<br/>"; } else { return s; } } /** * Αν το δεδομένο string είναι null, επιστροφή ενός κενού string, αλλιώς * επιστροφή του εαυτού του */ public static String nullToEmpty(String s) { return (s == null) ? "" : s; } /** * Μετατροπή των ελληνικών χαρακτήρων του δοθέντος αλφαριθμητικού σε μοτίβο * regex. Η μέθοδος φροντίζει μόνο για τους ελληνικούς χαρακτήρες μαζί με τα * σύμβολα _ και %. * * @param text - Το αλφαριθμητικό προς μετατροπή * @return Το αλφαριθμητικό με τους ελληνικούς χαρακτήρες σε μοτίβο regex */ public static String changeGreekCharactersToRegex(String text) { String regex = ""; if (text == null) { return null; } else { //Μετατροπή του δοθέντος αλφαριθμητικού ώστε να ελεγχθούν λιγότεροι χαρακτήρες String textUpperCase = toUpperCaseGreekSupportExtended(text); textUpperCase = changeLatinCharactersToRegex(textUpperCase); for (int i = 0, textUpperCaseSize = textUpperCase.length(); i < textUpperCaseSize; i++) { char character = textUpperCase.charAt(i); switch (character) { case 'Α': regex = regex.concat("[άαΆΑ]"); break; case 'Β': regex = regex.concat("[βΒ]"); break; case 'Γ': regex = regex.concat("[γΓ]"); break; case 'Δ': regex = regex.concat("[δΔ]"); break; case 'Ε': regex = regex.concat("[έεΈΕ]"); break; case 'Ζ': regex = regex.concat("[ζΖ]"); break; case 'Η': regex = regex.concat("[ήηΉΗ]"); break; case 'Θ': regex = regex.concat("[θΘ]"); break; case 'Ι': regex = regex.concat("[ϊίΐιΊΪΙ]"); break; case 'Κ': regex = regex.concat("[κΚ]"); break; case 'Λ': regex = regex.concat("[λΛ]"); break; case 'Μ': regex = regex.concat("[μΜ]"); break; case 'Ν': regex = regex.concat("[νΝ]"); break; case 'Ξ': regex = regex.concat("[ξΞ]"); break; case 'Ο': regex = regex.concat("[όοΌΟ]"); break; case 'Π': regex = regex.concat("[πΠ]"); break; case 'Ρ': regex = regex.concat("[ρΡ]"); break; case 'Σ': regex = regex.concat("[ςσΣ]"); break; case 'Τ': regex = regex.concat("[τΤ]"); break; case 'Υ': regex = regex.concat("[ύϋΰυΎΫΥ]"); break; case 'Φ': regex = regex.concat("[φΦ]"); break; case 'Χ': regex = regex.concat("[χΧ]"); break; case 'Ψ': regex = regex.concat("[ψΨ]"); break; case 'Ω': regex = regex.concat("[ώωΏΩ]"); break; case '_': regex = regex.concat("."); break; case '%': regex = regex.concat(".*"); break; default: regex = regex.concat(String.valueOf(character)); //TODO: add support for English ; } } } return regex; } public static String changeLatinCharactersToRegex(String text) { String regex = ""; if (text == null) { return null; } else { for (int i = 0, textSize = text.length(); i < textSize; i++) { char character = text.charAt(i); switch (character) { case 'A': regex = regex.concat("[Aa]"); break; case 'B': regex = regex.concat("[Bb]"); break; case 'C': regex = regex.concat("[Cc]"); break; case 'D': regex = regex.concat("[Dd]"); break; case 'E': regex = regex.concat("[Ee]"); break; case 'F': regex = regex.concat("[Ff]"); break; case 'G': regex = regex.concat("[Gg]"); break; case 'H': regex = regex.concat("[Hh]"); break; case 'I': regex = regex.concat("[Ii]"); break; case 'J': regex = regex.concat("[Jj]"); break; case 'K': regex = regex.concat("[Kk]"); break; case 'L': regex = regex.concat("[Ll]"); break; case 'M': regex = regex.concat("[Mm]"); break; case 'N': regex = regex.concat("[Nn]"); break; case 'O': regex = regex.concat("[Oo]"); break; case 'P': regex = regex.concat("[Pp]"); break; case 'Q': regex = regex.concat("[Qq]"); break; case 'R': regex = regex.concat("[Rr]"); break; case 'S': regex = regex.concat("[Ss]"); break; case 'T': regex = regex.concat("[Tt]"); break; case 'U': regex = regex.concat("[Uu]"); break; case 'V': regex = regex.concat("[Vv]"); break; case 'W': regex = regex.concat("[Ww]"); break; case 'X': regex = regex.concat("[Xx]"); break; case 'Y': regex = regex.concat("[Yy]"); break; case 'Z': regex = regex.concat("[Zz]"); break; default: regex = regex.concat(String.valueOf(character)); //TODO: add support for English ; } } } return regex; } public static String generateID(){ return UUID.randomUUID().toString(); } }
13072_0
package gr.grnet.dep.service.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import gr.grnet.dep.service.model.file.PositionNominationFile; import gr.grnet.dep.service.util.SimpleDateDeserializer; import gr.grnet.dep.service.util.SimpleDateSerializer; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import java.util.Date; import java.util.HashSet; import java.util.Set; @Entity @XmlRootElement public class PositionNomination { public static interface PositionNominationView { } public static interface DetailedPositionNominationView extends PositionNominationView { } @Id @GeneratedValue private Long id; @Version private int version; @ManyToOne private Position position; @Temporal(TemporalType.DATE) private Date nominationCommitteeConvergenceDate; // Ημερομηνία σύγκλισης επιτροπής για επιλογή private String nominationFEK; //ΦΕΚ Διορισμού @ManyToOne private Candidacy nominatedCandidacy; @ManyToOne private Candidacy secondNominatedCandidacy; @OneToMany(mappedBy = "nomination", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) private Set<PositionPhase> phases = new HashSet<PositionPhase>(); @OneToMany(mappedBy = "nomination", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) private Set<PositionNominationFile> files = new HashSet<PositionNominationFile>(); @Temporal(TemporalType.DATE) private Date createdAt; @Temporal(TemporalType.DATE) private Date updatedAt; public Long getId() { return id; } public void setId(Long id) { this.id = id; } @JsonSerialize(using = SimpleDateSerializer.class) public Date getNominationCommitteeConvergenceDate() { return nominationCommitteeConvergenceDate; } @JsonDeserialize(using = SimpleDateDeserializer.class) public void setNominationCommitteeConvergenceDate(Date nominationCommitteeConvergenceDate) { this.nominationCommitteeConvergenceDate = nominationCommitteeConvergenceDate; } public String getNominationFEK() { return nominationFEK; } public void setNominationFEK(String nominationFEK) { this.nominationFEK = nominationFEK; } @JsonView({DetailedPositionNominationView.class}) public Position getPosition() { return position; } public void setPosition(Position position) { this.position = position; } public Candidacy getNominatedCandidacy() { return nominatedCandidacy; } public void setNominatedCandidacy(Candidacy nominatedCandidacy) { this.nominatedCandidacy = nominatedCandidacy; } public Candidacy getSecondNominatedCandidacy() { return secondNominatedCandidacy; } public void setSecondNominatedCandidacy(Candidacy secondNominatedCandidacy) { this.secondNominatedCandidacy = secondNominatedCandidacy; } @XmlTransient @JsonIgnore public Set<PositionPhase> getPhases() { return phases; } public void setPhases(Set<PositionPhase> phases) { this.phases = phases; } @XmlTransient @JsonIgnore public Set<PositionNominationFile> getFiles() { return files; } public void setFiles(Set<PositionNominationFile> files) { this.files = files; } @JsonSerialize(using = SimpleDateSerializer.class) public Date getCreatedAt() { return createdAt; } @JsonDeserialize(using = SimpleDateDeserializer.class) public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } @JsonSerialize(using = SimpleDateSerializer.class) public Date getUpdatedAt() { return updatedAt; } @JsonDeserialize(using = SimpleDateDeserializer.class) public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } ////////////////////////////////////////////// public void addFile(PositionNominationFile file) { file.setNomination(this); this.files.add(file); } public void copyFrom(PositionNomination nomination) { this.setNominationCommitteeConvergenceDate(nomination.getNominationCommitteeConvergenceDate()); this.setNominationFEK(nomination.getNominationFEK()); this.setUpdatedAt(new Date()); } }
grnet/apella
dep-ejb/src/main/java/gr/grnet/dep/service/model/PositionNomination.java
1,277
// Ημερομηνία σύγκλισης επιτροπής για επιλογή
line_comment
el
package gr.grnet.dep.service.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import gr.grnet.dep.service.model.file.PositionNominationFile; import gr.grnet.dep.service.util.SimpleDateDeserializer; import gr.grnet.dep.service.util.SimpleDateSerializer; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import java.util.Date; import java.util.HashSet; import java.util.Set; @Entity @XmlRootElement public class PositionNomination { public static interface PositionNominationView { } public static interface DetailedPositionNominationView extends PositionNominationView { } @Id @GeneratedValue private Long id; @Version private int version; @ManyToOne private Position position; @Temporal(TemporalType.DATE) private Date nominationCommitteeConvergenceDate; // Ημερομηνία σύγκλισης<SUF> private String nominationFEK; //ΦΕΚ Διορισμού @ManyToOne private Candidacy nominatedCandidacy; @ManyToOne private Candidacy secondNominatedCandidacy; @OneToMany(mappedBy = "nomination", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) private Set<PositionPhase> phases = new HashSet<PositionPhase>(); @OneToMany(mappedBy = "nomination", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) private Set<PositionNominationFile> files = new HashSet<PositionNominationFile>(); @Temporal(TemporalType.DATE) private Date createdAt; @Temporal(TemporalType.DATE) private Date updatedAt; public Long getId() { return id; } public void setId(Long id) { this.id = id; } @JsonSerialize(using = SimpleDateSerializer.class) public Date getNominationCommitteeConvergenceDate() { return nominationCommitteeConvergenceDate; } @JsonDeserialize(using = SimpleDateDeserializer.class) public void setNominationCommitteeConvergenceDate(Date nominationCommitteeConvergenceDate) { this.nominationCommitteeConvergenceDate = nominationCommitteeConvergenceDate; } public String getNominationFEK() { return nominationFEK; } public void setNominationFEK(String nominationFEK) { this.nominationFEK = nominationFEK; } @JsonView({DetailedPositionNominationView.class}) public Position getPosition() { return position; } public void setPosition(Position position) { this.position = position; } public Candidacy getNominatedCandidacy() { return nominatedCandidacy; } public void setNominatedCandidacy(Candidacy nominatedCandidacy) { this.nominatedCandidacy = nominatedCandidacy; } public Candidacy getSecondNominatedCandidacy() { return secondNominatedCandidacy; } public void setSecondNominatedCandidacy(Candidacy secondNominatedCandidacy) { this.secondNominatedCandidacy = secondNominatedCandidacy; } @XmlTransient @JsonIgnore public Set<PositionPhase> getPhases() { return phases; } public void setPhases(Set<PositionPhase> phases) { this.phases = phases; } @XmlTransient @JsonIgnore public Set<PositionNominationFile> getFiles() { return files; } public void setFiles(Set<PositionNominationFile> files) { this.files = files; } @JsonSerialize(using = SimpleDateSerializer.class) public Date getCreatedAt() { return createdAt; } @JsonDeserialize(using = SimpleDateDeserializer.class) public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } @JsonSerialize(using = SimpleDateSerializer.class) public Date getUpdatedAt() { return updatedAt; } @JsonDeserialize(using = SimpleDateDeserializer.class) public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } ////////////////////////////////////////////// public void addFile(PositionNominationFile file) { file.setNomination(this); this.files.add(file); } public void copyFrom(PositionNomination nomination) { this.setNominationCommitteeConvergenceDate(nomination.getNominationCommitteeConvergenceDate()); this.setNominationFEK(nomination.getNominationFEK()); this.setUpdatedAt(new Date()); } }
600_6
import com.mysql.jdbc.Connection; import com.mysql.jdbc.ResultSet; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; /** * Created by George on 17/10/2016. */ public class RUSSIA2 { public static void main(String[] args) throws SQLException { Connection conn = null; Document doc = null; Document doc1 = null; Document doc2 = null; Document doc3 = null; try { doc = Jsoup.connect("http://www.forebet.com/en/football-tips-and-predictions-for-russia-premier-league/1-division").get(); } catch (IOException e) { e.printStackTrace(); } try { String userName = "root"; String password = "root"; String url = "jdbc:mysql://localhost:3306/bet?characterEncoding=utf8"; Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = (Connection) DriverManager.getConnection(url, userName, password); System.out.println("Database connection established"); } catch (Exception e) { System.err.println("Cannot connect to database server"); } Element table = doc.select("table.schema").first(); //Επιλέγουμε το σωστό table απο το website for (Element row : table.select("tr:gt(2)")) { // η for εξασφαλιζει οτι με τις αντιστοιχες επαναλήψεις θα περαστούν ολα τα στοιχεία του πινακα στη βαση μας Elements td = row.select("td > a"); if(td.eq(0).hasText()){ Elements td2 = row.select("td"); Elements td3 = row.select("td.tnms > span"); Elements td4 = row.select("td.predict_y"); Elements td6 = row.select("td.exact_yes.tabonly.scrpred"); Elements td8 = row.select("td.lResTd > span.ht_scr"); Elements td9 = row.select("td.lResTd"); Statement s = conn.createStatement(); PreparedStatement preparedStmt = conn.prepareStatement("insert into Leagues.Russia2 (Teams, Date, Prob1, ProbX, Prob2, Pick, SuccessPick, CorrectScorePick, SuccessCorrectScorePick, AvgGoals, Kelly, ProbUnder, ProbOver, PickGoal, SuccessPickGoal, HalfProb1, HalfProbX, HalfProb2, PickHT, PickFT, SuccessPickHT, SuccessPickFT, NGprob, GGprob, BTSpick, SuccessBTSpick, BTSodds, HT_FINAL_SCORE, FT_HT_FINAL_SCORE) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + " " + " ON DUPLICATE KEY UPDATE " + "Teams = VALUES(Teams)," + "Date = VALUES(Date)," + "Prob1 = VALUES(Prob1)," + "ProbX = VALUES(ProbX)," + "Prob2 = VALUES(Prob2)," + "Pick = VALUES(Pick)," + "SuccessPick = VALUES(SuccessPick)," + "CorrectScorePick = VALUES(CorrectScorePick)," + "SuccessCorrectScorePick = VALUES(SuccessCorrectScorePick)," + "AvgGoals = VALUES(AvgGoals)," + "Kelly = VALUES(Kelly)," + "ProbUnder = VALUES(ProbUnder)," + "ProbOver = VALUES(ProbOver)," + "PickGoal = VALUES(PickGoal)," + "SuccessPickGoal = VALUES(SuccessPickGoal)," + "HalfProb1 = VALUES(HalfProb1)," + "HalfProbX = VALUES(HalfProbX)," + "HalfProb2 = VALUES(HalfProb2)," + "PickHT = VALUES(PickHT)," + "PickFT = VALUES(PickFT)," + "SuccessPickHT = VALUES(SuccessPickHT)," + "SuccessPickFT = VALUES(SuccessPickFT)," + "NGprob = VALUES(NGprob)," + "GGprob = VALUES(GGprob)," + "BTSpick = VALUES(BTSpick)," + "SuccessBTSpick = VALUES(SuccessBTSpick)," + "BTSodds = VALUES(BTSodds)," + "HT_FINAL_SCORE = VALUES(HT_FINAL_SCORE)," + "FT_HT_FINAL_SCORE = VALUES(FT_HT_FINAL_SCORE)," + "id = LAST_INSERT_ID(id)" ); preparedStmt.setString(1, td.eq(0).text()); preparedStmt.setString(2, td3.eq(0).text()); preparedStmt.setString(3, td2.eq(1).text()); preparedStmt.setString(4, td2.eq(2).text()); preparedStmt.setString(5, td2.eq(3).text()); preparedStmt.setString(6, td2.eq(4).text()); preparedStmt.setString(7, td4.eq(0).text()); preparedStmt.setString(8, td2.eq(5).text()); preparedStmt.setString(9, td6.eq(0).text()); preparedStmt.setString(10, td2.eq(6).text()); preparedStmt.setString(11, td2.eq(9).text()); preparedStmt.setString(12, ""); preparedStmt.setString(13, ""); preparedStmt.setString(14, ""); preparedStmt.setString(15, ""); preparedStmt.setString(16, ""); preparedStmt.setString(17, ""); preparedStmt.setString(18, ""); preparedStmt.setString(19, ""); preparedStmt.setString(20, ""); preparedStmt.setString(21, ""); preparedStmt.setString(22, ""); preparedStmt.setString(23, ""); preparedStmt.setString(24, ""); preparedStmt.setString(25, ""); preparedStmt.setString(26, ""); preparedStmt.setString(27, ""); preparedStmt.setString(28, td8.eq(0).text()); preparedStmt.setString(29, td9.eq(0).text()); int euReturnValue = preparedStmt.executeUpdate(); System.out.println(String.format("executeUpdate returned %d", euReturnValue)); ResultSet rs = (ResultSet) s.executeQuery("SELECT LAST_INSERT_ID() AS n"); rs.next(); rs.getInt(1); s.close(); } } try { doc1 = Jsoup.connect("http://www.forebet.com/en/football-tips-and-predictions-for-russia-premier-league/1-division/under-over").get(); } catch (IOException e) { e.printStackTrace(); } Element table1 = doc1.select("table.schema").first(); //Επιλέγουμε το σωστό table απο το website for (Element row : table1.select("tr:gt(1)")) { // η for εξασφαλιζει οτι με τις αντιστοιχες επαναλήψεις θα περαστούν ολα τα στοιχεία του πινακα στη βαση μας Elements td = row.select("td > a"); if (td.eq(0).hasText()) { Elements td2 = row.select("td"); Elements td4 = row.select("td.predict_y"); Statement p = conn.createStatement(); PreparedStatement preparedStmt1 = conn.prepareStatement("update Leagues.Russia2 set ProbUnder = ?, ProbOver = ?, PickGoal = ? , SuccessPickGoal = ? where Teams = ?"); preparedStmt1.setString(1, td2.eq(1).text()); preparedStmt1.setString(2, td2.eq(2).text()); preparedStmt1.setString(3, td2.eq(3).text()); preparedStmt1.setString(4, td4.eq(0).text()); preparedStmt1.setString(5, td.eq(0).text()); int euReturnValue = preparedStmt1.executeUpdate(); System.out.println(String.format("executeUpdate returned %d", euReturnValue)); ResultSet rs = (ResultSet) p.executeQuery("SELECT LAST_INSERT_ID() AS n"); rs.next(); rs.getInt(1); p.close(); } } try { doc2 = Jsoup.connect("http://www.forebet.com/en/football-tips-and-predictions-for-russia-premier-league/1-division/halftime-fulltime").get(); } catch (IOException e) { e.printStackTrace(); } Element table2 = doc2.select("table.schema").first(); //Επιλέγουμε το σωστό table απο το website for (Element row : table2.select("tr:gt(1)")) { // η for εξασφαλιζει οτι με τις αντιστοιχες επαναλήψεις θα περαστούν ολα τα στοιχεία του πινακα στη βαση μας Elements td = row.select("td > a"); if(td.eq(0).hasText()){ Elements td2 = row.select("td"); Elements td4 = row.select("td.predict_y"); Statement d = conn.createStatement(); PreparedStatement preparedStmt2 = conn.prepareStatement("update Leagues.Russia2 set HalfProb1 = ?, HalfProbX = ?, HalfProb2 = ?, PickHT = ?, PickFT = ?, SuccessPickHT = ?, SuccessPickFT = ? where Teams = ?"); preparedStmt2.setString(1, td2.eq(1).text()); preparedStmt2.setString(2, td2.eq(2).text()); preparedStmt2.setString(3, td2.eq(3).text()); preparedStmt2.setString(4, td2.eq(4).text()); preparedStmt2.setString(5, td2.eq(5).text()); preparedStmt2.setString(6, td4.eq(0).text()); preparedStmt2.setString(7, td4.eq(1).text()); preparedStmt2.setString(8, td.eq(0).text()); int euReturnValue = preparedStmt2.executeUpdate(); System.out.println(String.format("executeUpdate returned %d", euReturnValue)); ResultSet rs = (ResultSet) d.executeQuery("SELECT LAST_INSERT_ID() AS n"); rs.next(); rs.getInt(1); d.close(); } } try { doc3 = Jsoup.connect("http://www.forebet.com/en/football-tips-and-predictions-for-russia-premier-league/1-division/bothtoscore").get(); } catch (IOException e) { e.printStackTrace(); } Element table3 = doc3.select("table.schema").first(); //Επιλέγουμε το σωστό table απο το website for (Element row : table3.select("tr:gt(1)")) { // η for εξασφαλιζει οτι με τις αντιστοιχες επαναλήψεις θα περαστούν ολα τα στοιχεία του πινακα στη βαση μας Elements td = row.select("td > a"); if(td.eq(0).hasText()){ Elements td2 = row.select("td"); Elements td4 = row.select("td.predict_y"); Statement a = conn.createStatement(); PreparedStatement preparedStmt3 = conn.prepareStatement("update Leagues.Russia2 set NGprob = ?, GGprob = ?, BTSpick = ?, SuccessBTSpick = ?, BTSodds = ? where Teams = ?"); preparedStmt3.setString(1, td2.eq(1).text()); preparedStmt3.setString(2, td2.eq(2).text()); preparedStmt3.setString(3, td2.eq(3).text()); preparedStmt3.setString(4, td4.eq(0).text()); preparedStmt3.setString(5, td2.eq(4).text()); preparedStmt3.setString(6, td.eq(0).text()); int euReturnValue = preparedStmt3.executeUpdate(); System.out.println(String.format("executeUpdate returned %d", euReturnValue)); ResultSet rs = (ResultSet) a.executeQuery("SELECT LAST_INSERT_ID() AS n"); rs.next(); rs.getInt(1); a.close(); } } } }
grokkos/bet-strategy
src/RUSSIA2.java
3,196
// η for εξασφαλιζει οτι με τις αντιστοιχες επαναλήψεις θα περαστούν ολα τα στοιχεία του πινακα στη βαση μας
line_comment
el
import com.mysql.jdbc.Connection; import com.mysql.jdbc.ResultSet; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; /** * Created by George on 17/10/2016. */ public class RUSSIA2 { public static void main(String[] args) throws SQLException { Connection conn = null; Document doc = null; Document doc1 = null; Document doc2 = null; Document doc3 = null; try { doc = Jsoup.connect("http://www.forebet.com/en/football-tips-and-predictions-for-russia-premier-league/1-division").get(); } catch (IOException e) { e.printStackTrace(); } try { String userName = "root"; String password = "root"; String url = "jdbc:mysql://localhost:3306/bet?characterEncoding=utf8"; Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = (Connection) DriverManager.getConnection(url, userName, password); System.out.println("Database connection established"); } catch (Exception e) { System.err.println("Cannot connect to database server"); } Element table = doc.select("table.schema").first(); //Επιλέγουμε το σωστό table απο το website for (Element row : table.select("tr:gt(2)")) { // η for εξασφαλιζει οτι με τις αντιστοιχες επαναλήψεις θα περαστούν ολα τα στοιχεία του πινακα στη βαση μας Elements td = row.select("td > a"); if(td.eq(0).hasText()){ Elements td2 = row.select("td"); Elements td3 = row.select("td.tnms > span"); Elements td4 = row.select("td.predict_y"); Elements td6 = row.select("td.exact_yes.tabonly.scrpred"); Elements td8 = row.select("td.lResTd > span.ht_scr"); Elements td9 = row.select("td.lResTd"); Statement s = conn.createStatement(); PreparedStatement preparedStmt = conn.prepareStatement("insert into Leagues.Russia2 (Teams, Date, Prob1, ProbX, Prob2, Pick, SuccessPick, CorrectScorePick, SuccessCorrectScorePick, AvgGoals, Kelly, ProbUnder, ProbOver, PickGoal, SuccessPickGoal, HalfProb1, HalfProbX, HalfProb2, PickHT, PickFT, SuccessPickHT, SuccessPickFT, NGprob, GGprob, BTSpick, SuccessBTSpick, BTSodds, HT_FINAL_SCORE, FT_HT_FINAL_SCORE) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + " " + " ON DUPLICATE KEY UPDATE " + "Teams = VALUES(Teams)," + "Date = VALUES(Date)," + "Prob1 = VALUES(Prob1)," + "ProbX = VALUES(ProbX)," + "Prob2 = VALUES(Prob2)," + "Pick = VALUES(Pick)," + "SuccessPick = VALUES(SuccessPick)," + "CorrectScorePick = VALUES(CorrectScorePick)," + "SuccessCorrectScorePick = VALUES(SuccessCorrectScorePick)," + "AvgGoals = VALUES(AvgGoals)," + "Kelly = VALUES(Kelly)," + "ProbUnder = VALUES(ProbUnder)," + "ProbOver = VALUES(ProbOver)," + "PickGoal = VALUES(PickGoal)," + "SuccessPickGoal = VALUES(SuccessPickGoal)," + "HalfProb1 = VALUES(HalfProb1)," + "HalfProbX = VALUES(HalfProbX)," + "HalfProb2 = VALUES(HalfProb2)," + "PickHT = VALUES(PickHT)," + "PickFT = VALUES(PickFT)," + "SuccessPickHT = VALUES(SuccessPickHT)," + "SuccessPickFT = VALUES(SuccessPickFT)," + "NGprob = VALUES(NGprob)," + "GGprob = VALUES(GGprob)," + "BTSpick = VALUES(BTSpick)," + "SuccessBTSpick = VALUES(SuccessBTSpick)," + "BTSodds = VALUES(BTSodds)," + "HT_FINAL_SCORE = VALUES(HT_FINAL_SCORE)," + "FT_HT_FINAL_SCORE = VALUES(FT_HT_FINAL_SCORE)," + "id = LAST_INSERT_ID(id)" ); preparedStmt.setString(1, td.eq(0).text()); preparedStmt.setString(2, td3.eq(0).text()); preparedStmt.setString(3, td2.eq(1).text()); preparedStmt.setString(4, td2.eq(2).text()); preparedStmt.setString(5, td2.eq(3).text()); preparedStmt.setString(6, td2.eq(4).text()); preparedStmt.setString(7, td4.eq(0).text()); preparedStmt.setString(8, td2.eq(5).text()); preparedStmt.setString(9, td6.eq(0).text()); preparedStmt.setString(10, td2.eq(6).text()); preparedStmt.setString(11, td2.eq(9).text()); preparedStmt.setString(12, ""); preparedStmt.setString(13, ""); preparedStmt.setString(14, ""); preparedStmt.setString(15, ""); preparedStmt.setString(16, ""); preparedStmt.setString(17, ""); preparedStmt.setString(18, ""); preparedStmt.setString(19, ""); preparedStmt.setString(20, ""); preparedStmt.setString(21, ""); preparedStmt.setString(22, ""); preparedStmt.setString(23, ""); preparedStmt.setString(24, ""); preparedStmt.setString(25, ""); preparedStmt.setString(26, ""); preparedStmt.setString(27, ""); preparedStmt.setString(28, td8.eq(0).text()); preparedStmt.setString(29, td9.eq(0).text()); int euReturnValue = preparedStmt.executeUpdate(); System.out.println(String.format("executeUpdate returned %d", euReturnValue)); ResultSet rs = (ResultSet) s.executeQuery("SELECT LAST_INSERT_ID() AS n"); rs.next(); rs.getInt(1); s.close(); } } try { doc1 = Jsoup.connect("http://www.forebet.com/en/football-tips-and-predictions-for-russia-premier-league/1-division/under-over").get(); } catch (IOException e) { e.printStackTrace(); } Element table1 = doc1.select("table.schema").first(); //Επιλέγουμε το σωστό table απο το website for (Element row : table1.select("tr:gt(1)")) { // η for εξασφαλιζει οτι με τις αντιστοιχες επαναλήψεις θα περαστούν ολα τα στοιχεία του πινακα στη βαση μας Elements td = row.select("td > a"); if (td.eq(0).hasText()) { Elements td2 = row.select("td"); Elements td4 = row.select("td.predict_y"); Statement p = conn.createStatement(); PreparedStatement preparedStmt1 = conn.prepareStatement("update Leagues.Russia2 set ProbUnder = ?, ProbOver = ?, PickGoal = ? , SuccessPickGoal = ? where Teams = ?"); preparedStmt1.setString(1, td2.eq(1).text()); preparedStmt1.setString(2, td2.eq(2).text()); preparedStmt1.setString(3, td2.eq(3).text()); preparedStmt1.setString(4, td4.eq(0).text()); preparedStmt1.setString(5, td.eq(0).text()); int euReturnValue = preparedStmt1.executeUpdate(); System.out.println(String.format("executeUpdate returned %d", euReturnValue)); ResultSet rs = (ResultSet) p.executeQuery("SELECT LAST_INSERT_ID() AS n"); rs.next(); rs.getInt(1); p.close(); } } try { doc2 = Jsoup.connect("http://www.forebet.com/en/football-tips-and-predictions-for-russia-premier-league/1-division/halftime-fulltime").get(); } catch (IOException e) { e.printStackTrace(); } Element table2 = doc2.select("table.schema").first(); //Επιλέγουμε το σωστό table απο το website for (Element row : table2.select("tr:gt(1)")) { // η for<SUF> Elements td = row.select("td > a"); if(td.eq(0).hasText()){ Elements td2 = row.select("td"); Elements td4 = row.select("td.predict_y"); Statement d = conn.createStatement(); PreparedStatement preparedStmt2 = conn.prepareStatement("update Leagues.Russia2 set HalfProb1 = ?, HalfProbX = ?, HalfProb2 = ?, PickHT = ?, PickFT = ?, SuccessPickHT = ?, SuccessPickFT = ? where Teams = ?"); preparedStmt2.setString(1, td2.eq(1).text()); preparedStmt2.setString(2, td2.eq(2).text()); preparedStmt2.setString(3, td2.eq(3).text()); preparedStmt2.setString(4, td2.eq(4).text()); preparedStmt2.setString(5, td2.eq(5).text()); preparedStmt2.setString(6, td4.eq(0).text()); preparedStmt2.setString(7, td4.eq(1).text()); preparedStmt2.setString(8, td.eq(0).text()); int euReturnValue = preparedStmt2.executeUpdate(); System.out.println(String.format("executeUpdate returned %d", euReturnValue)); ResultSet rs = (ResultSet) d.executeQuery("SELECT LAST_INSERT_ID() AS n"); rs.next(); rs.getInt(1); d.close(); } } try { doc3 = Jsoup.connect("http://www.forebet.com/en/football-tips-and-predictions-for-russia-premier-league/1-division/bothtoscore").get(); } catch (IOException e) { e.printStackTrace(); } Element table3 = doc3.select("table.schema").first(); //Επιλέγουμε το σωστό table απο το website for (Element row : table3.select("tr:gt(1)")) { // η for εξασφαλιζει οτι με τις αντιστοιχες επαναλήψεις θα περαστούν ολα τα στοιχεία του πινακα στη βαση μας Elements td = row.select("td > a"); if(td.eq(0).hasText()){ Elements td2 = row.select("td"); Elements td4 = row.select("td.predict_y"); Statement a = conn.createStatement(); PreparedStatement preparedStmt3 = conn.prepareStatement("update Leagues.Russia2 set NGprob = ?, GGprob = ?, BTSpick = ?, SuccessBTSpick = ?, BTSodds = ? where Teams = ?"); preparedStmt3.setString(1, td2.eq(1).text()); preparedStmt3.setString(2, td2.eq(2).text()); preparedStmt3.setString(3, td2.eq(3).text()); preparedStmt3.setString(4, td4.eq(0).text()); preparedStmt3.setString(5, td2.eq(4).text()); preparedStmt3.setString(6, td.eq(0).text()); int euReturnValue = preparedStmt3.executeUpdate(); System.out.println(String.format("executeUpdate returned %d", euReturnValue)); ResultSet rs = (ResultSet) a.executeQuery("SELECT LAST_INSERT_ID() AS n"); rs.next(); rs.getInt(1); a.close(); } } } }
30750_7
package eu.smartcontroller.guard.demo.controller; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import eu.smartcontroller.guard.demo.model.algorithms.AlgorithmCNITMLResponse; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import static eu.smartcontroller.guard.demo.SpringBootKafkaAppApplication.cnitMlAlgorithmEndpoint; public class AlgorithmCNITMLHandler { private static HttpClient client = HttpClientBuilder.create().build(); public static AlgorithmCNITMLResponse executeCommand(String commandId) { AlgorithmCNITMLResponse algorithmCNITMLResponse = new AlgorithmCNITMLResponse(); String algorithmResponse =""; Boolean connectivity=false; try { // create the request URL url = new URL("http://" + cnitMlAlgorithmEndpoint + "/commands/" + commandId); HttpPost request = new HttpPost(String.valueOf(url)); request.setHeader("Content-Type", "application/json"); //System.out.println("algorithm request: " + request); HttpResponse response = client.execute(request); // get the response try(BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { String line; StringBuilder outcome= new StringBuilder(); while ((line = rd.readLine()) != null) { outcome.append(line); } algorithmResponse = outcome.toString(); //System.out.println("!!!!!!!!!!algorithmResponse (executeCommand): " + algorithmResponse); connectivity = true; } } catch (IOException e) { KafkaProducerController.logger.info(e.getMessage() + " during request to CNIT-ML algorithm instance API."); e.printStackTrace(); } // read the algorithm Response as JsonArray and construct the algorithmCNITMLResponse instance JsonParser jsonParser = new JsonParser(); //JsonArray jsonFromString; JsonObject jsonFromString; if(connectivity) { if (!jsonParser.parse(algorithmResponse).isJsonNull()) { //jsonFromString = jsonParser.parse(algorithmResponse).getAsJsonArray(); jsonFromString = jsonParser.parse(algorithmResponse).getAsJsonObject(); /* //Ο Μάνος μου το είπε αυτό αλλά για να το χρησιμοποιήσω πρέπει να φτιαχτούν σωστά οι τύποι στο AlgorithmCNITMLResponse Gson gson = new Gson(); AlgorithmCNITMLResponse algorithmCNITMLResponse2 = gson.fromJson(algorithmResponse, AlgorithmCNITMLResponse.class); */ /* //Iterating the contents of the array Iterator<JsonElement> iterator = jsonFromString.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } */ /*algorithmCNITMLResponse.setError(jsonFromString.get(0).getAsJsonObject().get("error").getAsBoolean()); algorithmCNITMLResponse.setStdout(jsonFromString.get(0).getAsJsonObject().get("stdout").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setStderr(jsonFromString.get(0).getAsJsonObject().get("stderr").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setReturncode(jsonFromString.get(0).getAsJsonObject().get("returncode").getAsInt()); algorithmCNITMLResponse.setStart(jsonFromString.get(0).getAsJsonObject().get("start").getAsString()); algorithmCNITMLResponse.setEnd(jsonFromString.get(0).getAsJsonObject().get("end").getAsString());*/ algorithmCNITMLResponse.setError(jsonFromString.getAsJsonObject().get("error").getAsBoolean()); /*algorithmCNITMLResponse.setStdout(jsonFromString.getAsJsonObject().get("stdout").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setStderr(jsonFromString.getAsJsonObject().get("stderr").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setReturncode(jsonFromString.getAsJsonObject().get("returncode").getAsInt()); algorithmCNITMLResponse.setStart(jsonFromString.getAsJsonObject().get("start").getAsString()); algorithmCNITMLResponse.setEnd(jsonFromString.getAsJsonObject().get("end").getAsString());*/ } } KafkaProducerController.logger.info("Request to CNIT-ML algorithm instance API (executeCommand). Response: " + algorithmCNITMLResponse); return algorithmCNITMLResponse; } public static AlgorithmCNITMLResponse updateParameters(String id, String value) { AlgorithmCNITMLResponse algorithmCNITMLResponse = new AlgorithmCNITMLResponse(); String algorithmResponse =""; Boolean connectivity=false; try { // create the request URL url = new URL("http://" + cnitMlAlgorithmEndpoint + "/parameters/" + id + "/" + value); HttpPost request = new HttpPost(String.valueOf(url)); request.setHeader("Content-Type", "application/json"); //System.out.println("algorithm request2: " + request); HttpResponse response = client.execute(request); // get the response try(BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { String line; StringBuilder outcome= new StringBuilder(); while ((line = rd.readLine()) != null) { outcome.append(line); } algorithmResponse = outcome.toString(); //System.out.println("!!!!!!!!!!algorithmResponse (updateParameters): " + algorithmResponse); connectivity = true; } } catch (IOException e) { KafkaProducerController.logger.info(e.getMessage() + " during request to CNIT-ML algorithm instance API."); e.printStackTrace(); } // read the Algorithm Response as JsonArray and construct the algorithmCNITMLResponse instance JsonParser jsonParser = new JsonParser(); JsonObject jsonFromString; if(connectivity) { if (!jsonParser.parse(algorithmResponse).isJsonNull()) { jsonFromString = jsonParser.parse(algorithmResponse).getAsJsonObject(); algorithmCNITMLResponse.setError(jsonFromString.getAsJsonObject().get("error").getAsBoolean()); /*algorithmCNITMLResponse.setStdout(jsonFromString.getAsJsonObject().get("stdout").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setStderr(jsonFromString.getAsJsonObject().get("stderr").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setReturncode(jsonFromString.getAsJsonObject().get("returncode").getAsInt()); algorithmCNITMLResponse.setStart(jsonFromString.getAsJsonObject().get("start").getAsString()); algorithmCNITMLResponse.setEnd(jsonFromString.getAsJsonObject().get("end").getAsString());*/ } } KafkaProducerController.logger.info("Request to CNIT-ML algorithm instance API (updateParameters). Response: " + algorithmCNITMLResponse); return algorithmCNITMLResponse; } }
guard2020/guardce
guard-platform-CE/core_framework/security_controller/spring-boot-kafka-app/src/main/java/eu/smartcontroller/guard/demo/controller/AlgorithmCNITMLHandler.java
1,666
/* //Ο Μάνος μου το είπε αυτό αλλά για να το χρησιμοποιήσω πρέπει να φτιαχτούν σωστά οι τύποι στο AlgorithmCNITMLResponse Gson gson = new Gson(); AlgorithmCNITMLResponse algorithmCNITMLResponse2 = gson.fromJson(algorithmResponse, AlgorithmCNITMLResponse.class); */
block_comment
el
package eu.smartcontroller.guard.demo.controller; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import eu.smartcontroller.guard.demo.model.algorithms.AlgorithmCNITMLResponse; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import static eu.smartcontroller.guard.demo.SpringBootKafkaAppApplication.cnitMlAlgorithmEndpoint; public class AlgorithmCNITMLHandler { private static HttpClient client = HttpClientBuilder.create().build(); public static AlgorithmCNITMLResponse executeCommand(String commandId) { AlgorithmCNITMLResponse algorithmCNITMLResponse = new AlgorithmCNITMLResponse(); String algorithmResponse =""; Boolean connectivity=false; try { // create the request URL url = new URL("http://" + cnitMlAlgorithmEndpoint + "/commands/" + commandId); HttpPost request = new HttpPost(String.valueOf(url)); request.setHeader("Content-Type", "application/json"); //System.out.println("algorithm request: " + request); HttpResponse response = client.execute(request); // get the response try(BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { String line; StringBuilder outcome= new StringBuilder(); while ((line = rd.readLine()) != null) { outcome.append(line); } algorithmResponse = outcome.toString(); //System.out.println("!!!!!!!!!!algorithmResponse (executeCommand): " + algorithmResponse); connectivity = true; } } catch (IOException e) { KafkaProducerController.logger.info(e.getMessage() + " during request to CNIT-ML algorithm instance API."); e.printStackTrace(); } // read the algorithm Response as JsonArray and construct the algorithmCNITMLResponse instance JsonParser jsonParser = new JsonParser(); //JsonArray jsonFromString; JsonObject jsonFromString; if(connectivity) { if (!jsonParser.parse(algorithmResponse).isJsonNull()) { //jsonFromString = jsonParser.parse(algorithmResponse).getAsJsonArray(); jsonFromString = jsonParser.parse(algorithmResponse).getAsJsonObject(); /* //Ο Μάνος μου<SUF>*/ /* //Iterating the contents of the array Iterator<JsonElement> iterator = jsonFromString.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } */ /*algorithmCNITMLResponse.setError(jsonFromString.get(0).getAsJsonObject().get("error").getAsBoolean()); algorithmCNITMLResponse.setStdout(jsonFromString.get(0).getAsJsonObject().get("stdout").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setStderr(jsonFromString.get(0).getAsJsonObject().get("stderr").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setReturncode(jsonFromString.get(0).getAsJsonObject().get("returncode").getAsInt()); algorithmCNITMLResponse.setStart(jsonFromString.get(0).getAsJsonObject().get("start").getAsString()); algorithmCNITMLResponse.setEnd(jsonFromString.get(0).getAsJsonObject().get("end").getAsString());*/ algorithmCNITMLResponse.setError(jsonFromString.getAsJsonObject().get("error").getAsBoolean()); /*algorithmCNITMLResponse.setStdout(jsonFromString.getAsJsonObject().get("stdout").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setStderr(jsonFromString.getAsJsonObject().get("stderr").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setReturncode(jsonFromString.getAsJsonObject().get("returncode").getAsInt()); algorithmCNITMLResponse.setStart(jsonFromString.getAsJsonObject().get("start").getAsString()); algorithmCNITMLResponse.setEnd(jsonFromString.getAsJsonObject().get("end").getAsString());*/ } } KafkaProducerController.logger.info("Request to CNIT-ML algorithm instance API (executeCommand). Response: " + algorithmCNITMLResponse); return algorithmCNITMLResponse; } public static AlgorithmCNITMLResponse updateParameters(String id, String value) { AlgorithmCNITMLResponse algorithmCNITMLResponse = new AlgorithmCNITMLResponse(); String algorithmResponse =""; Boolean connectivity=false; try { // create the request URL url = new URL("http://" + cnitMlAlgorithmEndpoint + "/parameters/" + id + "/" + value); HttpPost request = new HttpPost(String.valueOf(url)); request.setHeader("Content-Type", "application/json"); //System.out.println("algorithm request2: " + request); HttpResponse response = client.execute(request); // get the response try(BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { String line; StringBuilder outcome= new StringBuilder(); while ((line = rd.readLine()) != null) { outcome.append(line); } algorithmResponse = outcome.toString(); //System.out.println("!!!!!!!!!!algorithmResponse (updateParameters): " + algorithmResponse); connectivity = true; } } catch (IOException e) { KafkaProducerController.logger.info(e.getMessage() + " during request to CNIT-ML algorithm instance API."); e.printStackTrace(); } // read the Algorithm Response as JsonArray and construct the algorithmCNITMLResponse instance JsonParser jsonParser = new JsonParser(); JsonObject jsonFromString; if(connectivity) { if (!jsonParser.parse(algorithmResponse).isJsonNull()) { jsonFromString = jsonParser.parse(algorithmResponse).getAsJsonObject(); algorithmCNITMLResponse.setError(jsonFromString.getAsJsonObject().get("error").getAsBoolean()); /*algorithmCNITMLResponse.setStdout(jsonFromString.getAsJsonObject().get("stdout").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setStderr(jsonFromString.getAsJsonObject().get("stderr").getAsJsonArray().get(0).getAsString()); algorithmCNITMLResponse.setReturncode(jsonFromString.getAsJsonObject().get("returncode").getAsInt()); algorithmCNITMLResponse.setStart(jsonFromString.getAsJsonObject().get("start").getAsString()); algorithmCNITMLResponse.setEnd(jsonFromString.getAsJsonObject().get("end").getAsString());*/ } } KafkaProducerController.logger.info("Request to CNIT-ML algorithm instance API (updateParameters). Response: " + algorithmCNITMLResponse); return algorithmCNITMLResponse; } }
186_5
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA: // cldrVersion=21.0 // number=$Revision: 6444 $ // type=root // date=$Date: 2012-01-25 16:40:58 -0500 (Wed, 25 Jan 2012) $ /** * Localized names for the "el_POLYTON" locale. */ public class LocalizedNamesImpl_el_POLYTON extends LocalizedNamesImpl_el { @Override public String[] loadSortedRegionCodes() { return new String[] { "BQ", "CW", "SS", "SX", "VA", "SH", "LC", "BL", "VC", "SM", "MF", "AZ", "EG", "ET", "HT", "CI", "AL", "DZ", "VI", "AS", "TL", "AO", "AI", "AD", "AQ", "AG", "UM", "AR", "AM", "AW", "AU", "AT", "AF", "VU", "BE", "VE", "BM", "VN", "BO", "KP", "BA", "BG", "BR", "IO", "VG", "FR", "TF", "GF", "PF", "DE", "GE", "GI", "GM", "GA", "GH", "GG", "GU", "GP", "GT", "GY", "GN", "GW", "GD", "GL", "DK", "DO", "EH", "CH", "GR", "SV", "ER", "EE", "EU", "ZM", "ZW", "SZ", "AE", "US", "GB", "EA", "JP", "IN", "ID", "JO", "IQ", "IR", "IE", "GQ", "EC", "IS", "ES", "IL", "IT", "KZ", "CM", "KH", "CA", "IC", "QA", "CF", "KE", "CN", "KG", "KI", "CO", "KM", "CD", "CG", "CR", "CU", "KW", "HR", "CY", "LA", "LS", "LV", "BY", "LB", "LR", "LY", "LT", "LI", "LU", "YT", "MG", "MO", "MY", "MW", "MV", "ML", "MT", "MA", "MQ", "MU", "MR", "ME", "MX", "FX", "MM", "FM", "MN", "MZ", "MD", "MC", "MS", "BD", "BB", "BS", "BH", "BZ", "BJ", "BW", "BF", "BI", "BT", "BN", "NA", "NR", "NZ", "NC", "NP", "AX", "MP", "KY", "CC", "CK", "MH", "WF", "SJ", "SB", "TC", "FO", "FK", "HM", "AC", "CP", "IM", "BV", "NF", "CX", "NE", "NG", "NI", "NU", "NO", "ZA", "GS", "KR", "DG", "DM", "NL", "AN", "OM", "HN", "HU", "UG", "UZ", "UA", "UY", "PK", "PS", "PW", "PA", "PG", "PY", "MK", "QO", "PE", "PN", "PL", "PT", "PR", "CV", "RE", "RW", "RO", "RU", "KN", "PM", "WS", "ST", "SA", "SN", "RS", "CS", "SC", "SG", "SL", "SK", "SI", "SO", "SD", "SE", "SR", "LK", "SY", "TW", "TH", "TZ", "TJ", "JM", "DJ", "TG", "TK", "TO", "TV", "TR", "TM", "TT", "TA", "TD", "CZ", "TN", "YE", "JE", "PH", "FI", "FJ", "CL", "HK", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("AD", "Ἀνδόρα"); namesMap.put("AE", "Ἠνωμένα Ἀραβικὰ Ἐμιράτα"); namesMap.put("AF", "Ἀφγανιστάν"); namesMap.put("AG", "Ἀντίγκουα καὶ Μπαρμπούντα"); namesMap.put("AI", "Ἀνγκουίλα"); namesMap.put("AL", "Ἀλβανία"); namesMap.put("AM", "Ἀρμενία"); namesMap.put("AN", "Ὁλλανδικὲς Ἀντίλλες"); namesMap.put("AO", "Ἀνγκόλα"); namesMap.put("AQ", "Ἀνταρκτική"); namesMap.put("AR", "Ἀργεντινή"); namesMap.put("AS", "Ἀμερικανικὴ Σαμόα"); namesMap.put("AT", "Αὐστρία"); namesMap.put("AU", "Αὐστραλία"); namesMap.put("AW", "Ἀρούμπα"); namesMap.put("AZ", "Ἀζερμπαϊτζάν"); namesMap.put("BA", "Βοσνία - Ἐρζεγοβίνη"); namesMap.put("BM", "Βερμοῦδες"); namesMap.put("BV", "Νῆσος Μπουβέ"); namesMap.put("CC", "Νῆσοι Κόκος (Κήλινγκ)"); namesMap.put("CD", "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ"); namesMap.put("CF", "Κεντροαφρικανικὴ Δημοκρατία"); namesMap.put("CH", "Ἑλβετία"); namesMap.put("CI", "Ἀκτὴ Ἐλεφαντοστού"); namesMap.put("CK", "Νῆσοι Κούκ"); namesMap.put("CV", "Πράσινο Ἀκρωτήριο"); namesMap.put("CX", "Νῆσος Χριστουγέννων"); namesMap.put("DO", "Δομινικανὴ Δημοκρατία"); namesMap.put("DZ", "Ἀλγερία"); namesMap.put("EC", "Ἰσημερινός"); namesMap.put("EE", "Ἐσθονία"); namesMap.put("EG", "Αἴγυπτος"); namesMap.put("EH", "Δυτικὴ Σαχάρα"); namesMap.put("ER", "Ἐρυθραία"); namesMap.put("ES", "Ἱσπανία"); namesMap.put("ET", "Αἰθιοπία"); namesMap.put("EU", "Εὐρωπαϊκὴ ᾿Ένωση"); namesMap.put("FM", "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς"); namesMap.put("FO", "Νῆσοι Φερόες"); namesMap.put("GB", "Ἡνωμένο Βασίλειο"); namesMap.put("GF", "Γαλλικὴ Γουιάνα"); namesMap.put("GQ", "Ἰσημερινὴ Γουινέα"); namesMap.put("GR", "Ἑλλάδα"); namesMap.put("GS", "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς"); namesMap.put("HK", "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("HM", "Νῆσοι Χὲρντ καὶ Μακντόναλντ"); namesMap.put("HN", "Ὁνδούρα"); namesMap.put("HT", "Ἁϊτή"); namesMap.put("HU", "Οὑγγαρία"); namesMap.put("ID", "Ἰνδονησία"); namesMap.put("IE", "Ἰρλανδία"); namesMap.put("IL", "Ἰσραήλ"); namesMap.put("IN", "Ἰνδία"); namesMap.put("IO", "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ"); namesMap.put("IQ", "Ἰράκ"); namesMap.put("IR", "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ"); namesMap.put("IS", "Ἰσλανδία"); namesMap.put("IT", "Ἰταλία"); namesMap.put("JO", "Ἰορδανία"); namesMap.put("JP", "Ἰαπωνία"); namesMap.put("KN", "Σαὶντ Κὶτς καὶ Νέβις"); namesMap.put("KY", "Νῆσοι Κέιμαν"); namesMap.put("LA", "Λατινικὴ Ἀμερική"); namesMap.put("LC", "Ἁγία Λουκία"); namesMap.put("LK", "Σρὶ Λάνκα"); namesMap.put("LU", "Λουξεμβοῦργο"); namesMap.put("MD", "Μολδαβία, Δημοκρατία τῆς"); namesMap.put("MH", "Νῆσοι Μάρσαλ"); namesMap.put("ML", "Μαλί"); namesMap.put("MO", "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("MP", "Νῆσοι Βόρειες Μαριάνες"); namesMap.put("NF", "Νῆσος Νόρφολκ"); namesMap.put("NL", "Ὁλλανδία"); namesMap.put("OM", "Ὀμάν"); namesMap.put("PF", "Γαλλικὴ Πολυνησία"); namesMap.put("PM", "Σαὶντ Πιὲρ καὶ Μικελόν"); namesMap.put("PS", "Παλαιστινιακὰ Ἐδάφη"); namesMap.put("SA", "Σαουδικὴ Ἀραβία"); namesMap.put("SB", "Νῆσοι Σολομῶντος"); namesMap.put("SH", "Ἁγία Ἑλένη"); namesMap.put("SJ", "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν"); namesMap.put("SM", "Ἅγιος Μαρίνος"); namesMap.put("ST", "Σάο Τομὲ καὶ Πρίνσιπε"); namesMap.put("SV", "Ἒλ Σαλβαδόρ"); namesMap.put("SY", "Συρία, Ἀραβικὴ Δημοκρατία τῆς"); namesMap.put("TC", "Νῆσοι Τὲρκς καὶ Κάικος"); namesMap.put("TD", "Τσάντ"); namesMap.put("TF", "Γαλλικὰ Νότια Ἐδάφη"); namesMap.put("TL", "Ἀνατολικὸ Τιμόρ"); namesMap.put("TT", "Τρινιδὰδ καὶ Τομπάγκο"); namesMap.put("UA", "Οὐκρανία"); namesMap.put("UG", "Οὐγκάντα"); namesMap.put("UM", "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν"); namesMap.put("US", "Ἡνωμένες Πολιτεῖες"); namesMap.put("UY", "Οὐρουγουάη"); namesMap.put("UZ", "Οὐζμπεκιστάν"); namesMap.put("VA", "Ἁγία Ἕδρα (Βατικανό)"); namesMap.put("VC", "Ἅγιος Βικέντιος καὶ Γρεναδίνες"); namesMap.put("VG", "Βρετανικὲς Παρθένοι Νῆσοι"); namesMap.put("VI", "Ἀμερικανικὲς Παρθένοι Νῆσοι"); namesMap.put("WF", "Νῆσοι Οὐάλλις καὶ Φουτουνά"); namesMap.put("YE", "Ὑεμένη"); namesMap.put("ZA", "Νότια Ἀφρική"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ return { "AD": "Ἀνδόρα", "AE": "Ἠνωμένα Ἀραβικὰ Ἐμιράτα", "AF": "Ἀφγανιστάν", "AG": "Ἀντίγκουα καὶ Μπαρμπούντα", "AI": "Ἀνγκουίλα", "AL": "Ἀλβανία", "AM": "Ἀρμενία", "AN": "Ὁλλανδικὲς Ἀντίλλες", "AO": "Ἀνγκόλα", "AQ": "Ἀνταρκτική", "AR": "Ἀργεντινή", "AS": "Ἀμερικανικὴ Σαμόα", "AT": "Αὐστρία", "AU": "Αὐστραλία", "AW": "Ἀρούμπα", "AZ": "Ἀζερμπαϊτζάν", "BA": "Βοσνία - Ἐρζεγοβίνη", "BM": "Βερμοῦδες", "BV": "Νῆσος Μπουβέ", "CC": "Νῆσοι Κόκος (Κήλινγκ)", "CD": "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ", "CF": "Κεντροαφρικανικὴ Δημοκρατία", "CH": "Ἑλβετία", "CI": "Ἀκτὴ Ἐλεφαντοστού", "CK": "Νῆσοι Κούκ", "CV": "Πράσινο Ἀκρωτήριο", "CX": "Νῆσος Χριστουγέννων", "DO": "Δομινικανὴ Δημοκρατία", "DZ": "Ἀλγερία", "EC": "Ἰσημερινός", "EE": "Ἐσθονία", "EG": "Αἴγυπτος", "EH": "Δυτικὴ Σαχάρα", "ER": "Ἐρυθραία", "ES": "Ἱσπανία", "ET": "Αἰθιοπία", "EU": "Εὐρωπαϊκὴ ᾿Ένωση", "FM": "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς", "FO": "Νῆσοι Φερόες", "GB": "Ἡνωμένο Βασίλειο", "GF": "Γαλλικὴ Γουιάνα", "GQ": "Ἰσημερινὴ Γουινέα", "GR": "Ἑλλάδα", "GS": "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς", "HK": "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "HM": "Νῆσοι Χὲρντ καὶ Μακντόναλντ", "HN": "Ὁνδούρα", "HT": "Ἁϊτή", "HU": "Οὑγγαρία", "ID": "Ἰνδονησία", "IE": "Ἰρλανδία", "IL": "Ἰσραήλ", "IN": "Ἰνδία", "IO": "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ", "IQ": "Ἰράκ", "IR": "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ", "IS": "Ἰσλανδία", "IT": "Ἰταλία", "JO": "Ἰορδανία", "JP": "Ἰαπωνία", "KN": "Σαὶντ Κὶτς καὶ Νέβις", "KY": "Νῆσοι Κέιμαν", "LA": "Λατινικὴ Ἀμερική", "LC": "Ἁγία Λουκία", "LK": "Σρὶ Λάνκα", "LU": "Λουξεμβοῦργο", "MD": "Μολδαβία, Δημοκρατία τῆς", "MH": "Νῆσοι Μάρσαλ", "ML": "Μαλί", "MO": "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "MP": "Νῆσοι Βόρειες Μαριάνες", "NF": "Νῆσος Νόρφολκ", "NL": "Ὁλλανδία", "OM": "Ὀμάν", "PF": "Γαλλικὴ Πολυνησία", "PM": "Σαὶντ Πιὲρ καὶ Μικελόν", "PS": "Παλαιστινιακὰ Ἐδάφη", "SA": "Σαουδικὴ Ἀραβία", "SB": "Νῆσοι Σολομῶντος", "SH": "Ἁγία Ἑλένη", "SJ": "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν", "SM": "Ἅγιος Μαρίνος", "ST": "Σάο Τομὲ καὶ Πρίνσιπε", "SV": "Ἒλ Σαλβαδόρ", "SY": "Συρία, Ἀραβικὴ Δημοκρατία τῆς", "TC": "Νῆσοι Τὲρκς καὶ Κάικος", "TD": "Τσάντ", "TF": "Γαλλικὰ Νότια Ἐδάφη", "TL": "Ἀνατολικὸ Τιμόρ", "TT": "Τρινιδὰδ καὶ Τομπάγκο", "UA": "Οὐκρανία", "UG": "Οὐγκάντα", "UM": "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν", "US": "Ἡνωμένες Πολιτεῖες", "UY": "Οὐρουγουάη", "UZ": "Οὐζμπεκιστάν", "VA": "Ἁγία Ἕδρα (Βατικανό)", "VC": "Ἅγιος Βικέντιος καὶ Γρεναδίνες", "VG": "Βρετανικὲς Παρθένοι Νῆσοι", "VI": "Ἀμερικανικὲς Παρθένοι Νῆσοι", "WF": "Νῆσοι Οὐάλλις καὶ Φουτουνά", "YE": "Ὑεμένη", "ZA": "Νότια Ἀφρική" }; }-*/; }
gwtproject/gwt
user/src/com/google/gwt/i18n/client/impl/cldr/LocalizedNamesImpl_el_POLYTON.java
6,699
/*-{ return { "AD": "Ἀνδόρα", "AE": "Ἠνωμένα Ἀραβικὰ Ἐμιράτα", "AF": "Ἀφγανιστάν", "AG": "Ἀντίγκουα καὶ Μπαρμπούντα", "AI": "Ἀνγκουίλα", "AL": "Ἀλβανία", "AM": "Ἀρμενία", "AN": "Ὁλλανδικὲς Ἀντίλλες", "AO": "Ἀνγκόλα", "AQ": "Ἀνταρκτική", "AR": "Ἀργεντινή", "AS": "Ἀμερικανικὴ Σαμόα", "AT": "Αὐστρία", "AU": "Αὐστραλία", "AW": "Ἀρούμπα", "AZ": "Ἀζερμπαϊτζάν", "BA": "Βοσνία - Ἐρζεγοβίνη", "BM": "Βερμοῦδες", "BV": "Νῆσος Μπουβέ", "CC": "Νῆσοι Κόκος (Κήλινγκ)", "CD": "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ", "CF": "Κεντροαφρικανικὴ Δημοκρατία", "CH": "Ἑλβετία", "CI": "Ἀκτὴ Ἐλεφαντοστού", "CK": "Νῆσοι Κούκ", "CV": "Πράσινο Ἀκρωτήριο", "CX": "Νῆσος Χριστουγέννων", "DO": "Δομινικανὴ Δημοκρατία", "DZ": "Ἀλγερία", "EC": "Ἰσημερινός", "EE": "Ἐσθονία", "EG": "Αἴγυπτος", "EH": "Δυτικὴ Σαχάρα", "ER": "Ἐρυθραία", "ES": "Ἱσπανία", "ET": "Αἰθιοπία", "EU": "Εὐρωπαϊκὴ ᾿Ένωση", "FM": "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς", "FO": "Νῆσοι Φερόες", "GB": "Ἡνωμένο Βασίλειο", "GF": "Γαλλικὴ Γουιάνα", "GQ": "Ἰσημερινὴ Γουινέα", "GR": "Ἑλλάδα", "GS": "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς", "HK": "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "HM": "Νῆσοι Χὲρντ καὶ Μακντόναλντ", "HN": "Ὁνδούρα", "HT": "Ἁϊτή", "HU": "Οὑγγαρία", "ID": "Ἰνδονησία", "IE": "Ἰρλανδία", "IL": "Ἰσραήλ", "IN": "Ἰνδία", "IO": "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ", "IQ": "Ἰράκ", "IR": "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ", "IS": "Ἰσλανδία", "IT": "Ἰταλία", "JO": "Ἰορδανία", "JP": "Ἰαπωνία", "KN": "Σαὶντ Κὶτς καὶ Νέβις", "KY": "Νῆσοι Κέιμαν", "LA": "Λατινικὴ Ἀμερική", "LC": "Ἁγία Λουκία", "LK": "Σρὶ Λάνκα", "LU": "Λουξεμβοῦργο", "MD": "Μολδαβία, Δημοκρατία τῆς", "MH": "Νῆσοι Μάρσαλ", "ML": "Μαλί", "MO": "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "MP": "Νῆσοι Βόρειες Μαριάνες", "NF": "Νῆσος Νόρφολκ", "NL": "Ὁλλανδία", "OM": "Ὀμάν", "PF": "Γαλλικὴ Πολυνησία", "PM": "Σαὶντ Πιὲρ καὶ Μικελόν", "PS": "Παλαιστινιακὰ Ἐδάφη", "SA": "Σαουδικὴ Ἀραβία", "SB": "Νῆσοι Σολομῶντος", "SH": "Ἁγία Ἑλένη", "SJ": "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν", "SM": "Ἅγιος Μαρίνος", "ST": "Σάο Τομὲ καὶ Πρίνσιπε", "SV": "Ἒλ Σαλβαδόρ", "SY": "Συρία, Ἀραβικὴ Δημοκρατία τῆς", "TC": "Νῆσοι Τὲρκς καὶ Κάικος", "TD": "Τσάντ", "TF": "Γαλλικὰ Νότια Ἐδάφη", "TL": "Ἀνατολικὸ Τιμόρ", "TT": "Τρινιδὰδ καὶ Τομπάγκο", "UA": "Οὐκρανία", "UG": "Οὐγκάντα", "UM": "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν", "US": "Ἡνωμένες Πολιτεῖες", "UY": "Οὐρουγουάη", "UZ": "Οὐζμπεκιστάν", "VA": "Ἁγία Ἕδρα (Βατικανό)", "VC": "Ἅγιος Βικέντιος καὶ Γρεναδίνες", "VG": "Βρετανικὲς Παρθένοι Νῆσοι", "VI": "Ἀμερικανικὲς Παρθένοι Νῆσοι", "WF": "Νῆσοι Οὐάλλις καὶ Φουτουνά", "YE": "Ὑεμένη", "ZA": "Νότια Ἀφρική" }; }-*/
block_comment
el
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA: // cldrVersion=21.0 // number=$Revision: 6444 $ // type=root // date=$Date: 2012-01-25 16:40:58 -0500 (Wed, 25 Jan 2012) $ /** * Localized names for the "el_POLYTON" locale. */ public class LocalizedNamesImpl_el_POLYTON extends LocalizedNamesImpl_el { @Override public String[] loadSortedRegionCodes() { return new String[] { "BQ", "CW", "SS", "SX", "VA", "SH", "LC", "BL", "VC", "SM", "MF", "AZ", "EG", "ET", "HT", "CI", "AL", "DZ", "VI", "AS", "TL", "AO", "AI", "AD", "AQ", "AG", "UM", "AR", "AM", "AW", "AU", "AT", "AF", "VU", "BE", "VE", "BM", "VN", "BO", "KP", "BA", "BG", "BR", "IO", "VG", "FR", "TF", "GF", "PF", "DE", "GE", "GI", "GM", "GA", "GH", "GG", "GU", "GP", "GT", "GY", "GN", "GW", "GD", "GL", "DK", "DO", "EH", "CH", "GR", "SV", "ER", "EE", "EU", "ZM", "ZW", "SZ", "AE", "US", "GB", "EA", "JP", "IN", "ID", "JO", "IQ", "IR", "IE", "GQ", "EC", "IS", "ES", "IL", "IT", "KZ", "CM", "KH", "CA", "IC", "QA", "CF", "KE", "CN", "KG", "KI", "CO", "KM", "CD", "CG", "CR", "CU", "KW", "HR", "CY", "LA", "LS", "LV", "BY", "LB", "LR", "LY", "LT", "LI", "LU", "YT", "MG", "MO", "MY", "MW", "MV", "ML", "MT", "MA", "MQ", "MU", "MR", "ME", "MX", "FX", "MM", "FM", "MN", "MZ", "MD", "MC", "MS", "BD", "BB", "BS", "BH", "BZ", "BJ", "BW", "BF", "BI", "BT", "BN", "NA", "NR", "NZ", "NC", "NP", "AX", "MP", "KY", "CC", "CK", "MH", "WF", "SJ", "SB", "TC", "FO", "FK", "HM", "AC", "CP", "IM", "BV", "NF", "CX", "NE", "NG", "NI", "NU", "NO", "ZA", "GS", "KR", "DG", "DM", "NL", "AN", "OM", "HN", "HU", "UG", "UZ", "UA", "UY", "PK", "PS", "PW", "PA", "PG", "PY", "MK", "QO", "PE", "PN", "PL", "PT", "PR", "CV", "RE", "RW", "RO", "RU", "KN", "PM", "WS", "ST", "SA", "SN", "RS", "CS", "SC", "SG", "SL", "SK", "SI", "SO", "SD", "SE", "SR", "LK", "SY", "TW", "TH", "TZ", "TJ", "JM", "DJ", "TG", "TK", "TO", "TV", "TR", "TM", "TT", "TA", "TD", "CZ", "TN", "YE", "JE", "PH", "FI", "FJ", "CL", "HK", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("AD", "Ἀνδόρα"); namesMap.put("AE", "Ἠνωμένα Ἀραβικὰ Ἐμιράτα"); namesMap.put("AF", "Ἀφγανιστάν"); namesMap.put("AG", "Ἀντίγκουα καὶ Μπαρμπούντα"); namesMap.put("AI", "Ἀνγκουίλα"); namesMap.put("AL", "Ἀλβανία"); namesMap.put("AM", "Ἀρμενία"); namesMap.put("AN", "Ὁλλανδικὲς Ἀντίλλες"); namesMap.put("AO", "Ἀνγκόλα"); namesMap.put("AQ", "Ἀνταρκτική"); namesMap.put("AR", "Ἀργεντινή"); namesMap.put("AS", "Ἀμερικανικὴ Σαμόα"); namesMap.put("AT", "Αὐστρία"); namesMap.put("AU", "Αὐστραλία"); namesMap.put("AW", "Ἀρούμπα"); namesMap.put("AZ", "Ἀζερμπαϊτζάν"); namesMap.put("BA", "Βοσνία - Ἐρζεγοβίνη"); namesMap.put("BM", "Βερμοῦδες"); namesMap.put("BV", "Νῆσος Μπουβέ"); namesMap.put("CC", "Νῆσοι Κόκος (Κήλινγκ)"); namesMap.put("CD", "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ"); namesMap.put("CF", "Κεντροαφρικανικὴ Δημοκρατία"); namesMap.put("CH", "Ἑλβετία"); namesMap.put("CI", "Ἀκτὴ Ἐλεφαντοστού"); namesMap.put("CK", "Νῆσοι Κούκ"); namesMap.put("CV", "Πράσινο Ἀκρωτήριο"); namesMap.put("CX", "Νῆσος Χριστουγέννων"); namesMap.put("DO", "Δομινικανὴ Δημοκρατία"); namesMap.put("DZ", "Ἀλγερία"); namesMap.put("EC", "Ἰσημερινός"); namesMap.put("EE", "Ἐσθονία"); namesMap.put("EG", "Αἴγυπτος"); namesMap.put("EH", "Δυτικὴ Σαχάρα"); namesMap.put("ER", "Ἐρυθραία"); namesMap.put("ES", "Ἱσπανία"); namesMap.put("ET", "Αἰθιοπία"); namesMap.put("EU", "Εὐρωπαϊκὴ ᾿Ένωση"); namesMap.put("FM", "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς"); namesMap.put("FO", "Νῆσοι Φερόες"); namesMap.put("GB", "Ἡνωμένο Βασίλειο"); namesMap.put("GF", "Γαλλικὴ Γουιάνα"); namesMap.put("GQ", "Ἰσημερινὴ Γουινέα"); namesMap.put("GR", "Ἑλλάδα"); namesMap.put("GS", "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς"); namesMap.put("HK", "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("HM", "Νῆσοι Χὲρντ καὶ Μακντόναλντ"); namesMap.put("HN", "Ὁνδούρα"); namesMap.put("HT", "Ἁϊτή"); namesMap.put("HU", "Οὑγγαρία"); namesMap.put("ID", "Ἰνδονησία"); namesMap.put("IE", "Ἰρλανδία"); namesMap.put("IL", "Ἰσραήλ"); namesMap.put("IN", "Ἰνδία"); namesMap.put("IO", "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ"); namesMap.put("IQ", "Ἰράκ"); namesMap.put("IR", "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ"); namesMap.put("IS", "Ἰσλανδία"); namesMap.put("IT", "Ἰταλία"); namesMap.put("JO", "Ἰορδανία"); namesMap.put("JP", "Ἰαπωνία"); namesMap.put("KN", "Σαὶντ Κὶτς καὶ Νέβις"); namesMap.put("KY", "Νῆσοι Κέιμαν"); namesMap.put("LA", "Λατινικὴ Ἀμερική"); namesMap.put("LC", "Ἁγία Λουκία"); namesMap.put("LK", "Σρὶ Λάνκα"); namesMap.put("LU", "Λουξεμβοῦργο"); namesMap.put("MD", "Μολδαβία, Δημοκρατία τῆς"); namesMap.put("MH", "Νῆσοι Μάρσαλ"); namesMap.put("ML", "Μαλί"); namesMap.put("MO", "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("MP", "Νῆσοι Βόρειες Μαριάνες"); namesMap.put("NF", "Νῆσος Νόρφολκ"); namesMap.put("NL", "Ὁλλανδία"); namesMap.put("OM", "Ὀμάν"); namesMap.put("PF", "Γαλλικὴ Πολυνησία"); namesMap.put("PM", "Σαὶντ Πιὲρ καὶ Μικελόν"); namesMap.put("PS", "Παλαιστινιακὰ Ἐδάφη"); namesMap.put("SA", "Σαουδικὴ Ἀραβία"); namesMap.put("SB", "Νῆσοι Σολομῶντος"); namesMap.put("SH", "Ἁγία Ἑλένη"); namesMap.put("SJ", "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν"); namesMap.put("SM", "Ἅγιος Μαρίνος"); namesMap.put("ST", "Σάο Τομὲ καὶ Πρίνσιπε"); namesMap.put("SV", "Ἒλ Σαλβαδόρ"); namesMap.put("SY", "Συρία, Ἀραβικὴ Δημοκρατία τῆς"); namesMap.put("TC", "Νῆσοι Τὲρκς καὶ Κάικος"); namesMap.put("TD", "Τσάντ"); namesMap.put("TF", "Γαλλικὰ Νότια Ἐδάφη"); namesMap.put("TL", "Ἀνατολικὸ Τιμόρ"); namesMap.put("TT", "Τρινιδὰδ καὶ Τομπάγκο"); namesMap.put("UA", "Οὐκρανία"); namesMap.put("UG", "Οὐγκάντα"); namesMap.put("UM", "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν"); namesMap.put("US", "Ἡνωμένες Πολιτεῖες"); namesMap.put("UY", "Οὐρουγουάη"); namesMap.put("UZ", "Οὐζμπεκιστάν"); namesMap.put("VA", "Ἁγία Ἕδρα (Βατικανό)"); namesMap.put("VC", "Ἅγιος Βικέντιος καὶ Γρεναδίνες"); namesMap.put("VG", "Βρετανικὲς Παρθένοι Νῆσοι"); namesMap.put("VI", "Ἀμερικανικὲς Παρθένοι Νῆσοι"); namesMap.put("WF", "Νῆσοι Οὐάλλις καὶ Φουτουνά"); namesMap.put("YE", "Ὑεμένη"); namesMap.put("ZA", "Νότια Ἀφρική"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ <SUF>*/; }
3349_26
package org.opentox.toxotis.persistence; import java.io.File; import java.net.URI; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import javax.sql.rowset.serial.SerialBlob; import org.apache.log4j.Logger; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.opentox.toxotis.client.VRI; import org.opentox.toxotis.client.collection.Services; import org.opentox.toxotis.core.component.Algorithm; import org.opentox.toxotis.core.component.BibTeX; import org.opentox.toxotis.core.component.Dataset; import org.opentox.toxotis.core.component.Model; import org.opentox.toxotis.core.component.Parameter; import org.opentox.toxotis.core.component.Task; import org.opentox.toxotis.ontology.collection.OTAlgorithmTypes; import org.opentox.toxotis.ontology.collection.OTClasses; import org.opentox.toxotis.persistence.db.DeleteTool; import org.opentox.toxotis.persistence.db.RegisterTool; import org.opentox.toxotis.persistence.util.HibernateUtil; import org.opentox.toxotis.util.aa.AuthenticationToken; /** * * @author Pantelis Sopasakis * @author Charalampos Chomenides */ public class Persist { public static void main(String[] args) throws Exception { org.apache.log4j.LogManager.resetConfiguration(); org.apache.log4j.PropertyConfigurator.configure("config/log4j.properties"); SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); // Question: How can we know if the database is newly created? // (In order to know whether we have to execute the following lines...) final boolean doAlter = true; if (doAlter) { try { Connection c = session.connection(); Statement stmt = c.createStatement(); stmt.addBatch("ALTER TABLE FeatOntol DROP PRIMARY KEY"); stmt.addBatch("ALTER TABLE FeatOntol ADD `ID_W` INT NOT NULL AUTO_INCREMENT PRIMARY KEY"); stmt.addBatch("ALTER TABLE OTComponent ADD `created` TIMESTAMP NOT NULL DEFAULT NOW()"); stmt.addBatch("ALTER TABLE User ADD `created` TIMESTAMP NOT NULL DEFAULT NOW()"); stmt.executeBatch(); } catch (HibernateException hbe) { hbe.printStackTrace(); } catch (SQLException sqle) { System.err.println("Info: Alter failed (Probably not an error!)"); Logger.getLogger(Persist.class).debug("Alter failed (Probably not an error!)", sqle); } catch (Exception e) { e.printStackTrace(); } } /* * OPEN SESSION */ session = sf.openSession(); // DeleteTool.deleteTask(session, Task.Status.RUNNING, Task.Status.QUEUED); System.out.println("Storing Ontological Classes"); RegisterTool.storeAllOntClasses(session); System.out.println("Ontological Classes stored successfully!\n"); // System.out.println("Acquiring Token..."); AuthenticationToken at = new AuthenticationToken(new File("/home/chung/toxotisKeys/my.key")); System.out.println("Done!"); System.out.println("Authentication Token : \n" + at); System.out.println("User:\n" + at.getUser()); // // System.out.println("Loading Algorithm"); // Algorithm algorithm = new Algorithm(Services.ntua().augment("algorithm", "svm")).loadFromRemote(at); // System.out.println("Algorithm Loaded"); // System.out.println("Storing Algorithm"); // RegisterTool.storeAlgorithm(algorithm, session); // System.out.println("Algorithm registered successfully!\n"); // // System.out.println("Loading Dataset"); // Dataset d = new Dataset(Services.ideaconsult().augment("dataset", "9").addUrlParameter("max", "50")).loadFromRemote(); // System.out.println("Dataset Loaded"); // System.out.println("Storing Dataset"); // RegisterTool.storeDataset(d, session); // System.out.println("Dataset registered successfully!\n"); // // System.out.println("Loading Model"); // Model model = new Model(Services.ntua().augment("model", "934ef1d0-2080-48eb-9f65-f61b830b5783")).loadFromRemote(); // model.setActualModel(new java.net.URI("http://in.gr/#asdf")); // System.out.println("Model Loaded"); // System.out.println("Storing Model"); // RegisterTool.storeModel(model, session); // System.out.println("Model registered successfully!\n"); // // System.out.println("Loading Tasks"); // Task task_complete = new Task(Services.ntua().augment("task", "68d471ad-0287-4f6e-a200-244d0234e8a1")).loadFromRemote(at); // System.out.println("Task #1 Loaded"); // Task task_error = new Task(Services.ntua().augment("task", "0980cbb3-a4a8-4a89-8538-51992d2fc67f")).loadFromRemote(at); // System.out.println("Task #2 Loaded"); // System.out.println("Storing Tasks"); // RegisterTool.storeTask(session, task_complete); // System.out.println("Task #1 registered successfully!"); // RegisterTool.storeTask(session, task_error); // System.out.println("Task #2 registered successfully!"); // System.out.println(); // BibTeX b = new BibTeX(Services.ntua().augment("bibtex","1")); // b.setAnnotation("asdf"); // b.setAuthor("gdfgfdg"); // RegisterTool.storeBibTeX(session, b); /* * For more info about criteria read: * http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html */ System.out.println(OTClasses.Algorithm()); List resultsFoundInDB = session.createCriteria(Task.class).add(Restrictions.eq("uri", "http://localhost:3000/task/dac56a96-7627-4cd6-9dda-c11083078ccb")).list(); // add(Restrictions.like("uri", "%svm")).list(); System.out.println("found " + resultsFoundInDB.size()); for (Object o : resultsFoundInDB) { Task t = (Task) o; VRI c = t.getUri(); System.out.println(c); System.out.println(t.getMeta().getHasSources()); } session.close(); } } // Όταν μεγαλώσω θέλω, // θέλω να γίνω 82 χρονών // τσατσά σ'ένα μπουρδέλο // χωρίς δόντια να μασάω τα κρουτόν // και να διαβάζω Οθέλο // // Όταν μεγαλώσω θέλω // θελώ να γίνω διαστημικός σταθμός // και να παίζω μπουγέλο // κι από μένανε να βρέχει κι ο ουρανός // τα ρούχα να σας πλένω // // Η ομορφιά του θέλω, // Μάρω Μαρκέλου //
hampos/ToxOtis-Persistence
src/org/opentox/toxotis/persistence/Persist.java
2,075
// και να παίζω μπουγέλο
line_comment
el
package org.opentox.toxotis.persistence; import java.io.File; import java.net.URI; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import javax.sql.rowset.serial.SerialBlob; import org.apache.log4j.Logger; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.opentox.toxotis.client.VRI; import org.opentox.toxotis.client.collection.Services; import org.opentox.toxotis.core.component.Algorithm; import org.opentox.toxotis.core.component.BibTeX; import org.opentox.toxotis.core.component.Dataset; import org.opentox.toxotis.core.component.Model; import org.opentox.toxotis.core.component.Parameter; import org.opentox.toxotis.core.component.Task; import org.opentox.toxotis.ontology.collection.OTAlgorithmTypes; import org.opentox.toxotis.ontology.collection.OTClasses; import org.opentox.toxotis.persistence.db.DeleteTool; import org.opentox.toxotis.persistence.db.RegisterTool; import org.opentox.toxotis.persistence.util.HibernateUtil; import org.opentox.toxotis.util.aa.AuthenticationToken; /** * * @author Pantelis Sopasakis * @author Charalampos Chomenides */ public class Persist { public static void main(String[] args) throws Exception { org.apache.log4j.LogManager.resetConfiguration(); org.apache.log4j.PropertyConfigurator.configure("config/log4j.properties"); SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); // Question: How can we know if the database is newly created? // (In order to know whether we have to execute the following lines...) final boolean doAlter = true; if (doAlter) { try { Connection c = session.connection(); Statement stmt = c.createStatement(); stmt.addBatch("ALTER TABLE FeatOntol DROP PRIMARY KEY"); stmt.addBatch("ALTER TABLE FeatOntol ADD `ID_W` INT NOT NULL AUTO_INCREMENT PRIMARY KEY"); stmt.addBatch("ALTER TABLE OTComponent ADD `created` TIMESTAMP NOT NULL DEFAULT NOW()"); stmt.addBatch("ALTER TABLE User ADD `created` TIMESTAMP NOT NULL DEFAULT NOW()"); stmt.executeBatch(); } catch (HibernateException hbe) { hbe.printStackTrace(); } catch (SQLException sqle) { System.err.println("Info: Alter failed (Probably not an error!)"); Logger.getLogger(Persist.class).debug("Alter failed (Probably not an error!)", sqle); } catch (Exception e) { e.printStackTrace(); } } /* * OPEN SESSION */ session = sf.openSession(); // DeleteTool.deleteTask(session, Task.Status.RUNNING, Task.Status.QUEUED); System.out.println("Storing Ontological Classes"); RegisterTool.storeAllOntClasses(session); System.out.println("Ontological Classes stored successfully!\n"); // System.out.println("Acquiring Token..."); AuthenticationToken at = new AuthenticationToken(new File("/home/chung/toxotisKeys/my.key")); System.out.println("Done!"); System.out.println("Authentication Token : \n" + at); System.out.println("User:\n" + at.getUser()); // // System.out.println("Loading Algorithm"); // Algorithm algorithm = new Algorithm(Services.ntua().augment("algorithm", "svm")).loadFromRemote(at); // System.out.println("Algorithm Loaded"); // System.out.println("Storing Algorithm"); // RegisterTool.storeAlgorithm(algorithm, session); // System.out.println("Algorithm registered successfully!\n"); // // System.out.println("Loading Dataset"); // Dataset d = new Dataset(Services.ideaconsult().augment("dataset", "9").addUrlParameter("max", "50")).loadFromRemote(); // System.out.println("Dataset Loaded"); // System.out.println("Storing Dataset"); // RegisterTool.storeDataset(d, session); // System.out.println("Dataset registered successfully!\n"); // // System.out.println("Loading Model"); // Model model = new Model(Services.ntua().augment("model", "934ef1d0-2080-48eb-9f65-f61b830b5783")).loadFromRemote(); // model.setActualModel(new java.net.URI("http://in.gr/#asdf")); // System.out.println("Model Loaded"); // System.out.println("Storing Model"); // RegisterTool.storeModel(model, session); // System.out.println("Model registered successfully!\n"); // // System.out.println("Loading Tasks"); // Task task_complete = new Task(Services.ntua().augment("task", "68d471ad-0287-4f6e-a200-244d0234e8a1")).loadFromRemote(at); // System.out.println("Task #1 Loaded"); // Task task_error = new Task(Services.ntua().augment("task", "0980cbb3-a4a8-4a89-8538-51992d2fc67f")).loadFromRemote(at); // System.out.println("Task #2 Loaded"); // System.out.println("Storing Tasks"); // RegisterTool.storeTask(session, task_complete); // System.out.println("Task #1 registered successfully!"); // RegisterTool.storeTask(session, task_error); // System.out.println("Task #2 registered successfully!"); // System.out.println(); // BibTeX b = new BibTeX(Services.ntua().augment("bibtex","1")); // b.setAnnotation("asdf"); // b.setAuthor("gdfgfdg"); // RegisterTool.storeBibTeX(session, b); /* * For more info about criteria read: * http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html */ System.out.println(OTClasses.Algorithm()); List resultsFoundInDB = session.createCriteria(Task.class).add(Restrictions.eq("uri", "http://localhost:3000/task/dac56a96-7627-4cd6-9dda-c11083078ccb")).list(); // add(Restrictions.like("uri", "%svm")).list(); System.out.println("found " + resultsFoundInDB.size()); for (Object o : resultsFoundInDB) { Task t = (Task) o; VRI c = t.getUri(); System.out.println(c); System.out.println(t.getMeta().getHasSources()); } session.close(); } } // Όταν μεγαλώσω θέλω, // θέλω να γίνω 82 χρονών // τσατσά σ'ένα μπουρδέλο // χωρίς δόντια να μασάω τα κρουτόν // και να διαβάζω Οθέλο // // Όταν μεγαλώσω θέλω // θελώ να γίνω διαστημικός σταθμός // και να<SUF> // κι από μένανε να βρέχει κι ο ουρανός // τα ρούχα να σας πλένω // // Η ομορφιά του θέλω, // Μάρω Μαρκέλου //
181_3
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA /** * Localized names for the "el_POLYTON" locale. */ public class LocalizedNamesImpl_el_POLYTON extends LocalizedNamesImpl_el { @Override public String[] loadSortedRegionCodes() { return new String[] { "VA", "SH", "LC", "BL", "VC", "SM", "MF", "AZ", "EG", "ET", "HT", "CI", "AL", "DZ", "VI", "AS", "TL", "AO", "AI", "AD", "AQ", "AG", "UM", "AR", "AM", "AW", "AU", "AT", "AF", "VU", "BE", "VE", "BM", "VN", "BO", "KP", "BA", "BG", "BR", "IO", "VG", "FR", "FX", "TF", "GF", "PF", "DE", "GE", "GI", "GM", "GA", "GH", "GG", "GU", "GP", "GT", "GY", "GN", "GW", "GD", "GL", "DK", "DO", "EH", "CH", "GR", "SV", "ER", "EE", "EU", "ZM", "ZW", "SZ", "AE", "US", "GB", "EA", "JP", "IN", "ID", "JO", "IQ", "IR", "IE", "GQ", "EC", "IS", "ES", "IL", "IT", "KZ", "CM", "KH", "CA", "IC", "QA", "CF", "KE", "CN", "KG", "KI", "CO", "KM", "CD", "CG", "CR", "CU", "KW", "HR", "CY", "LA", "LS", "LV", "BY", "LB", "LR", "LY", "LT", "LI", "LU", "YT", "MG", "MO", "MY", "MW", "MV", "ML", "MT", "MA", "MQ", "MU", "MR", "ME", "MX", "MM", "FM", "MN", "MZ", "MD", "MC", "MS", "BD", "BB", "BS", "BH", "BZ", "BJ", "BW", "BF", "BI", "BT", "BN", "NA", "NR", "NZ", "NC", "NP", "AX", "MP", "KY", "CC", "CK", "MH", "WF", "SJ", "SB", "TC", "FO", "FK", "HM", "AC", "CP", "IM", "BV", "NF", "CX", "NE", "NG", "NI", "NU", "NO", "ZA", "GS", "KR", "DG", "DM", "NL", "AN", "OM", "HN", "HU", "UG", "UZ", "UA", "UY", "PK", "PS", "PW", "PA", "PG", "PY", "MK", "QO", "PE", "PN", "PL", "PT", "PR", "CV", "RE", "RW", "RO", "RU", "KN", "PM", "WS", "ST", "SA", "SN", "RS", "CS", "SC", "SG", "SL", "SK", "SI", "SO", "SD", "SE", "SR", "LK", "SY", "TW", "TH", "TZ", "TJ", "JM", "DJ", "TG", "TK", "TO", "TV", "TR", "TM", "TT", "TA", "TD", "CZ", "TN", "YE", "JE", "PH", "FI", "FJ", "CL", "HK", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("AD", "Ἀνδόρα"); namesMap.put("AE", "Ἠνωμένα Ἀραβικὰ Ἐμιράτα"); namesMap.put("AF", "Ἀφγανιστάν"); namesMap.put("AG", "Ἀντίγκουα καὶ Μπαρμπούντα"); namesMap.put("AI", "Ἀνγκουίλα"); namesMap.put("AL", "Ἀλβανία"); namesMap.put("AM", "Ἀρμενία"); namesMap.put("AN", "Ὁλλανδικὲς Ἀντίλλες"); namesMap.put("AO", "Ἀνγκόλα"); namesMap.put("AQ", "Ἀνταρκτική"); namesMap.put("AR", "Ἀργεντινή"); namesMap.put("AS", "Ἀμερικανικὴ Σαμόα"); namesMap.put("AT", "Αὐστρία"); namesMap.put("AU", "Αὐστραλία"); namesMap.put("AW", "Ἀρούμπα"); namesMap.put("AZ", "Ἀζερμπαϊτζάν"); namesMap.put("BA", "Βοσνία - Ἐρζεγοβίνη"); namesMap.put("BM", "Βερμοῦδες"); namesMap.put("BV", "Νῆσος Μπουβέ"); namesMap.put("CC", "Νῆσοι Κόκος (Κήλινγκ)"); namesMap.put("CD", "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ"); namesMap.put("CF", "Κεντροαφρικανικὴ Δημοκρατία"); namesMap.put("CH", "Ἑλβετία"); namesMap.put("CI", "Ἀκτὴ Ἐλεφαντοστού"); namesMap.put("CK", "Νῆσοι Κούκ"); namesMap.put("CV", "Πράσινο Ἀκρωτήριο"); namesMap.put("CX", "Νῆσος Χριστουγέννων"); namesMap.put("DO", "Δομινικανὴ Δημοκρατία"); namesMap.put("DZ", "Ἀλγερία"); namesMap.put("EC", "Ἰσημερινός"); namesMap.put("EE", "Ἐσθονία"); namesMap.put("EG", "Αἴγυπτος"); namesMap.put("EH", "Δυτικὴ Σαχάρα"); namesMap.put("ER", "Ἐρυθραία"); namesMap.put("ES", "Ἱσπανία"); namesMap.put("ET", "Αἰθιοπία"); namesMap.put("EU", "Εὐρωπαϊκὴ ᾿Ένωση"); namesMap.put("FM", "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς"); namesMap.put("FO", "Νῆσοι Φερόες"); namesMap.put("GB", "Ἡνωμένο Βασίλειο"); namesMap.put("GF", "Γαλλικὴ Γουιάνα"); namesMap.put("GQ", "Ἰσημερινὴ Γουινέα"); namesMap.put("GR", "Ἑλλάδα"); namesMap.put("GS", "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς"); namesMap.put("HK", "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("HM", "Νῆσοι Χὲρντ καὶ Μακντόναλντ"); namesMap.put("HN", "Ὁνδούρα"); namesMap.put("HT", "Ἁϊτή"); namesMap.put("HU", "Οὑγγαρία"); namesMap.put("ID", "Ἰνδονησία"); namesMap.put("IE", "Ἰρλανδία"); namesMap.put("IL", "Ἰσραήλ"); namesMap.put("IN", "Ἰνδία"); namesMap.put("IO", "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ"); namesMap.put("IQ", "Ἰράκ"); namesMap.put("IR", "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ"); namesMap.put("IS", "Ἰσλανδία"); namesMap.put("IT", "Ἰταλία"); namesMap.put("JO", "Ἰορδανία"); namesMap.put("JP", "Ἰαπωνία"); namesMap.put("KN", "Σαὶντ Κὶτς καὶ Νέβις"); namesMap.put("KY", "Νῆσοι Κέιμαν"); namesMap.put("LA", "Λατινικὴ Ἀμερική"); namesMap.put("LC", "Ἁγία Λουκία"); namesMap.put("LK", "Σρὶ Λάνκα"); namesMap.put("LU", "Λουξεμβοῦργο"); namesMap.put("MD", "Μολδαβία, Δημοκρατία τῆς"); namesMap.put("MH", "Νῆσοι Μάρσαλ"); namesMap.put("ML", "Μαλί"); namesMap.put("MO", "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("MP", "Νῆσοι Βόρειες Μαριάνες"); namesMap.put("NF", "Νῆσος Νόρφολκ"); namesMap.put("NL", "Ὁλλανδία"); namesMap.put("OM", "Ὀμάν"); namesMap.put("PF", "Γαλλικὴ Πολυνησία"); namesMap.put("PM", "Σαὶντ Πιὲρ καὶ Μικελόν"); namesMap.put("PS", "Παλαιστινιακὰ Ἐδάφη"); namesMap.put("SA", "Σαουδικὴ Ἀραβία"); namesMap.put("SB", "Νῆσοι Σολομῶντος"); namesMap.put("SH", "Ἁγία Ἑλένη"); namesMap.put("SJ", "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν"); namesMap.put("SM", "Ἅγιος Μαρίνος"); namesMap.put("ST", "Σάο Τομὲ καὶ Πρίνσιπε"); namesMap.put("SV", "Ἒλ Σαλβαδόρ"); namesMap.put("SY", "Συρία, Ἀραβικὴ Δημοκρατία τῆς"); namesMap.put("TC", "Νῆσοι Τὲρκς καὶ Κάικος"); namesMap.put("TD", "Τσάντ"); namesMap.put("TF", "Γαλλικὰ Νότια Ἐδάφη"); namesMap.put("TL", "Ἀνατολικὸ Τιμόρ"); namesMap.put("TT", "Τρινιδὰδ καὶ Τομπάγκο"); namesMap.put("UA", "Οὐκρανία"); namesMap.put("UG", "Οὐγκάντα"); namesMap.put("UM", "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν"); namesMap.put("US", "Ἡνωμένες Πολιτεῖες"); namesMap.put("UY", "Οὐρουγουάη"); namesMap.put("UZ", "Οὐζμπεκιστάν"); namesMap.put("VA", "Ἁγία Ἕδρα (Βατικανό)"); namesMap.put("VC", "Ἅγιος Βικέντιος καὶ Γρεναδίνες"); namesMap.put("VG", "Βρετανικὲς Παρθένοι Νῆσοι"); namesMap.put("VI", "Ἀμερικανικὲς Παρθένοι Νῆσοι"); namesMap.put("WF", "Νῆσοι Οὐάλλις καὶ Φουτουνά"); namesMap.put("YE", "Ὑεμένη"); namesMap.put("ZA", "Νότια Ἀφρική"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ return { "AD": "Ἀνδόρα", "AE": "Ἠνωμένα Ἀραβικὰ Ἐμιράτα", "AF": "Ἀφγανιστάν", "AG": "Ἀντίγκουα καὶ Μπαρμπούντα", "AI": "Ἀνγκουίλα", "AL": "Ἀλβανία", "AM": "Ἀρμενία", "AN": "Ὁλλανδικὲς Ἀντίλλες", "AO": "Ἀνγκόλα", "AQ": "Ἀνταρκτική", "AR": "Ἀργεντινή", "AS": "Ἀμερικανικὴ Σαμόα", "AT": "Αὐστρία", "AU": "Αὐστραλία", "AW": "Ἀρούμπα", "AZ": "Ἀζερμπαϊτζάν", "BA": "Βοσνία - Ἐρζεγοβίνη", "BM": "Βερμοῦδες", "BV": "Νῆσος Μπουβέ", "CC": "Νῆσοι Κόκος (Κήλινγκ)", "CD": "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ", "CF": "Κεντροαφρικανικὴ Δημοκρατία", "CH": "Ἑλβετία", "CI": "Ἀκτὴ Ἐλεφαντοστού", "CK": "Νῆσοι Κούκ", "CV": "Πράσινο Ἀκρωτήριο", "CX": "Νῆσος Χριστουγέννων", "DO": "Δομινικανὴ Δημοκρατία", "DZ": "Ἀλγερία", "EC": "Ἰσημερινός", "EE": "Ἐσθονία", "EG": "Αἴγυπτος", "EH": "Δυτικὴ Σαχάρα", "ER": "Ἐρυθραία", "ES": "Ἱσπανία", "ET": "Αἰθιοπία", "EU": "Εὐρωπαϊκὴ ᾿Ένωση", "FM": "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς", "FO": "Νῆσοι Φερόες", "GB": "Ἡνωμένο Βασίλειο", "GF": "Γαλλικὴ Γουιάνα", "GQ": "Ἰσημερινὴ Γουινέα", "GR": "Ἑλλάδα", "GS": "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς", "HK": "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "HM": "Νῆσοι Χὲρντ καὶ Μακντόναλντ", "HN": "Ὁνδούρα", "HT": "Ἁϊτή", "HU": "Οὑγγαρία", "ID": "Ἰνδονησία", "IE": "Ἰρλανδία", "IL": "Ἰσραήλ", "IN": "Ἰνδία", "IO": "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ", "IQ": "Ἰράκ", "IR": "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ", "IS": "Ἰσλανδία", "IT": "Ἰταλία", "JO": "Ἰορδανία", "JP": "Ἰαπωνία", "KN": "Σαὶντ Κὶτς καὶ Νέβις", "KY": "Νῆσοι Κέιμαν", "LA": "Λατινικὴ Ἀμερική", "LC": "Ἁγία Λουκία", "LK": "Σρὶ Λάνκα", "LU": "Λουξεμβοῦργο", "MD": "Μολδαβία, Δημοκρατία τῆς", "MH": "Νῆσοι Μάρσαλ", "ML": "Μαλί", "MO": "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "MP": "Νῆσοι Βόρειες Μαριάνες", "NF": "Νῆσος Νόρφολκ", "NL": "Ὁλλανδία", "OM": "Ὀμάν", "PF": "Γαλλικὴ Πολυνησία", "PM": "Σαὶντ Πιὲρ καὶ Μικελόν", "PS": "Παλαιστινιακὰ Ἐδάφη", "SA": "Σαουδικὴ Ἀραβία", "SB": "Νῆσοι Σολομῶντος", "SH": "Ἁγία Ἑλένη", "SJ": "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν", "SM": "Ἅγιος Μαρίνος", "ST": "Σάο Τομὲ καὶ Πρίνσιπε", "SV": "Ἒλ Σαλβαδόρ", "SY": "Συρία, Ἀραβικὴ Δημοκρατία τῆς", "TC": "Νῆσοι Τὲρκς καὶ Κάικος", "TD": "Τσάντ", "TF": "Γαλλικὰ Νότια Ἐδάφη", "TL": "Ἀνατολικὸ Τιμόρ", "TT": "Τρινιδὰδ καὶ Τομπάγκο", "UA": "Οὐκρανία", "UG": "Οὐγκάντα", "UM": "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν", "US": "Ἡνωμένες Πολιτεῖες", "UY": "Οὐρουγουάη", "UZ": "Οὐζμπεκιστάν", "VA": "Ἁγία Ἕδρα (Βατικανό)", "VC": "Ἅγιος Βικέντιος καὶ Γρεναδίνες", "VG": "Βρετανικὲς Παρθένοι Νῆσοι", "VI": "Ἀμερικανικὲς Παρθένοι Νῆσοι", "WF": "Νῆσοι Οὐάλλις καὶ Φουτουνά", "YE": "Ὑεμένη", "ZA": "Νότια Ἀφρική" }; }-*/; }
heiko-braun/gwt-2.3.0
user/src/com/google/gwt/i18n/client/impl/cldr/LocalizedNamesImpl_el_POLYTON.java
6,608
/*-{ return { "AD": "Ἀνδόρα", "AE": "Ἠνωμένα Ἀραβικὰ Ἐμιράτα", "AF": "Ἀφγανιστάν", "AG": "Ἀντίγκουα καὶ Μπαρμπούντα", "AI": "Ἀνγκουίλα", "AL": "Ἀλβανία", "AM": "Ἀρμενία", "AN": "Ὁλλανδικὲς Ἀντίλλες", "AO": "Ἀνγκόλα", "AQ": "Ἀνταρκτική", "AR": "Ἀργεντινή", "AS": "Ἀμερικανικὴ Σαμόα", "AT": "Αὐστρία", "AU": "Αὐστραλία", "AW": "Ἀρούμπα", "AZ": "Ἀζερμπαϊτζάν", "BA": "Βοσνία - Ἐρζεγοβίνη", "BM": "Βερμοῦδες", "BV": "Νῆσος Μπουβέ", "CC": "Νῆσοι Κόκος (Κήλινγκ)", "CD": "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ", "CF": "Κεντροαφρικανικὴ Δημοκρατία", "CH": "Ἑλβετία", "CI": "Ἀκτὴ Ἐλεφαντοστού", "CK": "Νῆσοι Κούκ", "CV": "Πράσινο Ἀκρωτήριο", "CX": "Νῆσος Χριστουγέννων", "DO": "Δομινικανὴ Δημοκρατία", "DZ": "Ἀλγερία", "EC": "Ἰσημερινός", "EE": "Ἐσθονία", "EG": "Αἴγυπτος", "EH": "Δυτικὴ Σαχάρα", "ER": "Ἐρυθραία", "ES": "Ἱσπανία", "ET": "Αἰθιοπία", "EU": "Εὐρωπαϊκὴ ᾿Ένωση", "FM": "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς", "FO": "Νῆσοι Φερόες", "GB": "Ἡνωμένο Βασίλειο", "GF": "Γαλλικὴ Γουιάνα", "GQ": "Ἰσημερινὴ Γουινέα", "GR": "Ἑλλάδα", "GS": "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς", "HK": "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "HM": "Νῆσοι Χὲρντ καὶ Μακντόναλντ", "HN": "Ὁνδούρα", "HT": "Ἁϊτή", "HU": "Οὑγγαρία", "ID": "Ἰνδονησία", "IE": "Ἰρλανδία", "IL": "Ἰσραήλ", "IN": "Ἰνδία", "IO": "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ", "IQ": "Ἰράκ", "IR": "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ", "IS": "Ἰσλανδία", "IT": "Ἰταλία", "JO": "Ἰορδανία", "JP": "Ἰαπωνία", "KN": "Σαὶντ Κὶτς καὶ Νέβις", "KY": "Νῆσοι Κέιμαν", "LA": "Λατινικὴ Ἀμερική", "LC": "Ἁγία Λουκία", "LK": "Σρὶ Λάνκα", "LU": "Λουξεμβοῦργο", "MD": "Μολδαβία, Δημοκρατία τῆς", "MH": "Νῆσοι Μάρσαλ", "ML": "Μαλί", "MO": "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας", "MP": "Νῆσοι Βόρειες Μαριάνες", "NF": "Νῆσος Νόρφολκ", "NL": "Ὁλλανδία", "OM": "Ὀμάν", "PF": "Γαλλικὴ Πολυνησία", "PM": "Σαὶντ Πιὲρ καὶ Μικελόν", "PS": "Παλαιστινιακὰ Ἐδάφη", "SA": "Σαουδικὴ Ἀραβία", "SB": "Νῆσοι Σολομῶντος", "SH": "Ἁγία Ἑλένη", "SJ": "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν", "SM": "Ἅγιος Μαρίνος", "ST": "Σάο Τομὲ καὶ Πρίνσιπε", "SV": "Ἒλ Σαλβαδόρ", "SY": "Συρία, Ἀραβικὴ Δημοκρατία τῆς", "TC": "Νῆσοι Τὲρκς καὶ Κάικος", "TD": "Τσάντ", "TF": "Γαλλικὰ Νότια Ἐδάφη", "TL": "Ἀνατολικὸ Τιμόρ", "TT": "Τρινιδὰδ καὶ Τομπάγκο", "UA": "Οὐκρανία", "UG": "Οὐγκάντα", "UM": "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν", "US": "Ἡνωμένες Πολιτεῖες", "UY": "Οὐρουγουάη", "UZ": "Οὐζμπεκιστάν", "VA": "Ἁγία Ἕδρα (Βατικανό)", "VC": "Ἅγιος Βικέντιος καὶ Γρεναδίνες", "VG": "Βρετανικὲς Παρθένοι Νῆσοι", "VI": "Ἀμερικανικὲς Παρθένοι Νῆσοι", "WF": "Νῆσοι Οὐάλλις καὶ Φουτουνά", "YE": "Ὑεμένη", "ZA": "Νότια Ἀφρική" }; }-*/
block_comment
el
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA /** * Localized names for the "el_POLYTON" locale. */ public class LocalizedNamesImpl_el_POLYTON extends LocalizedNamesImpl_el { @Override public String[] loadSortedRegionCodes() { return new String[] { "VA", "SH", "LC", "BL", "VC", "SM", "MF", "AZ", "EG", "ET", "HT", "CI", "AL", "DZ", "VI", "AS", "TL", "AO", "AI", "AD", "AQ", "AG", "UM", "AR", "AM", "AW", "AU", "AT", "AF", "VU", "BE", "VE", "BM", "VN", "BO", "KP", "BA", "BG", "BR", "IO", "VG", "FR", "FX", "TF", "GF", "PF", "DE", "GE", "GI", "GM", "GA", "GH", "GG", "GU", "GP", "GT", "GY", "GN", "GW", "GD", "GL", "DK", "DO", "EH", "CH", "GR", "SV", "ER", "EE", "EU", "ZM", "ZW", "SZ", "AE", "US", "GB", "EA", "JP", "IN", "ID", "JO", "IQ", "IR", "IE", "GQ", "EC", "IS", "ES", "IL", "IT", "KZ", "CM", "KH", "CA", "IC", "QA", "CF", "KE", "CN", "KG", "KI", "CO", "KM", "CD", "CG", "CR", "CU", "KW", "HR", "CY", "LA", "LS", "LV", "BY", "LB", "LR", "LY", "LT", "LI", "LU", "YT", "MG", "MO", "MY", "MW", "MV", "ML", "MT", "MA", "MQ", "MU", "MR", "ME", "MX", "MM", "FM", "MN", "MZ", "MD", "MC", "MS", "BD", "BB", "BS", "BH", "BZ", "BJ", "BW", "BF", "BI", "BT", "BN", "NA", "NR", "NZ", "NC", "NP", "AX", "MP", "KY", "CC", "CK", "MH", "WF", "SJ", "SB", "TC", "FO", "FK", "HM", "AC", "CP", "IM", "BV", "NF", "CX", "NE", "NG", "NI", "NU", "NO", "ZA", "GS", "KR", "DG", "DM", "NL", "AN", "OM", "HN", "HU", "UG", "UZ", "UA", "UY", "PK", "PS", "PW", "PA", "PG", "PY", "MK", "QO", "PE", "PN", "PL", "PT", "PR", "CV", "RE", "RW", "RO", "RU", "KN", "PM", "WS", "ST", "SA", "SN", "RS", "CS", "SC", "SG", "SL", "SK", "SI", "SO", "SD", "SE", "SR", "LK", "SY", "TW", "TH", "TZ", "TJ", "JM", "DJ", "TG", "TK", "TO", "TV", "TR", "TM", "TT", "TA", "TD", "CZ", "TN", "YE", "JE", "PH", "FI", "FJ", "CL", "HK", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("AD", "Ἀνδόρα"); namesMap.put("AE", "Ἠνωμένα Ἀραβικὰ Ἐμιράτα"); namesMap.put("AF", "Ἀφγανιστάν"); namesMap.put("AG", "Ἀντίγκουα καὶ Μπαρμπούντα"); namesMap.put("AI", "Ἀνγκουίλα"); namesMap.put("AL", "Ἀλβανία"); namesMap.put("AM", "Ἀρμενία"); namesMap.put("AN", "Ὁλλανδικὲς Ἀντίλλες"); namesMap.put("AO", "Ἀνγκόλα"); namesMap.put("AQ", "Ἀνταρκτική"); namesMap.put("AR", "Ἀργεντινή"); namesMap.put("AS", "Ἀμερικανικὴ Σαμόα"); namesMap.put("AT", "Αὐστρία"); namesMap.put("AU", "Αὐστραλία"); namesMap.put("AW", "Ἀρούμπα"); namesMap.put("AZ", "Ἀζερμπαϊτζάν"); namesMap.put("BA", "Βοσνία - Ἐρζεγοβίνη"); namesMap.put("BM", "Βερμοῦδες"); namesMap.put("BV", "Νῆσος Μπουβέ"); namesMap.put("CC", "Νῆσοι Κόκος (Κήλινγκ)"); namesMap.put("CD", "Κονγκό, Λαϊκὴ Δημοκρατία τοῦ"); namesMap.put("CF", "Κεντροαφρικανικὴ Δημοκρατία"); namesMap.put("CH", "Ἑλβετία"); namesMap.put("CI", "Ἀκτὴ Ἐλεφαντοστού"); namesMap.put("CK", "Νῆσοι Κούκ"); namesMap.put("CV", "Πράσινο Ἀκρωτήριο"); namesMap.put("CX", "Νῆσος Χριστουγέννων"); namesMap.put("DO", "Δομινικανὴ Δημοκρατία"); namesMap.put("DZ", "Ἀλγερία"); namesMap.put("EC", "Ἰσημερινός"); namesMap.put("EE", "Ἐσθονία"); namesMap.put("EG", "Αἴγυπτος"); namesMap.put("EH", "Δυτικὴ Σαχάρα"); namesMap.put("ER", "Ἐρυθραία"); namesMap.put("ES", "Ἱσπανία"); namesMap.put("ET", "Αἰθιοπία"); namesMap.put("EU", "Εὐρωπαϊκὴ ᾿Ένωση"); namesMap.put("FM", "Μικρονησία, Ὁμόσπονδες Πολιτεῖες τῆς"); namesMap.put("FO", "Νῆσοι Φερόες"); namesMap.put("GB", "Ἡνωμένο Βασίλειο"); namesMap.put("GF", "Γαλλικὴ Γουιάνα"); namesMap.put("GQ", "Ἰσημερινὴ Γουινέα"); namesMap.put("GR", "Ἑλλάδα"); namesMap.put("GS", "Νότια Γεωργία καὶ Νότιες Νήσοι Σάντουιτς"); namesMap.put("HK", "Χὸνγκ Κόνγκ, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("HM", "Νῆσοι Χὲρντ καὶ Μακντόναλντ"); namesMap.put("HN", "Ὁνδούρα"); namesMap.put("HT", "Ἁϊτή"); namesMap.put("HU", "Οὑγγαρία"); namesMap.put("ID", "Ἰνδονησία"); namesMap.put("IE", "Ἰρλανδία"); namesMap.put("IL", "Ἰσραήλ"); namesMap.put("IN", "Ἰνδία"); namesMap.put("IO", "Βρετανικὰ Ἐδάφη Ἰνδικοῦ Ὠκεανοῦ"); namesMap.put("IQ", "Ἰράκ"); namesMap.put("IR", "Ἰράν, Ἰσλαμικὴ Δημοκρατία τοῦ"); namesMap.put("IS", "Ἰσλανδία"); namesMap.put("IT", "Ἰταλία"); namesMap.put("JO", "Ἰορδανία"); namesMap.put("JP", "Ἰαπωνία"); namesMap.put("KN", "Σαὶντ Κὶτς καὶ Νέβις"); namesMap.put("KY", "Νῆσοι Κέιμαν"); namesMap.put("LA", "Λατινικὴ Ἀμερική"); namesMap.put("LC", "Ἁγία Λουκία"); namesMap.put("LK", "Σρὶ Λάνκα"); namesMap.put("LU", "Λουξεμβοῦργο"); namesMap.put("MD", "Μολδαβία, Δημοκρατία τῆς"); namesMap.put("MH", "Νῆσοι Μάρσαλ"); namesMap.put("ML", "Μαλί"); namesMap.put("MO", "Μακάο, Εἰδικὴ Διοικητικὴ Περιφέρεια τῆς Κίνας"); namesMap.put("MP", "Νῆσοι Βόρειες Μαριάνες"); namesMap.put("NF", "Νῆσος Νόρφολκ"); namesMap.put("NL", "Ὁλλανδία"); namesMap.put("OM", "Ὀμάν"); namesMap.put("PF", "Γαλλικὴ Πολυνησία"); namesMap.put("PM", "Σαὶντ Πιὲρ καὶ Μικελόν"); namesMap.put("PS", "Παλαιστινιακὰ Ἐδάφη"); namesMap.put("SA", "Σαουδικὴ Ἀραβία"); namesMap.put("SB", "Νῆσοι Σολομῶντος"); namesMap.put("SH", "Ἁγία Ἑλένη"); namesMap.put("SJ", "Νῆσοι Σβάλμπαρ καὶ Γιὰν Μαγιέν"); namesMap.put("SM", "Ἅγιος Μαρίνος"); namesMap.put("ST", "Σάο Τομὲ καὶ Πρίνσιπε"); namesMap.put("SV", "Ἒλ Σαλβαδόρ"); namesMap.put("SY", "Συρία, Ἀραβικὴ Δημοκρατία τῆς"); namesMap.put("TC", "Νῆσοι Τὲρκς καὶ Κάικος"); namesMap.put("TD", "Τσάντ"); namesMap.put("TF", "Γαλλικὰ Νότια Ἐδάφη"); namesMap.put("TL", "Ἀνατολικὸ Τιμόρ"); namesMap.put("TT", "Τρινιδὰδ καὶ Τομπάγκο"); namesMap.put("UA", "Οὐκρανία"); namesMap.put("UG", "Οὐγκάντα"); namesMap.put("UM", "Ἀπομακρυσμένες Νησίδες τῶν Ἡνωμένων Πολιτειῶν"); namesMap.put("US", "Ἡνωμένες Πολιτεῖες"); namesMap.put("UY", "Οὐρουγουάη"); namesMap.put("UZ", "Οὐζμπεκιστάν"); namesMap.put("VA", "Ἁγία Ἕδρα (Βατικανό)"); namesMap.put("VC", "Ἅγιος Βικέντιος καὶ Γρεναδίνες"); namesMap.put("VG", "Βρετανικὲς Παρθένοι Νῆσοι"); namesMap.put("VI", "Ἀμερικανικὲς Παρθένοι Νῆσοι"); namesMap.put("WF", "Νῆσοι Οὐάλλις καὶ Φουτουνά"); namesMap.put("YE", "Ὑεμένη"); namesMap.put("ZA", "Νότια Ἀφρική"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ <SUF>*/; }
1770_17
import // <editor-fold defaultstate="collapsed"> java.awt.Color; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.plaf.ColorUIResource; public class Main { public static final String MAIN_DIR_PATH = "data"; public static final String DIGESTS_FILE_PATH = MAIN_DIR_PATH + "/digests.data"; public static final String APP_PUBLIC_KEY_FILE_PATH = MAIN_DIR_PATH + "/public.key"; public static final String USER_FILES_DIR_PATH = MAIN_DIR_PATH + "/user_files"; //Κωδικες Σφαλματων public static final int USERNAME_EXISTS = 1; public static final int CORRUPTED_KEY_FILE = 2; public static final int CORRUPTED_DIGESTS_FILE = 3; public static final int ENCRYPTION_ERROR = 4; public static final int ILLEGAL_USERNAME = 5; public static final int ILLEGAL_PASSWORD = 6; public static final int UNKNOWN_ERROR = 7; public static final int USER_NOT_EXISTS = 1; public static final int WRONG_PASSWORD = 2; public static final int CORRUPTED_DATA_FILES = 1; public static final int USER_FILES_INFRIGMENT = 10; private static final String usernameREGEX = "^\\w(?:\\w*(?:[.-]\\w+)?)*(?<=^.{4,22})$"; /** * Στην αρχη χρησιμοποιησα regex kai για το password αλλα τελικα το κανα σε * μεθοδο για καλυτερη ασφαλεια αλλαξα το τροπο υλοποιησης και τωρα δεν * αποθηκευεται ποτε ο κωδικος μεσα σε String (δηλαδη στη μνημη)* */ // private static final String passwordREGEX // = "^(?=.*\\d)(?=.*[\\[\\]\\^\\$\\.\\|\\?\\*\\+\\(\\)\\\\~`\\!@#%&\\-_+={}'\"\"<>:;, ])(?=.*[a-z])(?=.*[A-Z]).{8,32}$"; public static final String separator = ":=:"; private static UserInfo currentUserInfo; private static ArrayList<TransactionEntry> currentUserEntries = new ArrayList<>(); //Μεθοδος για την εγγραφη των νεων χρηστων public static int register(String name, String username, char[] password) { if (!username.matches(usernameREGEX)) { //Ελγχος για σωστη μορφη username return ILLEGAL_USERNAME; } if (!passwordStrengthCheck(password)) { //Ελεγχος και για σωστη μορφη κωδικου return ILLEGAL_PASSWORD; } try { if (getUserInfo(username) == null) { //Ελεγχος αν υπαρχει το username //Δημιουργια salts byte[] salt = SHA256.generateSalt(); String saltEncoded = Base64.getEncoder().encodeToString(salt); //Δημιουργια συνοψης με salts byte[] hash = SHA256.HashWithSalt(toBytes(password), salt); //Ασσυμετρη κρυπτογραφηση συνοψης και μετατροπη σε Base64 String για αποθηκευση σε αρχειο String encryptedHashEncoded = Base64.getEncoder().encodeToString( RSA2048.encrypt(hash, RSA2048.constructPublicKey(AppKeyPair.getPublic()))); //Δημιουργια τυχαιου συμμετρικου κλειδιου για τον χρηστη και μετατροπη σε Base64 String για αποθηκευση σε αρχειο String randomKeyEncoded = Base64.getEncoder().encodeToString(AES256.getRandomKey().getEncoded()); //Αποθηκευση στο αρχειο με τις συνοψεις appendContentToFile(name + separator + username + separator + saltEncoded + separator + encryptedHashEncoded + separator + randomKeyEncoded + "\n", new File(DIGESTS_FILE_PATH)); return 0; } else { return USERNAME_EXISTS; } } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (InvalidKeyException ex) { ex.printStackTrace(); return CORRUPTED_KEY_FILE; } catch (IllegalBlockSizeException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (BadPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (IOException ex) { ex.printStackTrace(); return CORRUPTED_DIGESTS_FILE; } catch (InvalidKeySpecException ex) { ex.printStackTrace(); return CORRUPTED_KEY_FILE; } catch (Exception ex) { ex.printStackTrace(); return UNKNOWN_ERROR; } } //Μεθοδος για Συνδεση Χρηστη public static int login(String username, char[] password) { try { currentUserInfo = getUserInfo(username); if (!(currentUserInfo == null)) { //Ελεγχος αν υπαρχει το username //Παιρνω τα αποθηκευμενα salt και τη κρυπτογραφημενη συνοψη String encodedSalt = currentUserInfo.getSaltEncoded(); String digestEncoded = currentUserInfo.getEncryptedDigestEncoded(); //Μετατροπη και παλι σε byte array byte[] salt = Base64.getDecoder().decode(encodedSalt); byte[] hash = SHA256.HashWithSalt(toBytes(password), salt); //Ασυμμετρη αποκωδικοποιηση συνοψης byte[] decryptedHash = RSA2048.decrypt( Base64.getDecoder().decode(digestEncoded), RSA2048.constructPrivateKey(AppKeyPair.getPrivate())); //Συγκριση των συνοψεων για επιβεβαιωση if (Arrays.equals(hash, decryptedHash)) { return 0; } else { return WRONG_PASSWORD; } } else { return USER_NOT_EXISTS; } } catch (IOException ex) { ex.printStackTrace(); return CORRUPTED_DIGESTS_FILE; } catch (InvalidKeyException ex) { ex.printStackTrace(); return CORRUPTED_DIGESTS_FILE; } catch (IllegalBlockSizeException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (BadPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (InvalidKeySpecException ex) { ex.printStackTrace(); return CORRUPTED_DIGESTS_FILE; } catch (Exception ex) { ex.printStackTrace(); return UNKNOWN_ERROR; } } //Μεθοδος για αποθηκευση νεας λογιστικης εγγραφης στο καταλληλο αρχειο public static int saveNewEntry(TransactionEntry entry) { String user_dir = USER_FILES_DIR_PATH + "/" + currentUserInfo.getUname(); File udir = new File(user_dir); if (!(udir.exists() && udir.isDirectory())) { udir.mkdir(); } try { //Συμμετρικη κωδικοποιηση με το κλειδι του χρηστη String encryptedEntry = AES256.Encrypt(entry.getId() + separator + entry.getDate() + separator + entry.getAmmount() + separator + entry.getDescription(), AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded()))) + "\n"; //Αποθηκευση στο καταλληλο αρχειο (αναλογα το ειδος της συνναλαγης) if (entry.getType() == TransactionEntry.INCOME) { File user_income_file = new File(udir.getPath() + "/" + "income.data"); appendContentToFile(encryptedEntry, user_income_file); } else { File user_outcome_file = new File(udir.getPath() + "/" + "outcome.data"); appendContentToFile(encryptedEntry, user_outcome_file); } //Προσθηκη στο ArrayList με τις αλλες εγγραφες currentUserEntries.add(entry); return 0; } catch (IOException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (InvalidKeyException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (IllegalBlockSizeException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (BadPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (Exception ex) { ex.printStackTrace(); return UNKNOWN_ERROR; } } //Μεθοδος για την αντικατασταση μιας εγγραφης μετα απο αλλαγη των στοιχειων της και αποθηκευση public static int replaceEntryAndSave(TransactionEntry entry) { //Αντικατασταση της εγγραφης for (int i = 0; i < currentUserEntries.size(); i++) { if (currentUserEntries.get(i).getId().equals(entry.getId())) { currentUserEntries.remove(i); currentUserEntries.add(i, entry); } } String user_dir = USER_FILES_DIR_PATH + "/" + currentUserInfo.getUname(); File user_income_file = new File(user_dir + "/" + "income.data"); File user_outcome_file = new File(user_dir + "/" + "outcome.data"); //Αποθηκευση παλι των εγγραφων στο αρχειο try { FileWriter fw; if (entry.getType() == TransactionEntry.INCOME) { fw = new FileWriter(user_income_file); } else { fw = new FileWriter(user_outcome_file); } BufferedWriter buff = new BufferedWriter(fw); for (TransactionEntry e : currentUserEntries) { if (e.getType() == entry.getType()) { String encryptedEntry = AES256.Encrypt(e.getId() + separator + e.getDate() + separator + e.getAmmount() + separator + e.getDescription(), AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded()))) + "\n"; buff.write(encryptedEntry); } } buff.close(); fw.close(); return 0; } catch (IOException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (InvalidKeyException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (IllegalBlockSizeException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (BadPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (Exception ex) { ex.printStackTrace(); return UNKNOWN_ERROR; } } //Μεθοδος για τη φορτωση των εγγραφων του χρηστη απο τα αρχεια (γινεται στην αρχη) public static int getCurrentUserEntries() { String user_dir = USER_FILES_DIR_PATH + "/" + currentUserInfo.getUname(); File user_income_file = new File(user_dir + "/" + "income.data"); File user_outcome_file = new File(user_dir + "/" + "outcome.data"); try { BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(user_income_file))); String encryptedEntry; //Καθε γραμμη ειναι μια εγγραφη, αποκωδικοποιειται και επειτα τη σπαω σε κομματια (με το separator που ορισα) //παιρνω τα στοιχεια της, τη δημιουργω και τη βαζω στη λιστα με τις εγγραφες του χρηστη //Αυτο γινεται κια στα δυο αρχεια του χρηστη while ((encryptedEntry = br.readLine()) != null) { String decryptedEntryStr = AES256.Decrypt(encryptedEntry, AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded()))); String[] entryDetails = decryptedEntryStr.split(separator); TransactionEntry entry = new TransactionEntry(entryDetails[0], entryDetails[1], entryDetails[2], entryDetails[3], TransactionEntry.INCOME); currentUserEntries.add(entry); } br.close(); br = new BufferedReader(new InputStreamReader( new FileInputStream(user_outcome_file))); while ((encryptedEntry = br.readLine()) != null) { String decryptedEntryStr = AES256.Decrypt(encryptedEntry, AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded()))); String[] entryDetails = decryptedEntryStr.split(separator); TransactionEntry entry = new TransactionEntry(entryDetails[0], entryDetails[1], entryDetails[2], entryDetails[3], TransactionEntry.OUTCOME); currentUserEntries.add(entry); } return 0; } catch (FileNotFoundException ex) { return 0; } catch (IOException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (InvalidKeyException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (InvalidAlgorithmParameterException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (IllegalBlockSizeException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (BadPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (Exception ex) { ex.printStackTrace(); return UNKNOWN_ERROR; } } //Μεθοδος για Επιστροφη λιστας συνναλαγων οι οποιες εγιναν σε μια συγκεκριμενη ημερομηνια public static ArrayList<TransactionEntry> getEntriesWithSelectedDate(String selectedDate) { ArrayList<TransactionEntry> entries = new ArrayList<>(); for (TransactionEntry e : currentUserEntries) { if (e.getDate().equals(selectedDate)) { entries.add(e); } } return entries; } //Μεθοδος για επιστροφη συνναλαγης βαση του κωδικου της public static TransactionEntry getEntryByID(String id) { for (TransactionEntry e : currentUserEntries) { if (e.getId().equals(id)) { return e; } } return null; } //Μεθοδος για επιστροφη λιστας με τους μηνες οι οποιοι εχουν συνναλαγες (η δευτερη λιστα ειναι για //να κρατασει εναν αριθμο για τον μηνα και ενα για τη χρονια του μηνα. Και επειδη ειναι και αυτο //ειναι λιστα μπορω να χρησιμοποιησω την μεθοδο contains που με γλυτωσε απο κοπο public static ArrayList<ArrayList<Integer>> getMonthsWithEntries() { ArrayList<ArrayList<Integer>> months = new ArrayList<>(); java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(GUI.dateFormat); for (TransactionEntry entry : currentUserEntries) { try { java.util.Date d = formatter.parse(entry.getDate()); ArrayList<Integer> temp = new ArrayList<>(Arrays.asList( Integer.parseInt(new java.text.SimpleDateFormat("MM").format(d)) - 1, Integer.parseInt(new java.text.SimpleDateFormat("yyyy").format(d)))); if (!months.contains(temp)) { months.add(temp); } } catch (ParseException ex) { ex.printStackTrace(); } } return months; } //Μεθοδοσ γι την επιστροφη λιστας με εγγραφες που εχουν γινει σε ενα συγκεκριμενο μηνα public static ArrayList<TransactionEntry> getEntriesWithSelectedMonth(String selectedMonth) { ArrayList<TransactionEntry> entries = new ArrayList<>(); for (TransactionEntry e : currentUserEntries) { java.util.Date entryDate = null; try { entryDate = new java.text.SimpleDateFormat(GUI.dateFormat).parse(e.getDate()); } catch (ParseException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } if (new java.text.SimpleDateFormat(GUI.monthYearFormat).format(entryDate) .equals(selectedMonth)) { entries.add(e); } } return entries; } //Η main στην αρχη αλλαζει την εμφανιση των γραφικων της java. Προσοχη χρειαζεται να προσθεσετε τη βιβλιοθηκη που υπαρχει //στον φακελο lib του project αλλιως τα γραφικα δε θα φαινονται καλα //Επισης φτιαχνει τους απαραιτητους φακελους αν δεν υπαρχουν και καλει τα γραφικα public static void main(String[] args) { SwingUtilities.invokeLater(() -> { try { UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel"); UIManager.put("ComboBox.selectionBackground", new ColorUIResource(new Color(80, 80, 80))); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { System.out.println("JTatto not found."); // System.exit(1); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } } File mdir = new File(MAIN_DIR_PATH); if (!(mdir.exists() && mdir.isDirectory())) { mdir.mkdir(); } File kdir = new File(USER_FILES_DIR_PATH); if (!(kdir.exists() && kdir.isDirectory())) { kdir.mkdir(); } File appkeyfile = new File(APP_PUBLIC_KEY_FILE_PATH); if (!appkeyfile.exists()) { try (PrintStream out = new PrintStream(new FileOutputStream(appkeyfile))) { out.print(AppKeyPair.getPublic()); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } File digestsfile = new File(DIGESTS_FILE_PATH); if (!digestsfile.exists()) { try { digestsfile.createNewFile(); } catch (IOException ex) { ex.printStackTrace(); } } new GUI(); }); } //Μεθοδος για τον ελεγχο την ασφαλειας του κωδικου (να εχει ενα πεζο ενα κεφαλαιο εναν ειδικο χαρακτηρα //και ενα ψηφιο τουλαχιστον και να ειναι απο 8 εως 32 χαρακτρηρες) private static boolean passwordStrengthCheck(char[] pass) { boolean special = false, uppercase = false, lowercase = false, digit = false, whitespace = false, illegal = false, length = pass.length > 8 && pass.length < 32; for (int i = 0; i < pass.length; i++) { if (Character.isUpperCase(pass[i])) { uppercase = true; } else if (Character.isLowerCase(pass[i])) { lowercase = true; } else if (Character.isDigit(pass[i])) { digit = true; } else if (Character.isWhitespace(pass[i])) { whitespace = true; } else if (!Character.isAlphabetic(i)) { special = true; } else { illegal = true; } } return (special && uppercase && lowercase && length && !whitespace && !illegal); } //Βρισκει τα στοιχεια ενος χρηστη που εχουν αποθηκευτει στο αρχειο των συνοψεων private static UserInfo getUserInfo(String username) throws IOException { UserInfo user = null; FileInputStream fstream = new FileInputStream(DIGESTS_FILE_PATH); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String line; while ((line = br.readLine()) != null) { String[] separated = line.split(separator); if (username.equals(separated[2])) { user = new UserInfo(separated[0], separated[1], separated[2], separated[3], separated[4], separated[5]); } } br.close(); return user; } public static UserInfo getCurrentUserInfo() { return currentUserInfo; } private static void appendContentToFile(String content, File file) throws IOException { if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file, true); BufferedWriter buff = new BufferedWriter(fw); buff.write(content); buff.close(); fw.close(); } //μετατροπη πινακα χαρακτηρων σε πινακα byte private static byte[] toBytes(char[] chars) { CharBuffer charBuffer = CharBuffer.wrap(chars); ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer); byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit()); Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data return bytes; } }
icsd12015/projects_security
Cash Flow X/Project/src/Main.java
6,638
//Συγκριση των συνοψεων για επιβεβαιωση
line_comment
el
import // <editor-fold defaultstate="collapsed"> java.awt.Color; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.plaf.ColorUIResource; public class Main { public static final String MAIN_DIR_PATH = "data"; public static final String DIGESTS_FILE_PATH = MAIN_DIR_PATH + "/digests.data"; public static final String APP_PUBLIC_KEY_FILE_PATH = MAIN_DIR_PATH + "/public.key"; public static final String USER_FILES_DIR_PATH = MAIN_DIR_PATH + "/user_files"; //Κωδικες Σφαλματων public static final int USERNAME_EXISTS = 1; public static final int CORRUPTED_KEY_FILE = 2; public static final int CORRUPTED_DIGESTS_FILE = 3; public static final int ENCRYPTION_ERROR = 4; public static final int ILLEGAL_USERNAME = 5; public static final int ILLEGAL_PASSWORD = 6; public static final int UNKNOWN_ERROR = 7; public static final int USER_NOT_EXISTS = 1; public static final int WRONG_PASSWORD = 2; public static final int CORRUPTED_DATA_FILES = 1; public static final int USER_FILES_INFRIGMENT = 10; private static final String usernameREGEX = "^\\w(?:\\w*(?:[.-]\\w+)?)*(?<=^.{4,22})$"; /** * Στην αρχη χρησιμοποιησα regex kai για το password αλλα τελικα το κανα σε * μεθοδο για καλυτερη ασφαλεια αλλαξα το τροπο υλοποιησης και τωρα δεν * αποθηκευεται ποτε ο κωδικος μεσα σε String (δηλαδη στη μνημη)* */ // private static final String passwordREGEX // = "^(?=.*\\d)(?=.*[\\[\\]\\^\\$\\.\\|\\?\\*\\+\\(\\)\\\\~`\\!@#%&\\-_+={}'\"\"<>:;, ])(?=.*[a-z])(?=.*[A-Z]).{8,32}$"; public static final String separator = ":=:"; private static UserInfo currentUserInfo; private static ArrayList<TransactionEntry> currentUserEntries = new ArrayList<>(); //Μεθοδος για την εγγραφη των νεων χρηστων public static int register(String name, String username, char[] password) { if (!username.matches(usernameREGEX)) { //Ελγχος για σωστη μορφη username return ILLEGAL_USERNAME; } if (!passwordStrengthCheck(password)) { //Ελεγχος και για σωστη μορφη κωδικου return ILLEGAL_PASSWORD; } try { if (getUserInfo(username) == null) { //Ελεγχος αν υπαρχει το username //Δημιουργια salts byte[] salt = SHA256.generateSalt(); String saltEncoded = Base64.getEncoder().encodeToString(salt); //Δημιουργια συνοψης με salts byte[] hash = SHA256.HashWithSalt(toBytes(password), salt); //Ασσυμετρη κρυπτογραφηση συνοψης και μετατροπη σε Base64 String για αποθηκευση σε αρχειο String encryptedHashEncoded = Base64.getEncoder().encodeToString( RSA2048.encrypt(hash, RSA2048.constructPublicKey(AppKeyPair.getPublic()))); //Δημιουργια τυχαιου συμμετρικου κλειδιου για τον χρηστη και μετατροπη σε Base64 String για αποθηκευση σε αρχειο String randomKeyEncoded = Base64.getEncoder().encodeToString(AES256.getRandomKey().getEncoded()); //Αποθηκευση στο αρχειο με τις συνοψεις appendContentToFile(name + separator + username + separator + saltEncoded + separator + encryptedHashEncoded + separator + randomKeyEncoded + "\n", new File(DIGESTS_FILE_PATH)); return 0; } else { return USERNAME_EXISTS; } } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (InvalidKeyException ex) { ex.printStackTrace(); return CORRUPTED_KEY_FILE; } catch (IllegalBlockSizeException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (BadPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (IOException ex) { ex.printStackTrace(); return CORRUPTED_DIGESTS_FILE; } catch (InvalidKeySpecException ex) { ex.printStackTrace(); return CORRUPTED_KEY_FILE; } catch (Exception ex) { ex.printStackTrace(); return UNKNOWN_ERROR; } } //Μεθοδος για Συνδεση Χρηστη public static int login(String username, char[] password) { try { currentUserInfo = getUserInfo(username); if (!(currentUserInfo == null)) { //Ελεγχος αν υπαρχει το username //Παιρνω τα αποθηκευμενα salt και τη κρυπτογραφημενη συνοψη String encodedSalt = currentUserInfo.getSaltEncoded(); String digestEncoded = currentUserInfo.getEncryptedDigestEncoded(); //Μετατροπη και παλι σε byte array byte[] salt = Base64.getDecoder().decode(encodedSalt); byte[] hash = SHA256.HashWithSalt(toBytes(password), salt); //Ασυμμετρη αποκωδικοποιηση συνοψης byte[] decryptedHash = RSA2048.decrypt( Base64.getDecoder().decode(digestEncoded), RSA2048.constructPrivateKey(AppKeyPair.getPrivate())); //Συγκριση των<SUF> if (Arrays.equals(hash, decryptedHash)) { return 0; } else { return WRONG_PASSWORD; } } else { return USER_NOT_EXISTS; } } catch (IOException ex) { ex.printStackTrace(); return CORRUPTED_DIGESTS_FILE; } catch (InvalidKeyException ex) { ex.printStackTrace(); return CORRUPTED_DIGESTS_FILE; } catch (IllegalBlockSizeException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (BadPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (InvalidKeySpecException ex) { ex.printStackTrace(); return CORRUPTED_DIGESTS_FILE; } catch (Exception ex) { ex.printStackTrace(); return UNKNOWN_ERROR; } } //Μεθοδος για αποθηκευση νεας λογιστικης εγγραφης στο καταλληλο αρχειο public static int saveNewEntry(TransactionEntry entry) { String user_dir = USER_FILES_DIR_PATH + "/" + currentUserInfo.getUname(); File udir = new File(user_dir); if (!(udir.exists() && udir.isDirectory())) { udir.mkdir(); } try { //Συμμετρικη κωδικοποιηση με το κλειδι του χρηστη String encryptedEntry = AES256.Encrypt(entry.getId() + separator + entry.getDate() + separator + entry.getAmmount() + separator + entry.getDescription(), AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded()))) + "\n"; //Αποθηκευση στο καταλληλο αρχειο (αναλογα το ειδος της συνναλαγης) if (entry.getType() == TransactionEntry.INCOME) { File user_income_file = new File(udir.getPath() + "/" + "income.data"); appendContentToFile(encryptedEntry, user_income_file); } else { File user_outcome_file = new File(udir.getPath() + "/" + "outcome.data"); appendContentToFile(encryptedEntry, user_outcome_file); } //Προσθηκη στο ArrayList με τις αλλες εγγραφες currentUserEntries.add(entry); return 0; } catch (IOException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (InvalidKeyException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (IllegalBlockSizeException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (BadPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (Exception ex) { ex.printStackTrace(); return UNKNOWN_ERROR; } } //Μεθοδος για την αντικατασταση μιας εγγραφης μετα απο αλλαγη των στοιχειων της και αποθηκευση public static int replaceEntryAndSave(TransactionEntry entry) { //Αντικατασταση της εγγραφης for (int i = 0; i < currentUserEntries.size(); i++) { if (currentUserEntries.get(i).getId().equals(entry.getId())) { currentUserEntries.remove(i); currentUserEntries.add(i, entry); } } String user_dir = USER_FILES_DIR_PATH + "/" + currentUserInfo.getUname(); File user_income_file = new File(user_dir + "/" + "income.data"); File user_outcome_file = new File(user_dir + "/" + "outcome.data"); //Αποθηκευση παλι των εγγραφων στο αρχειο try { FileWriter fw; if (entry.getType() == TransactionEntry.INCOME) { fw = new FileWriter(user_income_file); } else { fw = new FileWriter(user_outcome_file); } BufferedWriter buff = new BufferedWriter(fw); for (TransactionEntry e : currentUserEntries) { if (e.getType() == entry.getType()) { String encryptedEntry = AES256.Encrypt(e.getId() + separator + e.getDate() + separator + e.getAmmount() + separator + e.getDescription(), AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded()))) + "\n"; buff.write(encryptedEntry); } } buff.close(); fw.close(); return 0; } catch (IOException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (InvalidKeyException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (IllegalBlockSizeException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (BadPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (Exception ex) { ex.printStackTrace(); return UNKNOWN_ERROR; } } //Μεθοδος για τη φορτωση των εγγραφων του χρηστη απο τα αρχεια (γινεται στην αρχη) public static int getCurrentUserEntries() { String user_dir = USER_FILES_DIR_PATH + "/" + currentUserInfo.getUname(); File user_income_file = new File(user_dir + "/" + "income.data"); File user_outcome_file = new File(user_dir + "/" + "outcome.data"); try { BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(user_income_file))); String encryptedEntry; //Καθε γραμμη ειναι μια εγγραφη, αποκωδικοποιειται και επειτα τη σπαω σε κομματια (με το separator που ορισα) //παιρνω τα στοιχεια της, τη δημιουργω και τη βαζω στη λιστα με τις εγγραφες του χρηστη //Αυτο γινεται κια στα δυο αρχεια του χρηστη while ((encryptedEntry = br.readLine()) != null) { String decryptedEntryStr = AES256.Decrypt(encryptedEntry, AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded()))); String[] entryDetails = decryptedEntryStr.split(separator); TransactionEntry entry = new TransactionEntry(entryDetails[0], entryDetails[1], entryDetails[2], entryDetails[3], TransactionEntry.INCOME); currentUserEntries.add(entry); } br.close(); br = new BufferedReader(new InputStreamReader( new FileInputStream(user_outcome_file))); while ((encryptedEntry = br.readLine()) != null) { String decryptedEntryStr = AES256.Decrypt(encryptedEntry, AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded()))); String[] entryDetails = decryptedEntryStr.split(separator); TransactionEntry entry = new TransactionEntry(entryDetails[0], entryDetails[1], entryDetails[2], entryDetails[3], TransactionEntry.OUTCOME); currentUserEntries.add(entry); } return 0; } catch (FileNotFoundException ex) { return 0; } catch (IOException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (NoSuchPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (InvalidKeyException ex) { ex.printStackTrace(); return CORRUPTED_DATA_FILES; } catch (InvalidAlgorithmParameterException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (IllegalBlockSizeException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (BadPaddingException ex) { ex.printStackTrace(); return ENCRYPTION_ERROR; } catch (Exception ex) { ex.printStackTrace(); return UNKNOWN_ERROR; } } //Μεθοδος για Επιστροφη λιστας συνναλαγων οι οποιες εγιναν σε μια συγκεκριμενη ημερομηνια public static ArrayList<TransactionEntry> getEntriesWithSelectedDate(String selectedDate) { ArrayList<TransactionEntry> entries = new ArrayList<>(); for (TransactionEntry e : currentUserEntries) { if (e.getDate().equals(selectedDate)) { entries.add(e); } } return entries; } //Μεθοδος για επιστροφη συνναλαγης βαση του κωδικου της public static TransactionEntry getEntryByID(String id) { for (TransactionEntry e : currentUserEntries) { if (e.getId().equals(id)) { return e; } } return null; } //Μεθοδος για επιστροφη λιστας με τους μηνες οι οποιοι εχουν συνναλαγες (η δευτερη λιστα ειναι για //να κρατασει εναν αριθμο για τον μηνα και ενα για τη χρονια του μηνα. Και επειδη ειναι και αυτο //ειναι λιστα μπορω να χρησιμοποιησω την μεθοδο contains που με γλυτωσε απο κοπο public static ArrayList<ArrayList<Integer>> getMonthsWithEntries() { ArrayList<ArrayList<Integer>> months = new ArrayList<>(); java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(GUI.dateFormat); for (TransactionEntry entry : currentUserEntries) { try { java.util.Date d = formatter.parse(entry.getDate()); ArrayList<Integer> temp = new ArrayList<>(Arrays.asList( Integer.parseInt(new java.text.SimpleDateFormat("MM").format(d)) - 1, Integer.parseInt(new java.text.SimpleDateFormat("yyyy").format(d)))); if (!months.contains(temp)) { months.add(temp); } } catch (ParseException ex) { ex.printStackTrace(); } } return months; } //Μεθοδοσ γι την επιστροφη λιστας με εγγραφες που εχουν γινει σε ενα συγκεκριμενο μηνα public static ArrayList<TransactionEntry> getEntriesWithSelectedMonth(String selectedMonth) { ArrayList<TransactionEntry> entries = new ArrayList<>(); for (TransactionEntry e : currentUserEntries) { java.util.Date entryDate = null; try { entryDate = new java.text.SimpleDateFormat(GUI.dateFormat).parse(e.getDate()); } catch (ParseException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } if (new java.text.SimpleDateFormat(GUI.monthYearFormat).format(entryDate) .equals(selectedMonth)) { entries.add(e); } } return entries; } //Η main στην αρχη αλλαζει την εμφανιση των γραφικων της java. Προσοχη χρειαζεται να προσθεσετε τη βιβλιοθηκη που υπαρχει //στον φακελο lib του project αλλιως τα γραφικα δε θα φαινονται καλα //Επισης φτιαχνει τους απαραιτητους φακελους αν δεν υπαρχουν και καλει τα γραφικα public static void main(String[] args) { SwingUtilities.invokeLater(() -> { try { UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel"); UIManager.put("ComboBox.selectionBackground", new ColorUIResource(new Color(80, 80, 80))); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { System.out.println("JTatto not found."); // System.exit(1); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } } File mdir = new File(MAIN_DIR_PATH); if (!(mdir.exists() && mdir.isDirectory())) { mdir.mkdir(); } File kdir = new File(USER_FILES_DIR_PATH); if (!(kdir.exists() && kdir.isDirectory())) { kdir.mkdir(); } File appkeyfile = new File(APP_PUBLIC_KEY_FILE_PATH); if (!appkeyfile.exists()) { try (PrintStream out = new PrintStream(new FileOutputStream(appkeyfile))) { out.print(AppKeyPair.getPublic()); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } File digestsfile = new File(DIGESTS_FILE_PATH); if (!digestsfile.exists()) { try { digestsfile.createNewFile(); } catch (IOException ex) { ex.printStackTrace(); } } new GUI(); }); } //Μεθοδος για τον ελεγχο την ασφαλειας του κωδικου (να εχει ενα πεζο ενα κεφαλαιο εναν ειδικο χαρακτηρα //και ενα ψηφιο τουλαχιστον και να ειναι απο 8 εως 32 χαρακτρηρες) private static boolean passwordStrengthCheck(char[] pass) { boolean special = false, uppercase = false, lowercase = false, digit = false, whitespace = false, illegal = false, length = pass.length > 8 && pass.length < 32; for (int i = 0; i < pass.length; i++) { if (Character.isUpperCase(pass[i])) { uppercase = true; } else if (Character.isLowerCase(pass[i])) { lowercase = true; } else if (Character.isDigit(pass[i])) { digit = true; } else if (Character.isWhitespace(pass[i])) { whitespace = true; } else if (!Character.isAlphabetic(i)) { special = true; } else { illegal = true; } } return (special && uppercase && lowercase && length && !whitespace && !illegal); } //Βρισκει τα στοιχεια ενος χρηστη που εχουν αποθηκευτει στο αρχειο των συνοψεων private static UserInfo getUserInfo(String username) throws IOException { UserInfo user = null; FileInputStream fstream = new FileInputStream(DIGESTS_FILE_PATH); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String line; while ((line = br.readLine()) != null) { String[] separated = line.split(separator); if (username.equals(separated[2])) { user = new UserInfo(separated[0], separated[1], separated[2], separated[3], separated[4], separated[5]); } } br.close(); return user; } public static UserInfo getCurrentUserInfo() { return currentUserInfo; } private static void appendContentToFile(String content, File file) throws IOException { if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file, true); BufferedWriter buff = new BufferedWriter(fw); buff.write(content); buff.close(); fw.close(); } //μετατροπη πινακα χαρακτηρων σε πινακα byte private static byte[] toBytes(char[] chars) { CharBuffer charBuffer = CharBuffer.wrap(chars); ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer); byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit()); Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data return bytes; } }
4139_21
package eu.apps4net; import java.io.IOException; import java.util.HashSet; import java.util.StringJoiner; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class AirSupport { /** * Σπάει τη γραμμή του CSV σε στοιχεία, αποφεύγοντας να διαχωρίζει τα στοιχεία μέσα σε εισαγωγικά * * source: 2ο θέμα, 3ης εργασία ΠΛΗ47, του 2021-2022 * * @param line string to be split */ private static String[] processLine(String line) { // Create a regular expression for proper split of each line // The regex for characters other than quote (") String otherThanQuote = " [^\"] "; // The regex for a quoted string. e.g "whatever1 whatever2" String quotedString = String.format(" \" %s* \" ", otherThanQuote); // The regex to split the line using comma (,) but taking into consideration the quoted strings // This means that is a comma is in a quoted string, it should be ignored. String regex = String.format("(?x) " + // enable comments, ignore white spaces ", " + // match a comma "(?= " + // start positive look ahead " (?: " + // start non-capturing group 1 " %s* " + // match 'otherThanQuote' zero or more times " %s " + // match 'quotedString' " )* " + // end group 1 and repeat it zero or more times " %s* " + // match 'otherThanQuote' " $ " + // match the end of the string ") ", // stop positive look ahead otherThanQuote, quotedString, otherThanQuote); String[] tokens = line.split(regex, -1); // check for the proper number of columns if (tokens.length == 10) { return tokens; } else { System.err.println("Wrong number of columns for line: " + line); return null; } } public static class TokenizerMapper extends Mapper<Object, Text, Text, LongWritable> { private final static LongWritable tweetId = new LongWritable(); private final Text word = new Text(); public void map(Object key, Text value, Context context) throws IOException, InterruptedException { Tweet tweet = null; String line = value.toString(); String tweetText = ""; // Σπάει τη γραμμή σε στοιχεία String[] tweetArray = processLine(line); // Αν το tweetArray δεν είναι null if(tweetArray != null) { // Δημιουργία αντικειμένου Tweet tweet = new Tweet(tweetArray); // Παίρνει καθαρό κείμενο από το Tweet tweetText = tweet.getClearedText(); } // Παίρνει την τρέχουσα γραμμή σε tokens StringTokenizer itr = new StringTokenizer(tweetText); // Επεξεργάζεται το κάθε token while (itr.hasMoreTokens()) { String token = itr.nextToken().strip(); // Αγνοεί τα tokens μικρότερα από 3 χαρακτήρες if (token.length() < 3) { continue; } word.set(String.valueOf(token)); try { // Παίρνει το tweetId και το μετατρέπει σε long, αφού πρώτα το μετατρέψει σε double tweetId.set((long) Double.parseDouble(tweet.getTweetId())); // Αποθηκεύει το token και το tweetId στο context context.write(word, tweetId); } catch (Exception e) { System.out.println(e.getMessage()); } } } } public static class TweetsReducer extends Reducer<Text, LongWritable, Text, Text> { private final Text result = new Text(); public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException { // Δημιουργία string με όλα τα tweetIds, αφαιρώντας τα πιθανά διπλά // (λέξεις που εμφανίζονται που εμφανίζονται πάνω από μία φορά στο ίδιο tweet) HashSet<String> tweetIds = new HashSet<>(); for (LongWritable val : values) { tweetIds.add(String.valueOf(val)); } StringJoiner text = new StringJoiner(" "); for (String tweetId : tweetIds) { text.add(tweetId); } // Αποθηκεύει το string στο result result.set(String.valueOf(text)); // Αποθηκεύει το token και το string στο context context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "Airline tweets"); job.setJarByClass(AirSupport.class); job.setMapperClass(TokenizerMapper.class); job.setReducerClass(TweetsReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(LongWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } /** * Βοηθητική κλάση για την καταχώρηση του Tweet */ public static class Tweet { private final String tweetId; private final String airlineSentiment; private final String airlineSentimentConfidence; private final String negativeReason; private final String negativeReasonConfidence; private final String airline; private final String name; private final String text; private final String tweetCreated; private final String userTimezone; public Tweet(String[] tweetArray) { this.tweetId = tweetArray[0]; this.airlineSentiment = tweetArray[1]; this.airlineSentimentConfidence = tweetArray[2]; this.negativeReason = tweetArray[3]; this.negativeReasonConfidence = tweetArray[4]; this.airline = tweetArray[5]; this.name = tweetArray[6]; this.text = tweetArray[7]; this.tweetCreated = tweetArray[8]; this.userTimezone = tweetArray[9]; } public String getTweetId() { return tweetId; } public String getName() { return name; } /** * Επιστρέφει καθαρισμένο το κείμενο, αφήνοντας μόνο λέξεις, mentions και hashtags * * @return String */ public String getClearedText() { return text.replaceAll("^[0-9]+", "") .replaceAll("http\\S+", "") .replaceAll("[^\\p{L}\\p{Nd}\\s@#]", "") .replaceAll("\\p{C}", "") .replaceAll("\\s+", " ") .toLowerCase(); } @Override public String toString() { return "Tweet{" + "tweetId='" + tweetId + '\'' + ", airlineSentiment='" + airlineSentiment + '\'' + ", airlineSentimentConfidence='" + airlineSentimentConfidence + '\'' + ", negativeReason='" + negativeReason + '\'' + ", negativeReasonConfidence='" + negativeReasonConfidence + '\'' + ", airline='" + airline + '\'' + ", name='" + name + '\'' + ", text='" + text + '\'' + ", tweetCreated='" + tweetCreated + '\'' + ", userTimezone='" + userTimezone + '\'' + '}'; } } }
ikiranis/AirSupport
src/main/java/eu/apps4net/AirSupport.java
2,215
// Αγνοεί τα tokens μικρότερα από 3 χαρακτήρες
line_comment
el
package eu.apps4net; import java.io.IOException; import java.util.HashSet; import java.util.StringJoiner; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class AirSupport { /** * Σπάει τη γραμμή του CSV σε στοιχεία, αποφεύγοντας να διαχωρίζει τα στοιχεία μέσα σε εισαγωγικά * * source: 2ο θέμα, 3ης εργασία ΠΛΗ47, του 2021-2022 * * @param line string to be split */ private static String[] processLine(String line) { // Create a regular expression for proper split of each line // The regex for characters other than quote (") String otherThanQuote = " [^\"] "; // The regex for a quoted string. e.g "whatever1 whatever2" String quotedString = String.format(" \" %s* \" ", otherThanQuote); // The regex to split the line using comma (,) but taking into consideration the quoted strings // This means that is a comma is in a quoted string, it should be ignored. String regex = String.format("(?x) " + // enable comments, ignore white spaces ", " + // match a comma "(?= " + // start positive look ahead " (?: " + // start non-capturing group 1 " %s* " + // match 'otherThanQuote' zero or more times " %s " + // match 'quotedString' " )* " + // end group 1 and repeat it zero or more times " %s* " + // match 'otherThanQuote' " $ " + // match the end of the string ") ", // stop positive look ahead otherThanQuote, quotedString, otherThanQuote); String[] tokens = line.split(regex, -1); // check for the proper number of columns if (tokens.length == 10) { return tokens; } else { System.err.println("Wrong number of columns for line: " + line); return null; } } public static class TokenizerMapper extends Mapper<Object, Text, Text, LongWritable> { private final static LongWritable tweetId = new LongWritable(); private final Text word = new Text(); public void map(Object key, Text value, Context context) throws IOException, InterruptedException { Tweet tweet = null; String line = value.toString(); String tweetText = ""; // Σπάει τη γραμμή σε στοιχεία String[] tweetArray = processLine(line); // Αν το tweetArray δεν είναι null if(tweetArray != null) { // Δημιουργία αντικειμένου Tweet tweet = new Tweet(tweetArray); // Παίρνει καθαρό κείμενο από το Tweet tweetText = tweet.getClearedText(); } // Παίρνει την τρέχουσα γραμμή σε tokens StringTokenizer itr = new StringTokenizer(tweetText); // Επεξεργάζεται το κάθε token while (itr.hasMoreTokens()) { String token = itr.nextToken().strip(); // Αγνοεί τα<SUF> if (token.length() < 3) { continue; } word.set(String.valueOf(token)); try { // Παίρνει το tweetId και το μετατρέπει σε long, αφού πρώτα το μετατρέψει σε double tweetId.set((long) Double.parseDouble(tweet.getTweetId())); // Αποθηκεύει το token και το tweetId στο context context.write(word, tweetId); } catch (Exception e) { System.out.println(e.getMessage()); } } } } public static class TweetsReducer extends Reducer<Text, LongWritable, Text, Text> { private final Text result = new Text(); public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException { // Δημιουργία string με όλα τα tweetIds, αφαιρώντας τα πιθανά διπλά // (λέξεις που εμφανίζονται που εμφανίζονται πάνω από μία φορά στο ίδιο tweet) HashSet<String> tweetIds = new HashSet<>(); for (LongWritable val : values) { tweetIds.add(String.valueOf(val)); } StringJoiner text = new StringJoiner(" "); for (String tweetId : tweetIds) { text.add(tweetId); } // Αποθηκεύει το string στο result result.set(String.valueOf(text)); // Αποθηκεύει το token και το string στο context context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "Airline tweets"); job.setJarByClass(AirSupport.class); job.setMapperClass(TokenizerMapper.class); job.setReducerClass(TweetsReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(LongWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } /** * Βοηθητική κλάση για την καταχώρηση του Tweet */ public static class Tweet { private final String tweetId; private final String airlineSentiment; private final String airlineSentimentConfidence; private final String negativeReason; private final String negativeReasonConfidence; private final String airline; private final String name; private final String text; private final String tweetCreated; private final String userTimezone; public Tweet(String[] tweetArray) { this.tweetId = tweetArray[0]; this.airlineSentiment = tweetArray[1]; this.airlineSentimentConfidence = tweetArray[2]; this.negativeReason = tweetArray[3]; this.negativeReasonConfidence = tweetArray[4]; this.airline = tweetArray[5]; this.name = tweetArray[6]; this.text = tweetArray[7]; this.tweetCreated = tweetArray[8]; this.userTimezone = tweetArray[9]; } public String getTweetId() { return tweetId; } public String getName() { return name; } /** * Επιστρέφει καθαρισμένο το κείμενο, αφήνοντας μόνο λέξεις, mentions και hashtags * * @return String */ public String getClearedText() { return text.replaceAll("^[0-9]+", "") .replaceAll("http\\S+", "") .replaceAll("[^\\p{L}\\p{Nd}\\s@#]", "") .replaceAll("\\p{C}", "") .replaceAll("\\s+", " ") .toLowerCase(); } @Override public String toString() { return "Tweet{" + "tweetId='" + tweetId + '\'' + ", airlineSentiment='" + airlineSentiment + '\'' + ", airlineSentimentConfidence='" + airlineSentimentConfidence + '\'' + ", negativeReason='" + negativeReason + '\'' + ", negativeReasonConfidence='" + negativeReasonConfidence + '\'' + ", airline='" + airline + '\'' + ", name='" + name + '\'' + ", text='" + text + '\'' + ", tweetCreated='" + tweetCreated + '\'' + ", userTimezone='" + userTimezone + '\'' + '}'; } } }
272_4
// Controller κλάση που περιέχει μεθόδους για τραβάνε δεδομένα από το API // // Βασικές μέθοδοι που μπορεί να καλέσει ο χρήστης: // getSingleDraw() // getRangeDraws() // getLastDrawIds(int length) package controller; import api.CurrentDrawApi; import api.DrawApi; import api.RangeDrawApi; import java.util.ArrayList; import java.util.function.Consumer; import model.Draw; import service.DateRange; import service.SplittedDateRange; public class FetchFromApi { private ArrayList<Draw> drawsData = new ArrayList<>(); private ArrayList<String> drawIds = new ArrayList<>(); private Consumer<Integer> worker; private int lastId; public int getLastId() { return lastId; } public void setWorker(Consumer<Integer> worker) { this.worker = worker; } public ArrayList<Draw> getDrawsData() { return drawsData; } public ArrayList<String> getDrawIds() { return drawIds; } public void clearDraws() { drawsData.clear(); } // Κάνει το διάβασμα από το Api για ένα μοναδικό drawId public void getSingleDraw(String drawId) { clearDraws(); DrawApi api = new DrawApi(drawId); drawsData.add(api.getData()); } // Κάνει το διάβασμα από το Api για ένα εύρος ημερομηνιών public void getRangeDraws(DateRange dateRange) { ArrayList<DateRange> dateRanges; int progress = 0; clearDraws(); // Σπάει το range σε τρίμηνα SplittedDateRange splittedDateRange = new SplittedDateRange(dateRange); dateRanges = splittedDateRange.getSplitted(); // Κάνει κλήσεις στο API για κάθε τρίμηνο και τα αποτελέσματα τα // περνάει στην λίστα drawsData for (DateRange range : dateRanges) { RangeDrawApi api = new RangeDrawApi(range); drawsData.addAll(api.getData()); // Επιστροφή στο worker του ποσοστού προόδου worker.accept(100*(progress+1)/dateRanges.size()); progress++; } } // Επιστρέφει το drawId της τελευταίας κλήρωσης private int getLastDrawId() { CurrentDrawApi api = new CurrentDrawApi(); Draw lastDraw = api.getData(); return lastDraw.getId(); } // Επιστρέφει μία λίστα με τα τελευταία length drawIds public void getLastDrawIds(int length) { lastId = getLastDrawId(); for (int i = lastId; i >= lastId - length; i--) { drawIds.add(Integer.toString(i)); } } }
ikiranis/tzokerApp
src/controller/FetchFromApi.java
879
// Σπάει το range σε τρίμηνα
line_comment
el
// Controller κλάση που περιέχει μεθόδους για τραβάνε δεδομένα από το API // // Βασικές μέθοδοι που μπορεί να καλέσει ο χρήστης: // getSingleDraw() // getRangeDraws() // getLastDrawIds(int length) package controller; import api.CurrentDrawApi; import api.DrawApi; import api.RangeDrawApi; import java.util.ArrayList; import java.util.function.Consumer; import model.Draw; import service.DateRange; import service.SplittedDateRange; public class FetchFromApi { private ArrayList<Draw> drawsData = new ArrayList<>(); private ArrayList<String> drawIds = new ArrayList<>(); private Consumer<Integer> worker; private int lastId; public int getLastId() { return lastId; } public void setWorker(Consumer<Integer> worker) { this.worker = worker; } public ArrayList<Draw> getDrawsData() { return drawsData; } public ArrayList<String> getDrawIds() { return drawIds; } public void clearDraws() { drawsData.clear(); } // Κάνει το διάβασμα από το Api για ένα μοναδικό drawId public void getSingleDraw(String drawId) { clearDraws(); DrawApi api = new DrawApi(drawId); drawsData.add(api.getData()); } // Κάνει το διάβασμα από το Api για ένα εύρος ημερομηνιών public void getRangeDraws(DateRange dateRange) { ArrayList<DateRange> dateRanges; int progress = 0; clearDraws(); // Σπάει το<SUF> SplittedDateRange splittedDateRange = new SplittedDateRange(dateRange); dateRanges = splittedDateRange.getSplitted(); // Κάνει κλήσεις στο API για κάθε τρίμηνο και τα αποτελέσματα τα // περνάει στην λίστα drawsData for (DateRange range : dateRanges) { RangeDrawApi api = new RangeDrawApi(range); drawsData.addAll(api.getData()); // Επιστροφή στο worker του ποσοστού προόδου worker.accept(100*(progress+1)/dateRanges.size()); progress++; } } // Επιστρέφει το drawId της τελευταίας κλήρωσης private int getLastDrawId() { CurrentDrawApi api = new CurrentDrawApi(); Draw lastDraw = api.getData(); return lastDraw.getId(); } // Επιστρέφει μία λίστα με τα τελευταία length drawIds public void getLastDrawIds(int length) { lastId = getLastDrawId(); for (int i = lastId; i >= lastId - length; i--) { drawIds.add(Integer.toString(i)); } } }
2766_26
package Compiler; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; public class Parser { static ArrayList<Token> tokens; static Token token; public static void main(String[] args){ Lex lex = new Lex("C:\\Users\\kavou\\Desktop\\lex.txt"); System.out.println("lexical correct program"); tokens = lex.getTokens(); token=next(); program(); System.out.println("syntactically correct program"); } private static Token next(){ //Παίρνουμε το πρώτο Token απο τη λίστα Tokens και βάζουμε στη μεταβλητή token token = tokens.get(0); //Στη συνέχεια το αφαιρούμε απο τη λίστα tokens.remove(0); return token; } public static void error(String s){ //Εμφανίζει μήνυμα λάθους System.out.println("ERROR: " +s); //Και τερματίζει το πρόγραμμα System.exit(0); } public static void program(){ //Ελέγχουμε αν ξεκινάει με τη λέξη program if (token.type.name()=="programTK"){ token=next(); //Και αν στη συνέχεια ακολουθάει το όνομα του //προγράμματος (το οποίο είναι τύπου variable) if(token.type.name()=="variableTK"){ token=next(); //Αφού έγιναν οι έλεγχοι, προχωράμε στη μέθοδο block block(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else { error("variable expected after keyword program, error at line " +token.line); } } //Αλλιώς εμφανίζεται μήνυμα λάθους else { error("keyword program expected, error at line " +token.line); } } public static void block(){ //Ελέγχουμε αν ξεκινάει με τη λέξη begin if (token.type.name()=="beginTK"){ token=next(); //Αφού έγινε ο έλεγχος προχωράμε στη μέθοδο declarations declarations(); //Και στη συνέχεια στη sequence sequence(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else { error("keyword begin expected, error at line " +token.line); } } public static void declarations(){ //Ελέγχουμε αν ξεκινάει με το declare if (token.type.name()=="declareTK"){ token=next(); //Αφού έγινε ο έλεγχος προχωράμε στη μέθοδο varlist varlist(); //Μετά την εκτέλεση της varlist, ελέγχουμε αν υπάρχει η λέξη enddeclare if (token.type.name()=="enddeclareTK"){ //Αν υπάρχει επιστρέφουμε στην block (για να συνεχίσει στη sequence) token=next(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else { error("keyword enddeclare expected after keyword declare, error at line " +token.line); } } } public static void varlist(){ //Ελέγχουμε αν ξεκινάει με μεταβλητή. Αν όχι δεν εμφανίζεται //μήνυμα λάθους, γιατί η varlist έχει το δικαίωμα να μην περιέχει τίποτα. if(token.type.name()=="variableTK"){ token=next(); } //Αν συναντήσουμε κόμμα while (token.type.name()=="commaTK"){ token=next(); //Πρέπει υποχρεωτικά να ακολουθεί μεταβλητή if(token.type.name()=="variableTK"){ token=next(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else{ error("variable expected after comma, error at line " +token.line); } } } public static void sequence(){ //Καλείται η statement statement(); //Αν συναντήσουμε ελληνικό ερωτηματικό while (token.type.name()=="semicolTK"){ //Προχωράμε στο επόμενο token token=next(); //Και ξανακαλολυμε τη statement statement(); } } public static void statement(){ //Ελέγχουμε ποιο είναι το πρώτο token που συναντάμε //και καλούμε την αντίστοιχη μέθοδο. //Αν δεν συναντήσουμε τίποτα, δεν εμφανίζεται μήνυμα λάθους //γιατί η statement έχει το δικαίωμα να μην περιέχει τίποτα. if (token.type.name()=="inputTK"){ token=next(); input_stat(); } else if (token.type.name()=="variableTK") { token=next(); assignment_stat(); } else if (token.type.name()=="printTK") { token=next(); print_stat(); } else if(token.type.name()=="endTK"){ return; } //Εμφανίζεται μήνυμα λάθους μόνο όταν βρούμε κάποιο token, //διαφορετικό απο τα παραπάνω τέσσερα else{ error("not valid character, error at line " +token.line); } } public static void input_stat(){ //Μετά το input ελέγχουμε αν υπάρχει αριστερή παρένθεση if(token.type.name()=="leftpTK"){ //Και προχωράμε στο επόμενο token token=next(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else{ error("expected left parenthesis after keyword input, error at line " +token.line); } //Στη συνέχεια ελέγχουμε αν μετά την αριστερή παρένθεση εμφανίζεται μεταβλητή if(token.type.name()=="variableTK"){ //Και προχωράμε στο επόμενο token token=next(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else{ error("expected variable inside input(), error at line " +token.line); } //Τέλος ελέγχουμε αν μετά τη μεταβλητή εμφανίζεται δεξιά παρένθεση if(token.type.name()=="rightpTK"){ //Και προχωράμε στο επόμενο token token=next(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else{ error("expected right parenthesis after variable, error at line " +token.line); } } public static void assignment_stat(){ //Μετά τη μεταβλητή ελέγχουμε αν υπάρχει το token "assignmentTK" (:=) if(token.type.name()=="assignTK"){ //Και προχωράμε στο επόμενο token token=next(); //Και στη συνέχεια καλούμε τη μεθοδο expression expression(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else{ error(":= expected after variable, error at line " +token.line); } } public static void print_stat(){ //Μετά το print ελέγχουμε αν υπάρχει αριστερή παρένθεση if(token.type.name()=="leftpTK"){ //Και παίρνουμε το επόμενο token token=next(); //Όσο δεν βρίσκουμε δεξιά παρένθεση, καλούμε την expression while(token.type.name()!="rightpTK"){ expression(); } //Όταν βρούμε δεξιά παρένθεση, παίρνουμε το επόμενο token token=next(); } //Εμφανίζεται μήνυμα λάθους αν δεν ξεκινάει με αριστερή παρένθεση μετά το print else{ error("expected left parenthesis after keyword print, error at line " +token.line); } } public static void expression(){ //Καλείται η optional_sign optional_sign(); //Και στη συνέχεια η term term(); //Όσες φορές βρούμε σύν ή πλήν while(token.type.name()=="plusTK" || token.type.name()=="minusTK"){ //Καλούμε την add_oper add_oper(); } } public static void term(){ //Καλείται η factor factor(); //Όσες φορές βρούμε επί ή δια while(token.type.name()=="multTK" || token.type.name()=="divTK"){ //Καλούμε την Mul_oper mul_oper(); } } public static void factor(){ //Αν βρούμε constant ή variable if(token.type.name()=="constantTK" || token.type.name()=="variableTK") { //Παίρνουμε το επόμενο token. Ο έλεγχος επιστρέφει στην term token=next(); } //Αν βρούμε αριστερή παρένθεση else if(token.type.name()=="leftpTK"){ //Παίρνουμε το επόμενο token token=next(); //Όσο δεν βρίσκουμε δεξιά παρένθεση καλούμε την expression. while(token.type.name()!="rightpTK"){ expression(); } //Αν βρούμε δεξιά παρένθεση, παίρνουμε το επόμενο token. //Ο έλεγχος επιστρέφει στην term token=next(); } //Αν δεν βρούμε ένα απ' τα προηγούμενα τρία token, τότε επιστρέφεται μήνυμα λάθους else{ error("constant or variable or (EXPRESSION) expected, error at line " +token.line); } } public static void add_oper(){ //Παίρνουμε το επόμενο token token=next(); //Και καλούμε την term term(); } public static void mul_oper(){ //Παίρνουμε το επόμενο token token=next(); //Και καλούμε την factor factor(); } public static void optional_sign(){ //Αν βρούμε σύν ή πλήν if(token.type.name()=="plusTK" || token.type.name()=="minusTK"){ //Καλούμε την add_oper add_oper(); } } }
ilias-arm/LexicalAnalyzer
LexicalAnalyzer/src/Compiler/Parser.java
3,723
//Προχωράμε στο επόμενο token
line_comment
el
package Compiler; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; public class Parser { static ArrayList<Token> tokens; static Token token; public static void main(String[] args){ Lex lex = new Lex("C:\\Users\\kavou\\Desktop\\lex.txt"); System.out.println("lexical correct program"); tokens = lex.getTokens(); token=next(); program(); System.out.println("syntactically correct program"); } private static Token next(){ //Παίρνουμε το πρώτο Token απο τη λίστα Tokens και βάζουμε στη μεταβλητή token token = tokens.get(0); //Στη συνέχεια το αφαιρούμε απο τη λίστα tokens.remove(0); return token; } public static void error(String s){ //Εμφανίζει μήνυμα λάθους System.out.println("ERROR: " +s); //Και τερματίζει το πρόγραμμα System.exit(0); } public static void program(){ //Ελέγχουμε αν ξεκινάει με τη λέξη program if (token.type.name()=="programTK"){ token=next(); //Και αν στη συνέχεια ακολουθάει το όνομα του //προγράμματος (το οποίο είναι τύπου variable) if(token.type.name()=="variableTK"){ token=next(); //Αφού έγιναν οι έλεγχοι, προχωράμε στη μέθοδο block block(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else { error("variable expected after keyword program, error at line " +token.line); } } //Αλλιώς εμφανίζεται μήνυμα λάθους else { error("keyword program expected, error at line " +token.line); } } public static void block(){ //Ελέγχουμε αν ξεκινάει με τη λέξη begin if (token.type.name()=="beginTK"){ token=next(); //Αφού έγινε ο έλεγχος προχωράμε στη μέθοδο declarations declarations(); //Και στη συνέχεια στη sequence sequence(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else { error("keyword begin expected, error at line " +token.line); } } public static void declarations(){ //Ελέγχουμε αν ξεκινάει με το declare if (token.type.name()=="declareTK"){ token=next(); //Αφού έγινε ο έλεγχος προχωράμε στη μέθοδο varlist varlist(); //Μετά την εκτέλεση της varlist, ελέγχουμε αν υπάρχει η λέξη enddeclare if (token.type.name()=="enddeclareTK"){ //Αν υπάρχει επιστρέφουμε στην block (για να συνεχίσει στη sequence) token=next(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else { error("keyword enddeclare expected after keyword declare, error at line " +token.line); } } } public static void varlist(){ //Ελέγχουμε αν ξεκινάει με μεταβλητή. Αν όχι δεν εμφανίζεται //μήνυμα λάθους, γιατί η varlist έχει το δικαίωμα να μην περιέχει τίποτα. if(token.type.name()=="variableTK"){ token=next(); } //Αν συναντήσουμε κόμμα while (token.type.name()=="commaTK"){ token=next(); //Πρέπει υποχρεωτικά να ακολουθεί μεταβλητή if(token.type.name()=="variableTK"){ token=next(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else{ error("variable expected after comma, error at line " +token.line); } } } public static void sequence(){ //Καλείται η statement statement(); //Αν συναντήσουμε ελληνικό ερωτηματικό while (token.type.name()=="semicolTK"){ //Προχωράμε στο<SUF> token=next(); //Και ξανακαλολυμε τη statement statement(); } } public static void statement(){ //Ελέγχουμε ποιο είναι το πρώτο token που συναντάμε //και καλούμε την αντίστοιχη μέθοδο. //Αν δεν συναντήσουμε τίποτα, δεν εμφανίζεται μήνυμα λάθους //γιατί η statement έχει το δικαίωμα να μην περιέχει τίποτα. if (token.type.name()=="inputTK"){ token=next(); input_stat(); } else if (token.type.name()=="variableTK") { token=next(); assignment_stat(); } else if (token.type.name()=="printTK") { token=next(); print_stat(); } else if(token.type.name()=="endTK"){ return; } //Εμφανίζεται μήνυμα λάθους μόνο όταν βρούμε κάποιο token, //διαφορετικό απο τα παραπάνω τέσσερα else{ error("not valid character, error at line " +token.line); } } public static void input_stat(){ //Μετά το input ελέγχουμε αν υπάρχει αριστερή παρένθεση if(token.type.name()=="leftpTK"){ //Και προχωράμε στο επόμενο token token=next(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else{ error("expected left parenthesis after keyword input, error at line " +token.line); } //Στη συνέχεια ελέγχουμε αν μετά την αριστερή παρένθεση εμφανίζεται μεταβλητή if(token.type.name()=="variableTK"){ //Και προχωράμε στο επόμενο token token=next(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else{ error("expected variable inside input(), error at line " +token.line); } //Τέλος ελέγχουμε αν μετά τη μεταβλητή εμφανίζεται δεξιά παρένθεση if(token.type.name()=="rightpTK"){ //Και προχωράμε στο επόμενο token token=next(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else{ error("expected right parenthesis after variable, error at line " +token.line); } } public static void assignment_stat(){ //Μετά τη μεταβλητή ελέγχουμε αν υπάρχει το token "assignmentTK" (:=) if(token.type.name()=="assignTK"){ //Και προχωράμε στο επόμενο token token=next(); //Και στη συνέχεια καλούμε τη μεθοδο expression expression(); } //Αλλιώς εμφανίζεται μήνυμα λάθους else{ error(":= expected after variable, error at line " +token.line); } } public static void print_stat(){ //Μετά το print ελέγχουμε αν υπάρχει αριστερή παρένθεση if(token.type.name()=="leftpTK"){ //Και παίρνουμε το επόμενο token token=next(); //Όσο δεν βρίσκουμε δεξιά παρένθεση, καλούμε την expression while(token.type.name()!="rightpTK"){ expression(); } //Όταν βρούμε δεξιά παρένθεση, παίρνουμε το επόμενο token token=next(); } //Εμφανίζεται μήνυμα λάθους αν δεν ξεκινάει με αριστερή παρένθεση μετά το print else{ error("expected left parenthesis after keyword print, error at line " +token.line); } } public static void expression(){ //Καλείται η optional_sign optional_sign(); //Και στη συνέχεια η term term(); //Όσες φορές βρούμε σύν ή πλήν while(token.type.name()=="plusTK" || token.type.name()=="minusTK"){ //Καλούμε την add_oper add_oper(); } } public static void term(){ //Καλείται η factor factor(); //Όσες φορές βρούμε επί ή δια while(token.type.name()=="multTK" || token.type.name()=="divTK"){ //Καλούμε την Mul_oper mul_oper(); } } public static void factor(){ //Αν βρούμε constant ή variable if(token.type.name()=="constantTK" || token.type.name()=="variableTK") { //Παίρνουμε το επόμενο token. Ο έλεγχος επιστρέφει στην term token=next(); } //Αν βρούμε αριστερή παρένθεση else if(token.type.name()=="leftpTK"){ //Παίρνουμε το επόμενο token token=next(); //Όσο δεν βρίσκουμε δεξιά παρένθεση καλούμε την expression. while(token.type.name()!="rightpTK"){ expression(); } //Αν βρούμε δεξιά παρένθεση, παίρνουμε το επόμενο token. //Ο έλεγχος επιστρέφει στην term token=next(); } //Αν δεν βρούμε ένα απ' τα προηγούμενα τρία token, τότε επιστρέφεται μήνυμα λάθους else{ error("constant or variable or (EXPRESSION) expected, error at line " +token.line); } } public static void add_oper(){ //Παίρνουμε το επόμενο token token=next(); //Και καλούμε την term term(); } public static void mul_oper(){ //Παίρνουμε το επόμενο token token=next(); //Και καλούμε την factor factor(); } public static void optional_sign(){ //Αν βρούμε σύν ή πλήν if(token.type.name()=="plusTK" || token.type.name()=="minusTK"){ //Καλούμε την add_oper add_oper(); } } }
8549_12
/* * 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.di.nomothesiag3parser; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.lucene.analysis.core.SimpleAnalyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.openrdf.OpenRDFException; import org.openrdf.query.BindingSet; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.http.HTTPRepository; /** * * @author Kiddo */ public class EntityIndex { IndexWriter indexWriter; Directory directory; public EntityIndex() throws IOException{ // Path path = Paths.get("C:/Users/liako/Desktop/lucene/indexes/entities"); // directory = FSDirectory.open(path); // IndexWriterConfig config = new IndexWriterConfig(new SimpleAnalyzer()); // indexWriter = new IndexWriter(directory, config); // indexWriter.deleteAll(); } public void closeIndex() throws IOException{ indexWriter.close(); directory.close(); } String capitalize(String title){ String caps_title = ""; int count =0; while(count<title.length()){ switch(title.charAt(count)){ case 'α': case 'ά': caps_title += 'Α'; break; case 'β': caps_title += 'Β'; break; case 'γ': caps_title += 'Γ'; break; case 'δ': caps_title += 'Δ'; break; case 'ε': case 'έ': caps_title += 'Ε'; break; case 'ζ': caps_title += 'Ζ'; break; case 'η': case 'ή': caps_title += 'Η'; break; case 'θ': caps_title += 'Θ'; break; case 'ι': case 'ί': caps_title += 'Ι'; break; case 'κ': caps_title += 'Κ'; break; case 'λ': caps_title += 'Λ'; break; case 'μ': caps_title += 'Μ'; break; case 'ν': caps_title += 'Ν'; break; case 'ξ': caps_title += 'Ξ'; break; case 'ο': case 'ό': caps_title += 'Ο'; break; case 'π': caps_title += 'Π'; break; case 'ρ': caps_title += 'Ρ'; break; case 'σ': case 'ς': caps_title += 'Σ'; break; case 'τ': caps_title += 'Τ'; break; case 'υ': case 'ύ': caps_title += 'Υ'; break; case 'φ': caps_title += 'Φ'; break; case 'χ': caps_title += 'Χ'; break; case 'ψ': caps_title += 'Ψ'; break; case 'ω': case 'ώ': caps_title += 'Ω'; break; default: caps_title += title.charAt(count); } count++; } return caps_title; } void findPlaces() throws IOException{ String sesameServer = "http://localhost:8080/openrdf-sesame"; String repositoryID = "legislation"; // Connect to Sesame Repository repo = new HTTPRepository(sesameServer, repositoryID); try { repo.initialize(); } catch (RepositoryException ex) { Logger.getLogger(EntityIndex.class.getName()).log(Level.SEVERE, null, ex); } TupleQueryResult result; try { RepositoryConnection con = repo.getConnection(); try { String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n" + "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n" + "\n" + "SELECT DISTINCT ?name ?id \n" + "WHERE{\n" + "?id <http://geo.linkedopendata.gr/gag/ontology/έχει_επίσημο_όνομα> ?name." + "}\n" ; //System.out.println(queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString); result = tupleQuery.evaluate(); try { // iterate the result set while (result.hasNext()) { BindingSet bindingSet = result.next(); String name = bindingSet.getValue("name").toString(); name = name.replace("^^<http://www.w3.org/2001/XMLSchema#string>", ""); name = trimDoubleQuotes(name); String id = bindingSet.getValue("id").toString(); addDoc(indexWriter,name,id); System.out.println(name); } } finally { result.close(); } } finally { con.close(); } } catch (OpenRDFException e) { // handle exception } } void findOrganizations() throws IOException{ String sesameServer = "http://localhost:8080/openrdf-sesame"; String repositoryID = "legislation"; // Connect to Sesame Repository repo = new HTTPRepository(sesameServer, repositoryID); try { repo.initialize(); } catch (RepositoryException ex) { Logger.getLogger(EntityIndex.class.getName()).log(Level.SEVERE, null, ex); } TupleQueryResult result; try { RepositoryConnection con = repo.getConnection(); try { String queryString = "PREFIX pb: <http://geo.linkedopendata.gr/public-buildings/ontology/>\n" + "\n" + "SELECT DISTINCT ?name ?id \n" + "WHERE{\n" + "?id pb:έχει_όνομα_υπηρεσίας ?name." + "}\n" ; //System.out.println(queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString); result = tupleQuery.evaluate(); try { // iterate the result set while (result.hasNext()) { BindingSet bindingSet = result.next(); String name = bindingSet.getValue("name").toString(); name = name.replace("^^<http://www.w3.org/2001/XMLSchema#string>", ""); name = trimDoubleQuotes(name); String id = bindingSet.getValue("id").toString(); addDoc(indexWriter,name,id); System.out.println(name); } } finally { result.close(); } } finally { con.close(); } } catch (OpenRDFException e) { // handle exception } } void findPeople() throws IOException{ String sesameServer = "http://localhost:8080/openrdf-sesame"; String repositoryID = "dbpedia"; // Connect to Sesame Repository repo = new HTTPRepository(sesameServer, repositoryID); try { repo.initialize(); } catch (RepositoryException ex) { Logger.getLogger(EntityIndex.class.getName()).log(Level.SEVERE, null, ex); } TupleQueryResult result; try { RepositoryConnection con = repo.getConnection(); try { String queryString = "PREFIX ontology: <http://dbpedia.org/ontology/>\n" + "PREFIX prop: <http://el.dbpedia.org/property/>\n" + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "\n" + "select distinct ?id ?name ?image\n" + "where {\n" + "?id rdf:type ontology:Politician.\n" + "?id foaf:name ?name.\n" + "\n" + "{?id prop:εθνικότητα <http://el.dbpedia.org/resource/Έλληνας>} UNION {?id prop:εθνικότητα \"Ελληνική\"@el} UNION {?id prop:εθνικότητα <http://el.dbpedia.org/resource/Έλληνες>}\n" + "\n" + "}"; //System.out.println(queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString); result = tupleQuery.evaluate(); try { // iterate the result set while (result.hasNext()) { BindingSet bindingSet = result.next(); String name = bindingSet.getValue("name").toString(); name = name.replace("^^<http://www.w3.org/2001/XMLSchema#string>", ""); name = this.capitalize(trimDoubleQuotes(name.replace("@el", ""))); String id = bindingSet.getValue("id").toString().replace("resource", "page"); addDoc(indexWriter,name,id); System.out.println(name); } } finally { result.close(); } } finally { con.close(); } } catch (OpenRDFException e) { // handle exception } } public String tagEntity(String ent){ return ""; } public static String trimDoubleQuotes(String text) { int textLength = text.length(); if (textLength >= 2 && text.charAt(0) == '"' && text.charAt(textLength - 1) == '"') { return text.substring(1, textLength - 1); } return text; } public String searchEntity(String text) { //Apache Lucene searching text inside .txt files String uri = ""; try { Path path = Paths.get("C:/Users/liako/Desktop/Nomothesi@ API/lucene/indexes/entities"); Directory directory2 = FSDirectory.open(path); IndexReader indexReader = DirectoryReader.open(directory2); IndexSearcher indexSearcher = new IndexSearcher(indexReader); QueryParser queryParser = new QueryParser("entity", new StandardAnalyzer()); String text2 = "\"" + text + "\"~"; //text.replace(" ", "~ ").replace("-~", "-") + "~"; Query query = queryParser.parse(text2); TopDocs topDocs = indexSearcher.search(query,10); if(topDocs.totalHits>0){ //System.out.print(" | TOTAL_HITS: " + topDocs.totalHits); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { if(scoreDoc.score>3){ Document document = indexSearcher.doc(scoreDoc.doc); float query_size = (float) text.length(); float entity_size = (float) document.get("entity").length(); float limit = query_size/entity_size; if(text.contains(" ") && limit >=0.8){ // System.out.print("QUERY: " + text); // System.out.print(" | RESULT: " + document.get("entity")); // System.out.println(" | SCORE: " +scoreDoc.score); // System.out.println(" | LIMIT: " + limit); uri = document.get("uri"); } else if(limit >=0.7){ // System.out.print("QUERY: " + text); // System.out.print(" | RESULT: " + document.get("entity")); // System.out.println(" | SCORE: " +scoreDoc.score); // System.out.println(" | LIMIT: " + limit); uri = document.get("uri"); } } break; } } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return uri; } private void addDoc(IndexWriter w, String entity, String uri) throws IOException { Document doc = new Document(); doc.add(new TextField("entity", entity, Store.YES)); doc.add(new TextField("uri", uri, Store.YES)); indexWriter.addDocument(doc); } }
iliaschalkidis/nomothesia-g3-parser
src/main/java/com/di/nomothesiag3parser/EntityIndex.java
3,342
//el.dbpedia.org/resource/Έλληνας>} UNION {?id prop:εθνικότητα \"Ελληνική\"@el} UNION {?id prop:εθνικότητα <http://el.dbpedia.org/resource/Έλληνες>}\n" +
line_comment
el
/* * 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.di.nomothesiag3parser; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.lucene.analysis.core.SimpleAnalyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.openrdf.OpenRDFException; import org.openrdf.query.BindingSet; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.http.HTTPRepository; /** * * @author Kiddo */ public class EntityIndex { IndexWriter indexWriter; Directory directory; public EntityIndex() throws IOException{ // Path path = Paths.get("C:/Users/liako/Desktop/lucene/indexes/entities"); // directory = FSDirectory.open(path); // IndexWriterConfig config = new IndexWriterConfig(new SimpleAnalyzer()); // indexWriter = new IndexWriter(directory, config); // indexWriter.deleteAll(); } public void closeIndex() throws IOException{ indexWriter.close(); directory.close(); } String capitalize(String title){ String caps_title = ""; int count =0; while(count<title.length()){ switch(title.charAt(count)){ case 'α': case 'ά': caps_title += 'Α'; break; case 'β': caps_title += 'Β'; break; case 'γ': caps_title += 'Γ'; break; case 'δ': caps_title += 'Δ'; break; case 'ε': case 'έ': caps_title += 'Ε'; break; case 'ζ': caps_title += 'Ζ'; break; case 'η': case 'ή': caps_title += 'Η'; break; case 'θ': caps_title += 'Θ'; break; case 'ι': case 'ί': caps_title += 'Ι'; break; case 'κ': caps_title += 'Κ'; break; case 'λ': caps_title += 'Λ'; break; case 'μ': caps_title += 'Μ'; break; case 'ν': caps_title += 'Ν'; break; case 'ξ': caps_title += 'Ξ'; break; case 'ο': case 'ό': caps_title += 'Ο'; break; case 'π': caps_title += 'Π'; break; case 'ρ': caps_title += 'Ρ'; break; case 'σ': case 'ς': caps_title += 'Σ'; break; case 'τ': caps_title += 'Τ'; break; case 'υ': case 'ύ': caps_title += 'Υ'; break; case 'φ': caps_title += 'Φ'; break; case 'χ': caps_title += 'Χ'; break; case 'ψ': caps_title += 'Ψ'; break; case 'ω': case 'ώ': caps_title += 'Ω'; break; default: caps_title += title.charAt(count); } count++; } return caps_title; } void findPlaces() throws IOException{ String sesameServer = "http://localhost:8080/openrdf-sesame"; String repositoryID = "legislation"; // Connect to Sesame Repository repo = new HTTPRepository(sesameServer, repositoryID); try { repo.initialize(); } catch (RepositoryException ex) { Logger.getLogger(EntityIndex.class.getName()).log(Level.SEVERE, null, ex); } TupleQueryResult result; try { RepositoryConnection con = repo.getConnection(); try { String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n" + "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n" + "\n" + "SELECT DISTINCT ?name ?id \n" + "WHERE{\n" + "?id <http://geo.linkedopendata.gr/gag/ontology/έχει_επίσημο_όνομα> ?name." + "}\n" ; //System.out.println(queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString); result = tupleQuery.evaluate(); try { // iterate the result set while (result.hasNext()) { BindingSet bindingSet = result.next(); String name = bindingSet.getValue("name").toString(); name = name.replace("^^<http://www.w3.org/2001/XMLSchema#string>", ""); name = trimDoubleQuotes(name); String id = bindingSet.getValue("id").toString(); addDoc(indexWriter,name,id); System.out.println(name); } } finally { result.close(); } } finally { con.close(); } } catch (OpenRDFException e) { // handle exception } } void findOrganizations() throws IOException{ String sesameServer = "http://localhost:8080/openrdf-sesame"; String repositoryID = "legislation"; // Connect to Sesame Repository repo = new HTTPRepository(sesameServer, repositoryID); try { repo.initialize(); } catch (RepositoryException ex) { Logger.getLogger(EntityIndex.class.getName()).log(Level.SEVERE, null, ex); } TupleQueryResult result; try { RepositoryConnection con = repo.getConnection(); try { String queryString = "PREFIX pb: <http://geo.linkedopendata.gr/public-buildings/ontology/>\n" + "\n" + "SELECT DISTINCT ?name ?id \n" + "WHERE{\n" + "?id pb:έχει_όνομα_υπηρεσίας ?name." + "}\n" ; //System.out.println(queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString); result = tupleQuery.evaluate(); try { // iterate the result set while (result.hasNext()) { BindingSet bindingSet = result.next(); String name = bindingSet.getValue("name").toString(); name = name.replace("^^<http://www.w3.org/2001/XMLSchema#string>", ""); name = trimDoubleQuotes(name); String id = bindingSet.getValue("id").toString(); addDoc(indexWriter,name,id); System.out.println(name); } } finally { result.close(); } } finally { con.close(); } } catch (OpenRDFException e) { // handle exception } } void findPeople() throws IOException{ String sesameServer = "http://localhost:8080/openrdf-sesame"; String repositoryID = "dbpedia"; // Connect to Sesame Repository repo = new HTTPRepository(sesameServer, repositoryID); try { repo.initialize(); } catch (RepositoryException ex) { Logger.getLogger(EntityIndex.class.getName()).log(Level.SEVERE, null, ex); } TupleQueryResult result; try { RepositoryConnection con = repo.getConnection(); try { String queryString = "PREFIX ontology: <http://dbpedia.org/ontology/>\n" + "PREFIX prop: <http://el.dbpedia.org/property/>\n" + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "\n" + "select distinct ?id ?name ?image\n" + "where {\n" + "?id rdf:type ontology:Politician.\n" + "?id foaf:name ?name.\n" + "\n" + "{?id prop:εθνικότητα <http://el.dbpedia.org/resource/Έλληνας>} UNION<SUF> "\n" + "}"; //System.out.println(queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString); result = tupleQuery.evaluate(); try { // iterate the result set while (result.hasNext()) { BindingSet bindingSet = result.next(); String name = bindingSet.getValue("name").toString(); name = name.replace("^^<http://www.w3.org/2001/XMLSchema#string>", ""); name = this.capitalize(trimDoubleQuotes(name.replace("@el", ""))); String id = bindingSet.getValue("id").toString().replace("resource", "page"); addDoc(indexWriter,name,id); System.out.println(name); } } finally { result.close(); } } finally { con.close(); } } catch (OpenRDFException e) { // handle exception } } public String tagEntity(String ent){ return ""; } public static String trimDoubleQuotes(String text) { int textLength = text.length(); if (textLength >= 2 && text.charAt(0) == '"' && text.charAt(textLength - 1) == '"') { return text.substring(1, textLength - 1); } return text; } public String searchEntity(String text) { //Apache Lucene searching text inside .txt files String uri = ""; try { Path path = Paths.get("C:/Users/liako/Desktop/Nomothesi@ API/lucene/indexes/entities"); Directory directory2 = FSDirectory.open(path); IndexReader indexReader = DirectoryReader.open(directory2); IndexSearcher indexSearcher = new IndexSearcher(indexReader); QueryParser queryParser = new QueryParser("entity", new StandardAnalyzer()); String text2 = "\"" + text + "\"~"; //text.replace(" ", "~ ").replace("-~", "-") + "~"; Query query = queryParser.parse(text2); TopDocs topDocs = indexSearcher.search(query,10); if(topDocs.totalHits>0){ //System.out.print(" | TOTAL_HITS: " + topDocs.totalHits); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { if(scoreDoc.score>3){ Document document = indexSearcher.doc(scoreDoc.doc); float query_size = (float) text.length(); float entity_size = (float) document.get("entity").length(); float limit = query_size/entity_size; if(text.contains(" ") && limit >=0.8){ // System.out.print("QUERY: " + text); // System.out.print(" | RESULT: " + document.get("entity")); // System.out.println(" | SCORE: " +scoreDoc.score); // System.out.println(" | LIMIT: " + limit); uri = document.get("uri"); } else if(limit >=0.7){ // System.out.print("QUERY: " + text); // System.out.print(" | RESULT: " + document.get("entity")); // System.out.println(" | SCORE: " +scoreDoc.score); // System.out.println(" | LIMIT: " + limit); uri = document.get("uri"); } } break; } } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return uri; } private void addDoc(IndexWriter w, String entity, String uri) throws IOException { Document doc = new Document(); doc.add(new TextField("entity", entity, Store.YES)); doc.add(new TextField("uri", uri, Store.YES)); indexWriter.addDocument(doc); } }
963_0
import java.util.ArrayList; import java.util.HashMap; import java.lang.Integer; public class OnlineRoom { private HashMap<Shop, Integer> totalLikes; private HashMap<Shop, Integer> totalSuperLikes; private CategoryList totalCategories; private ArrayList<String> roomCustomers; private Order finalOrder; public void mergeLikes(ArrayList<Shop> newLikes){ //Προσθέτει 1 like σε κάθε μαγαζί μέσα στο totalLikes που υπάρχει στο newLikes for (int i=0; i< newLikes.size();i++) { Shop key = newLikes.get(i); if (this.totalLikes.containsKey(key)) { Integer previousLikes = this.totalLikes.get(key); //this.totalLikes.replace(key, Integer(previousLikes.intValue()+1)); } else { //this.totalLikes.put(newLikes.get(i), Integer(1)); } } } }
iloudaros/nomnomr
code/app/src/main/java/OnlineRoom.java
267
//Προσθέτει 1 like σε κάθε μαγαζί μέσα στο totalLikes που υπάρχει στο newLikes
line_comment
el
import java.util.ArrayList; import java.util.HashMap; import java.lang.Integer; public class OnlineRoom { private HashMap<Shop, Integer> totalLikes; private HashMap<Shop, Integer> totalSuperLikes; private CategoryList totalCategories; private ArrayList<String> roomCustomers; private Order finalOrder; public void mergeLikes(ArrayList<Shop> newLikes){ //Προσθέτει 1<SUF> for (int i=0; i< newLikes.size();i++) { Shop key = newLikes.get(i); if (this.totalLikes.containsKey(key)) { Integer previousLikes = this.totalLikes.get(key); //this.totalLikes.replace(key, Integer(previousLikes.intValue()+1)); } else { //this.totalLikes.put(newLikes.get(i), Integer(1)); } } } }
5001_1
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Ένα παιχνίδι με τον Φασκωλόμυς που χάφτει φύλλα. * * @author Ευστάθιος Ιωσηφίδης, Ελένη Κάλφα * @version 0.1 */ public class WombatWorld extends World { /** * Constructor for objects of class WombatWorld. * */ public WombatWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(600, 400, 1); Wombat arkoudaki = new Wombat(); addObject(arkoudaki,100,100); Leaf fillo=new Leaf(); addObject(fillo,200,200); Leaf fillo1=new Leaf(); addObject(fillo1,443,160); Leaf fillo2=new Leaf(); addObject(fillo2,398,335); } }
iosifidis/EPAL
ΔΠ/Εργαστηριακά μαθήματα/Ειδικά θέματα στον προγραμματισμό/Wombats/WombatWorld.java
310
/** * Ένα παιχνίδι με τον Φασκωλόμυς που χάφτει φύλλα. * * @author Ευστάθιος Ιωσηφίδης, Ελένη Κάλφα * @version 0.1 */
block_comment
el
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Ένα παιχνίδι με<SUF>*/ public class WombatWorld extends World { /** * Constructor for objects of class WombatWorld. * */ public WombatWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(600, 400, 1); Wombat arkoudaki = new Wombat(); addObject(arkoudaki,100,100); Leaf fillo=new Leaf(); addObject(fillo,200,200); Leaf fillo1=new Leaf(); addObject(fillo1,443,160); Leaf fillo2=new Leaf(); addObject(fillo2,398,335); } }
1293_30
// Φοιτητής: Ευστάθιος Ιωσηφίδης // ΑΜ: iis21027 // Άδεια χρήσης: GNU General Public License v3.0 // Use UTF-8 encoding to view the comments import java.util.ArrayList; public class Registry { //Δημιουργία λιστών private ArrayList<Communication> allCommunications = new ArrayList<Communication>(); // Λίστα με όλες τις επικοινωνίες (τηλέφωνο/SMS) private ArrayList<Suspect> allSuspects = new ArrayList<Suspect>(); //Λίστα με όλους τους υπόπτους //Μέθοδος προσθήκης υπόπτου στην λίστα όλων των υπόπτων public void addSuspect(Suspect aSuspect) { allSuspects.add(aSuspect); } //Μέθοδος προσθήκης εγγραφής επικοινωνίας public void addCommunication(Communication aCommunication) { allCommunications.add(aCommunication); for(int i=0;i<allSuspects.size();i++) { //Αναζήτηση εάν ποιος έχει στην λίστα του το πρώτο νούμερο (num1) if(allSuspects.get(i).getListOfNumbers().contains(aCommunication.num1)) { // Να ανατρέξει την λίστα υπόπτων for(int j=0;j<allSuspects.size();j++) { // Αναζήτηση ποιος έχει στην λίστα του το δεύτερο νούμερο (num2) if(allSuspects.get(j).getListOfNumbers().contains(aCommunication.num2)) { //Ενημέρωση της λίστας των συνεργατών allSuspects.get(j).getListOfAssociates().add(allSuspects.get(i)); allSuspects.get(i).getListOfAssociates().add(allSuspects.get(j)); } } } } } //Μέθοδος για λήψη υπόπτου με τους περισσότερους πιθανούς συνεργάτες public Suspect getSuspectWithMostPartners() { // Δήλωση μεταβλητών εντός μεθόδου int tempMax=0; int top=0; //Ανατρέχω την λίστα όλων των υπόπτων for(int i=0;i<allSuspects.size();i++) //Όσοι είναι οι πιθανοί συνεργάτες του allSuspects.get(i) for(int j=0;j<allSuspects.get(i).getListOfAssociates().size();j++) { //Έλεγχος με τον προσωρινό μέγα ύποπτο if(allSuspects.get(i).getListOfAssociates().size() > tempMax) { //Ανάθεση του νέου μέγα υπόπτου tempMax = allSuspects.get(i).getListOfAssociates().size(); top=i; } } //Επιστροφή υπόπτου με τους περισσότερους πιθανούς συνεργάτες return allSuspects.get(top); } //Μέθοδος επιστροφής κλήσης με την μεγαλύτερη διάρκεια public PhoneCall getLongestPhoneCallBetween(String number1, String number2) { // Δήλωση μεταβλητών-αναφορών-αντικειμένων εντός μεθόδου int tempMax=0; PhoneCall maxDuration = null; //Ανατρέχουμε την allCommunications for(Communication c : allCommunications) { //Έλεγχος αν είναι κλήση if(c instanceof PhoneCall) { PhoneCall phoneCall = (PhoneCall) c; //Ρητή μετατροπή σε κλήση if(phoneCall.num1.equals(number1) && phoneCall.num2.equals(number2)) { //Έλεγχος αν η διάρκεια της επικοινωνίας είναι μεγαλύτερη από την τρέχουσα μέγιστη if(phoneCall.getCallDuration() > tempMax) { //Να αποθηκευτεί η μέγιστη διάρκεια ως τρέχουσα μέγιστη tempMax = phoneCall.getCallDuration(); maxDuration = phoneCall; } } } } // Επιστροφή της διάρκειας return maxDuration; } //Μέθοδος που επιστρέφει μηνύματα που μεταξύ τους που περιέχουν κακές λέξεις public ArrayList<SMS> getMessagesBetween(String number1, String number2) { // Δήλωση μεταβλητών-αναφορών-αντικειμένων-δομών εντός μεθόδου String tempMessage = ""; ArrayList<SMS> sms = new ArrayList<SMS>(); //Ανατρέχουμε την allCommunications for(Communication c : allCommunications) { // Ελέγχουμε αν είναι SMS if(c instanceof SMS) { SMS Sms = (SMS) c; //Ρητή μετατροπή σε SMS if(Sms.num1.equals(number1) && Sms.num2.equals(number2)) { //Έλεγχος ύπαρξης κακών λέξεων if(Sms.getSMS().contains("Bomb") || Sms.getSMS().contains("Attack") || Sms.getSMS().contains("Explosives") || Sms.getSMS().contains("Gun")) { //Να αποθηκευτεί το ελεχθέν SMS ως τρέχον SMS tempMessage = Sms.getSMS(); //Προσθήκη στην ArrayList sms sms.add(Sms); } } } } //Επιστροφή του SMS return sms; } public ArrayList<Suspect> getSuspects() { return allSuspects; } }
iosifidis/UoM-Applied-Informatics
s3/object_oriented_programming/assignments/4.CrimeNet-Graph/src/Registry.java
2,144
//Ρητή μετατροπή σε SMS
line_comment
el
// Φοιτητής: Ευστάθιος Ιωσηφίδης // ΑΜ: iis21027 // Άδεια χρήσης: GNU General Public License v3.0 // Use UTF-8 encoding to view the comments import java.util.ArrayList; public class Registry { //Δημιουργία λιστών private ArrayList<Communication> allCommunications = new ArrayList<Communication>(); // Λίστα με όλες τις επικοινωνίες (τηλέφωνο/SMS) private ArrayList<Suspect> allSuspects = new ArrayList<Suspect>(); //Λίστα με όλους τους υπόπτους //Μέθοδος προσθήκης υπόπτου στην λίστα όλων των υπόπτων public void addSuspect(Suspect aSuspect) { allSuspects.add(aSuspect); } //Μέθοδος προσθήκης εγγραφής επικοινωνίας public void addCommunication(Communication aCommunication) { allCommunications.add(aCommunication); for(int i=0;i<allSuspects.size();i++) { //Αναζήτηση εάν ποιος έχει στην λίστα του το πρώτο νούμερο (num1) if(allSuspects.get(i).getListOfNumbers().contains(aCommunication.num1)) { // Να ανατρέξει την λίστα υπόπτων for(int j=0;j<allSuspects.size();j++) { // Αναζήτηση ποιος έχει στην λίστα του το δεύτερο νούμερο (num2) if(allSuspects.get(j).getListOfNumbers().contains(aCommunication.num2)) { //Ενημέρωση της λίστας των συνεργατών allSuspects.get(j).getListOfAssociates().add(allSuspects.get(i)); allSuspects.get(i).getListOfAssociates().add(allSuspects.get(j)); } } } } } //Μέθοδος για λήψη υπόπτου με τους περισσότερους πιθανούς συνεργάτες public Suspect getSuspectWithMostPartners() { // Δήλωση μεταβλητών εντός μεθόδου int tempMax=0; int top=0; //Ανατρέχω την λίστα όλων των υπόπτων for(int i=0;i<allSuspects.size();i++) //Όσοι είναι οι πιθανοί συνεργάτες του allSuspects.get(i) for(int j=0;j<allSuspects.get(i).getListOfAssociates().size();j++) { //Έλεγχος με τον προσωρινό μέγα ύποπτο if(allSuspects.get(i).getListOfAssociates().size() > tempMax) { //Ανάθεση του νέου μέγα υπόπτου tempMax = allSuspects.get(i).getListOfAssociates().size(); top=i; } } //Επιστροφή υπόπτου με τους περισσότερους πιθανούς συνεργάτες return allSuspects.get(top); } //Μέθοδος επιστροφής κλήσης με την μεγαλύτερη διάρκεια public PhoneCall getLongestPhoneCallBetween(String number1, String number2) { // Δήλωση μεταβλητών-αναφορών-αντικειμένων εντός μεθόδου int tempMax=0; PhoneCall maxDuration = null; //Ανατρέχουμε την allCommunications for(Communication c : allCommunications) { //Έλεγχος αν είναι κλήση if(c instanceof PhoneCall) { PhoneCall phoneCall = (PhoneCall) c; //Ρητή μετατροπή σε κλήση if(phoneCall.num1.equals(number1) && phoneCall.num2.equals(number2)) { //Έλεγχος αν η διάρκεια της επικοινωνίας είναι μεγαλύτερη από την τρέχουσα μέγιστη if(phoneCall.getCallDuration() > tempMax) { //Να αποθηκευτεί η μέγιστη διάρκεια ως τρέχουσα μέγιστη tempMax = phoneCall.getCallDuration(); maxDuration = phoneCall; } } } } // Επιστροφή της διάρκειας return maxDuration; } //Μέθοδος που επιστρέφει μηνύματα που μεταξύ τους που περιέχουν κακές λέξεις public ArrayList<SMS> getMessagesBetween(String number1, String number2) { // Δήλωση μεταβλητών-αναφορών-αντικειμένων-δομών εντός μεθόδου String tempMessage = ""; ArrayList<SMS> sms = new ArrayList<SMS>(); //Ανατρέχουμε την allCommunications for(Communication c : allCommunications) { // Ελέγχουμε αν είναι SMS if(c instanceof SMS) { SMS Sms = (SMS) c; //Ρητή μετατροπή<SUF> if(Sms.num1.equals(number1) && Sms.num2.equals(number2)) { //Έλεγχος ύπαρξης κακών λέξεων if(Sms.getSMS().contains("Bomb") || Sms.getSMS().contains("Attack") || Sms.getSMS().contains("Explosives") || Sms.getSMS().contains("Gun")) { //Να αποθηκευτεί το ελεχθέν SMS ως τρέχον SMS tempMessage = Sms.getSMS(); //Προσθήκη στην ArrayList sms sms.add(Sms); } } } } //Επιστροφή του SMS return sms; } public ArrayList<Suspect> getSuspects() { return allSuspects; } }
4979_30
/* * Copyright 2012-2017 Institute of Computer Science, * Foundation for Research and Technology - Hellas * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved * by the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software distributed * under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and limitations * under the Licence. * * Contact: POBox 1385, Heraklio Crete, GR-700 13 GREECE * Tel:+30-2810-391632 * Fax: +30-2810-391638 * E-mail: [email protected] * http://www.ics.forth.gr/isl * * Authors : Georgios Samaritakis, Konstantina Konsolaki. * * This file is part of the FeXML webapp. */ package gr.forth.ics.isl.fexml; import gr.forth.ics.isl.fexml.utilities.Utils; import gr.forth.ics.isl.fexml.utilities.XMLFragment; import isl.dbms.DBCollection; import isl.dbms.DBFile; import isl.dbms.DBMSException; import isl.dms.DMSException; import isl.dms.file.DMSTag; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringEscapeUtils; import schemareader.Element; import schemareader.SchemaFile; /** * * @author samarita */ public class Query extends BasicServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String result = ""; String xpath = request.getParameter("xpath"); String type = request.getParameter("type"); String vocabulary = request.getParameter("vocabulary"); String facet = request.getParameter("facet"); String childrenParam = request.getParameter("children"); String childrenPathsParam = request.getParameter("childrenPaths"); String lang = request.getParameter("lang"); String value = request.getParameter("value"); String sourceType = request.getParameter("sourceType"); String sourceId = request.getParameter("sourceId"); String sourceXML = request.getParameter("sourceXML"); //Prefix added so that code handles both sps_ and ics_ attribute names... String prefix = request.getParameter("prefix"); if (prefix == null) { prefix = "ics"; } if (lang == null) { lang = "gr"; } if (childrenParam == null) { if (value != null) { //Get xpath+restrictions code xpath = xpath.replaceAll("\\[\\d+\\]", ""); //Person example SchemaFile sch = new SchemaFile(schemaFolder + type + ".xsd"); ArrayList<Element> elements = sch.getElements(xpath); Element el = elements.get(0); HashMap<String, String> res = el.getRestrictions(); //Build result StringBuilder output = new StringBuilder("type=" + el.getType()); if (!res.isEmpty()) { Set<String> keys = res.keySet(); for (String key : keys) { output = output.append("^^^" + key + "=" + res.get(key)); } } result = output.toString(); } else { String id = request.getParameter("id"); if (vocabulary == null) { if (facet == null) { //Links code HashMap<String, String> queryResult = getValueFromAndType(xpath, prefix); if (queryResult == null) { result = ""; } else { String selectedType = type; for (String entityType : queryResult.keySet()) { String valueFromXpath = queryResult.get(entityType); String typeOfValueFromXpath = entityType; if (!typeOfValueFromXpath.equals(type)) { type = typeOfValueFromXpath; } StringBuilder pathCondition = new StringBuilder("["); StringBuilder pathOutput = new StringBuilder(""); valueFromXpath = calculateInlineValues(valueFromXpath, sourceType, sourceId, sourceXML); //Experimental:Changed pathOutput from // to / (Zominthos) if (valueFromXpath.contains(",")) { String[] paths = valueFromXpath.split(","); pathOutput = pathOutput.append("concat($i/"); for (String path : paths) { if (!path.endsWith("]")) {//add [1] tp avoid cardinality issues path = path + "[1]"; } pathCondition = pathCondition.append(path).append("!='' or"); pathOutput = pathOutput.append(path.trim()).append("/string(),', ',$i/"); } pathCondition = pathCondition.replace(pathCondition.length() - 2, pathCondition.length(), "]"); pathOutput = pathOutput.replace(pathOutput.length() - 9, pathOutput.length(), ")");//was 10 with // } else { pathCondition = pathCondition.append(valueFromXpath).append("!='']"); pathOutput = pathOutput.append("$i/").append(valueFromXpath).append("/string()"); } DBCollection dbc = new DBCollection(BasicServlet.DBURI, applicationCollection + "/" + type, BasicServlet.DBuser, BasicServlet.DBpassword); String digitalPath = ""; try { digitalPath = "/" + DMSTag.valueOf("xpath", "upload", type, Query.conf)[0] + "/text()"; //exume valei sto DMSTags.xml ths exist ena neo element upload sta pedia pu xreiazetai na vazume to type sto admin part } catch (DMSException ex) { } catch (ArrayIndexOutOfBoundsException e) { } String query = "let $col := collection('" + applicationCollection + "/" + type + "')" + pathCondition + "[.//lang='" + lang + "']" + "\nreturn" + "\n<select id='" + xpath + "'>" // + "\n<option value='----------" + type + "----------' data-id='0' data-type='" + type + "'>----------" + type + "----------</option>" + "\n<option value='--------------------' data-id='0' data-type='" + type + "'>--------------------</option>" + "\n<optgroup label='" + type + "'>" + "\n{for $i in $col" + "\nlet $name := " + pathOutput + "\nlet $imagePath := encode-for-uri($i" + digitalPath + ")" // + "\nlet $imagePath := $i//Οντότητα/ΨηφιακόΑντίγραφοΟντότητα/ΨηφιακόΑρχείο/string()" + "\nlet $id := $i//admin/id/string()" + "\nlet $uri := concat('.../',substring-after($i//admin/uri_id,'" + URI_Reference_Path + "'),', ')" + "\norder by $name collation '?lang=el-gr'" + "\nreturn"; String returnBlock = "\n<option value='{$uri}{$name}' data-id='{$id}' image-path='{$imagePath}' data-type='" + type + "'>{$uri}{$name}</option>}"; if (selectedType.equals(type)) { returnBlock = "\nif ($id='" + id + "') then" + "\n<option value='{$uri}{$name}' selected='' data-id='{$id}' image-path='{$imagePath}' data-type='" + type + "'>{$uri}{$name}</option>" + "\nelse" + "\n<option value='{$uri}{$name}' data-id='{$id}' image-path='{$imagePath}' data-type='" + type + "'>{$uri}{$name}</option>}"; } returnBlock = returnBlock + "\n</optgroup>" + "\n</select>"; query = query + returnBlock; // System.out.println(query); result = result + dbc.query(query)[0]; } result = result.replaceAll("(?s)</select><select[^>]+>[^<]+.*?(?=<optgroup)", ""); // System.out.println(result); } } else {//Facet code String facetProps = getFacetProperties(xpath, prefix); Utils utils = new Utils(); String themasURL = utils.getMatch(facetProps, "(?<=themasUrl=\")[^\"]*(?=\")"); String username = utils.getMatch(facetProps, "(?<=username=\")[^\"]*(?=\")"); String thesaurusName = utils.getMatch(facetProps, "(?<=thesaurusName=\")[^\"]*(?=\")"); String facetId = utils.getMatch(facetProps, "(?<=facetId=\")[^\"]*(?=\")"); // System.out.println("FACET ID is:" + facetId); if (!facetId.equals("")) { String facetURLpart = ""; if (facetId.contains("_")) {//multiple facets String[] facets = facetId.split("_"); for (String fac : facets) { facetURLpart = facetURLpart + "&input_term=topterm&op_term=refid=&inputvalue_term=" + fac; } } else { facetURLpart = "&input_term=topterm&op_term=refid=&inputvalue_term=" + facetId; } String urlEnd = "&external_user=" + username + "&external_thesaurus=" + thesaurusName; String serviceURL = themasURL + "SearchResults_Terms?updateTermCriteria=parseCriteria" + "&answerType=XMLSTREAM&pageFirstResult=SaveAll" + "&operator_term=or&output_term1=name" + urlEnd + facetURLpart; String themasServiceResponse = utils.consumeService(serviceURL); if (themasServiceResponse.contains("<terms count=\"0\">")) {//Hierarchy, not facet, should call service again System.out.println("IT'S A HIERARCHY!"); serviceURL = themasURL + "SearchResults_Terms?updateTermCriteria=parseCriteria" + "&answerType=XMLSTREAM&pageFirstResult=SaveAll" + "&operator_term=or&output_term1=name" + urlEnd + facetURLpart; themasServiceResponse = utils.consumeService(serviceURL); } // System.out.println(serviceURL); if (themasServiceResponse.length() > 0) { XMLFragment xml = new XMLFragment(themasServiceResponse); ArrayList<String> terms = xml.query("//term/descriptor/text()"); ArrayList<String> Ids = xml.query("//term/descriptor/@referenceId"); StringBuilder selectBlock = new StringBuilder(" <select id='" + xpath + "' data-thesaurusName='" + thesaurusName + "' data-username='" + username + "' data-themasURL='" + themasURL + "' data-facet='" + facetId + "'>"); selectBlock.append("<option value='-------------------' data-id='0'>-------------------</option>"); for (int i = 0; i < terms.size(); i++) { if (Ids.get(i).equals(id)) { selectBlock.append("<option selected='' value='" + terms.get(i) + "' data-id='" + Ids.get(i) + "'>" + terms.get(i) + "</option>"); } else { selectBlock.append("<option value='" + terms.get(i) + "' data-id='" + Ids.get(i) + "'>" + terms.get(i) + "</option>"); } } selectBlock.append("</select>"); result = selectBlock.toString(); } else { result = "No facet found!"; } } } } else { //Vocabulary code if (vocabulary.equals("")) { vocabulary = getVocabulary(xpath, prefix); } if (vocabulary == null || vocabulary.equals("")) { result = "No vocab found!"; } else { DBFile dbf; String parentName = ""; String childName = ""; try { dbf = new DBFile(BasicServlet.DBURI, applicationCollection + "/Vocabulary/" + lang, vocabulary, BasicServlet.DBuser, BasicServlet.DBpassword); parentName = dbf.query("//name(/*)")[0].toString(); childName = dbf.query("//name(/" + parentName + "/*[1])")[0].toString(); } catch (DBMSException ex) { DBCollection vocabCol = new DBCollection(BasicServlet.DBURI, applicationCollection + "/Vocabulary/" + lang, BasicServlet.DBuser, BasicServlet.DBpassword); String randomFileName = vocabCol.listFiles()[0]; DBFile randomFile = vocabCol.getFile(randomFileName); dbf = vocabCol.createFile(vocabulary, "XMLDBFile"); parentName = randomFile.query("//name(/*)")[0].toString(); childName = randomFile.query("//name(/" + parentName + "/*[1])")[0].toString(); dbf.setXMLAsString("<" + parentName + "><" + childName + " id='0'>-------------------</" + childName + "></" + parentName + ">"); dbf.store(); } String query = "let $voc := doc('" + applicationCollection + "/Vocabulary/" + lang + "/" + vocabulary + "')" + "\nreturn" + "\n<select id='" + xpath + "' data-vocabulary='" + vocabulary + "'>" + "\n{for $i in $voc//" + childName + "\norder by $i collation '?lang=el-gr'" + "\nreturn" + "\nif ($i/@id='" + id + "') then" + "\n<option value='{$i/string()}' selected='' data-id='{$i/@id}'>{$i/string()}</option>" + "\nelse" + "\n<option value='{$i/string()}' data-id='{$i/@id}'>{$i/string()}</option>}" + "\n</select>"; result = dbf.queryString(query)[0]; } } } } else { //Schema add/remove code //For now remove position info from xpath xpath = xpath.replaceAll("\\[\\d+\\]", ""); xpath = detectRecursion(xpath); //to solve recursion problem String[] children = null; children = childrenParam.split("___"); String[] childrenPaths = null; if (childrenPathsParam != null) { childrenPaths = childrenPathsParam.split("___"); } ArrayList childrenList = new ArrayList(Arrays.asList(children)); ArrayList childrenPathsList = new ArrayList(Arrays.asList(childrenPaths)); SchemaFile sch = new SchemaFile(schemaFolder + type + ".xsd"); ArrayList<Element> elements = sch.getElements(xpath); ArrayList<String> schemaChildren = new ArrayList<String>(); ArrayList<String> mayAdd = new ArrayList<String>(); ArrayList<String> mayRemove = childrenList; ArrayList<String> mayRemovePaths = childrenPathsList; StringBuffer output = new StringBuffer(""); String verdict = ""; for (Element el : elements) { if (el != null) { if (el.getFullPath().equals(xpath + "/" + el.getName())) { schemaChildren.add(el.getName()); int occurs = Collections.frequency(childrenList, el.getName()); if (el.getInfo().startsWith("Choice")) { int choiceMinOccurs = Integer.parseInt(el.getInfo().split("_")[1]); int choiceMaxOccurs = Integer.parseInt(el.getInfo().split("_")[2]); int actualMinOccurs = el.getMinOccurs(); if (actualMinOccurs > 0) { if (choiceMinOccurs < el.getMinOccurs()) { actualMinOccurs = choiceMinOccurs; } } int actualMaxOccurs = el.getMaxOccurs(); if (actualMinOccurs != -1) { if (choiceMaxOccurs == -1 || choiceMaxOccurs > actualMaxOccurs) { actualMaxOccurs = choiceMaxOccurs; } } String actualMaxOccursAsString = "" + actualMaxOccurs; if (actualMaxOccurs == -1) { actualMaxOccursAsString = "∞"; } StringBuilder actions = new StringBuilder("ACTIONS:"); if (actualMaxOccurs == -1 || occurs < actualMaxOccurs) { actions = actions.append(" + "); mayAdd.add(el.getName()); } if (occurs > actualMinOccurs) { actions = actions.append(" X "); } else { while (mayRemove.contains(el.getName())) { mayRemovePaths.remove(mayRemove.indexOf(el.getName())); mayRemove.remove(el.getName()); } } verdict = "Element: " + el.getName() + " ## Εμφανίσεις: " + occurs + " ## Επιτρεπτές(" + actualMinOccurs + "," + actualMaxOccursAsString + ") " + actions + " ή "; } else { if (output.length() > 0) { String lastChar = "" + output.charAt(output.length() - 2); if (lastChar.equals("ή")) { output = output.replace(output.length() - 2, output.length(), "\n"); } } String maxOccurs = "" + el.getMaxOccurs(); if (el.getMaxOccurs() == -1) { maxOccurs = "∞"; } StringBuilder actions = new StringBuilder("ACTIONS:"); if (el.getMaxOccurs() == -1 || occurs < el.getMaxOccurs()) { actions = actions.append(" + "); mayAdd.add(el.getName()); } if (occurs > el.getMinOccurs()) { actions = actions.append(" X "); } else { while (mayRemove.contains(el.getName())) { mayRemovePaths.remove(mayRemove.indexOf(el.getName())); mayRemove.remove(el.getName()); } } verdict = "Element: " + el.getName() + " ## Εμφανίσεις: " + occurs + " ## Επιτρεπτές(" + el.getMinOccurs() + "," + maxOccurs + ") " + actions + "\n"; } } } } output.append("<select id='add' style='margin-left:3px;' >"); for (String addElem : mayAdd) { if (!addElem.equals("admin")) { String fullPath = xpath + "/" + addElem; fullPath = detectRecursion(fullPath); //to solve recursion problem if (isVisibleFromXPath(type, fullPath, lang)) {//May only add if element is visible, otherwise no point... String label = getLabelFromXPath(type, fullPath, lang); if (label == null || label.equals("")) { label = "(" + addElem + ")"; } String tree = sch.createXMLSubtree(fullPath, "minimum"); System.out.println(tree); String encodedTree = StringEscapeUtils.escapeXml(tree); output.append("<option data-schemaName='").append(addElem).append("' value='").append(encodedTree).append("'>").append(label).append("</option>"); } } } output.append("</select>^^^"); //ΙΕ bad hack... output.append("<select id='remove' style='margin-left:3px;' >"); for (int i = 0; i < mayRemove.size(); i++) { String removeElem = mayRemove.get(i); if (!removeElem.equals("admin") && !removeElem.equals("")) { String removeElemPath = mayRemovePaths.get(i); String position = ""; if (removeElemPath.endsWith("]")) { position = removeElemPath.substring(removeElemPath.lastIndexOf("[")); } String label = getLabelFromXPath(type, mayRemovePaths.get(i), lang); if (label == null || label.equals("")) { label = "(" + removeElem + ")"; } output.append("<option value='").append(removeElemPath).append("'>").append(label).append(position).append("</option>"); } } output.append("</select>^^^<input type='hidden' id='schemaChildren' value='"); for (int i = 0; i < schemaChildren.size(); i++) { if (i == schemaChildren.size() - 1) { output.append(schemaChildren.get(i)); } else { output.append(schemaChildren.get(i)).append("___"); } } output.append("'/>"); result = output.toString(); } try { /* * TODO output your page here */ out.println(result); } finally { out.close(); } } private String detectRecursion(String xpath) { String[] pathComponents = xpath.split("/"); String path = ""; for (String pathComponent : pathComponents) { if (path.isEmpty()) { path = path + "/" + pathComponent + "/"; } else { if (!path.contains("/" + pathComponent + "/")) { path = path + pathComponent + "/"; } else { int index = path.indexOf("/" + pathComponent + "/") + pathComponent.length() + 2; path = path.substring(0, index); } } } return path.substring(1, path.length() - 1); } private HashMap<String, String> getValueFromAndType(String xpath, String prefix) { HashMap<String, String> result = new HashMap<String, String>(); DBCollection nodesCol = new DBCollection(BasicServlet.DBURI, applicationCollection + "/LaAndLi", BasicServlet.DBuser, BasicServlet.DBpassword); xpath = xpath.replaceAll("\\[\\d++\\]", ""); //Should be only one String[] valuesFromTable = nodesCol.query("//node[xpath='" + xpath + "']/valueFrom[.!='']/string()"); String linkToType = ""; String linkToPath = ""; //If no info in LaAndLi collection, then try querying legacy data if (valuesFromTable == null || valuesFromTable.length == 0) { DBCollection rootCol = new DBCollection(BasicServlet.DBURI, applicationCollection, BasicServlet.DBuser, BasicServlet.DBpassword); String[] typeTable = rootCol.query("//" + xpath + "/@" + prefix + "_type[.!='']/string()"); if (typeTable != null && typeTable.length > 0) { String type = typeTable[0]; if (type.equals("AP")) { } else if (type.equals("Archive")) { linkToPath = "Οντότητα/ΑρχειακόΣτοιχείοΟντότητα/Τίτλος"; } else if (type.equals("Bibliography")) { linkToPath = "Οντότητα/ΒιβλιογραφίαΟντότητα/Τίτλος"; } else if (type.equals("DigitalCopy")) { linkToPath = "Οντότητα/ΨηφιακόΑντίγραφοΟντότητα/Τίτλος"; } else if (type.equals("Equipment")) { linkToPath = "Οντότητα/ΕξοπλισμόςΟντότητα/Ονομασία"; } else if (type.equals("Event")) { linkToPath = "Οντότητα/ΣυμβάνΟντότητα/Ονομασία"; } else if (type.equals("KAP")) { } else if (type.equals("Keimena")) { linkToPath = "Οντότητα/ΚείμενοΟντότητα/Τίτλος"; } else if (type.equals("Location")) { linkToPath = "Οντότητα/ΤόποςΟντότητα/Ονομασία"; } else if (type.equals("Martyries")) { linkToPath = "Οντότητα/ΜαρτυρίαΟντότητα/Θέμα"; } else if (type.equals("Material")) { linkToPath = "Οντότητα/ΥλικόΟντότητα/Ονομασία"; } else if (type.equals("Organization")) { linkToPath = "Οντότητα/ΟργανισμόςΟντότητα/Επωνυμία"; } else if (type.equals("Part")) { linkToPath = "Οντότητα/ΤμήμαΟντότητα/Ονομασία"; } else if (type.equals("Person")) { linkToPath = "Οντότητα/ΠρόσωποΟντότητα/Ονοματεπώνυμο"; } if (linkToPath != null) { nodesCol.xUpdate("//node[xpath='" + xpath + "']/valueFrom", linkToPath); } } } String uniqueXpath = ""; if (valuesFromTable != null) { for (String valueFromTable : valuesFromTable) { linkToPath = valueFromTable; if (linkToPath.contains(",")) { uniqueXpath = linkToPath.split(",")[0]; } else { uniqueXpath = linkToPath; } //Added next line in case I use [1] etc...e.g. Συγγραφέας σε Βιβλιογραφία... uniqueXpath = uniqueXpath.replaceAll("\\[\\d++\\]", ""); uniqueXpath = uniqueXpath.replaceAll("\\[.*\\]", ""); // System.out.println("2="+uniqueXpath); String[] typeOfvaluesFromTable = nodesCol.query("//node[xpath='" + uniqueXpath + "']/@type/string()"); if (typeOfvaluesFromTable != null && typeOfvaluesFromTable.length > 0) { result.put(typeOfvaluesFromTable[0], linkToPath); } } } return result; } private String calculateInlineValues(String paths, String sourceType, String sourceId, String sourceXML) { ArrayList<String> inlinePaths = findReg("\\{\\{.*?\\}\\}", paths, 0); for (String inPath : inlinePaths) { String modifiedPath = "//" + inPath.substring(2, inPath.length() - 2) + "/string()"; DBCollection dbc = new DBCollection(BasicServlet.DBURI, applicationCollection + "/Temp", BasicServlet.DBuser, BasicServlet.DBpassword); DBFile dbf = dbc.createFile(sourceType + sourceId + ".xml", "XMLDBFile"); dbf.setXMLAsString(sourceXML); dbf.store(); String[] res = dbf.queryString(modifiedPath); String actualValue = ""; if (res != null && res.length > 0) { actualValue = res[0]; } paths = paths.replace(inPath, actualValue); dbf.remove(); } return paths; } private String getVocabulary(String xpath, String prefix) { DBCollection nodesCol = new DBCollection(BasicServlet.DBURI, applicationCollection + "/LaAndLi", BasicServlet.DBuser, BasicServlet.DBpassword); xpath = xpath.replaceAll("\\[\\d++\\]", ""); //Should be only one String[] vocabsTable = nodesCol.query("//node[xpath='" + xpath + "']/vocabulary[.!='']/string()"); if (vocabsTable == null || vocabsTable.length == 0) { //If no info in LaAndLi collection, then try querying legacy data DBCollection rootCol = new DBCollection(BasicServlet.DBURI, applicationCollection, BasicServlet.DBuser, BasicServlet.DBpassword); vocabsTable = rootCol.query("//" + xpath + "/@" + prefix + "_vocabulary/string()"); if (vocabsTable != null && vocabsTable.length > 0) { nodesCol.xUpdate("//node[xpath='" + xpath + "']/vocabulary", vocabsTable[0]); } } if (vocabsTable != null && vocabsTable.length > 0) { return vocabsTable[0]; } else { return null; } } private String getFacetProperties(String xpath, String prefix) { DBCollection nodesCol = new DBCollection(BasicServlet.DBURI, applicationCollection + "/LaAndLi", BasicServlet.DBuser, BasicServlet.DBpassword); xpath = xpath.replaceAll("\\[\\d++\\]", ""); //Should be only one? String[] facetsTable = nodesCol.query("//node[xpath='" + xpath + "']/facet"); if (facetsTable == null || facetsTable.length == 0) { //If no info in LaAndLi collection, then try querying legacy data //TO CHECK DBCollection rootCol = new DBCollection(BasicServlet.DBURI, applicationCollection, BasicServlet.DBuser, BasicServlet.DBpassword); facetsTable = rootCol.query("//" + xpath + "/@" + prefix + "_facet"); if (facetsTable != null && facetsTable.length > 0) { System.out.println("XPATH=" + xpath); System.out.println("FT[0]=" + facetsTable[0]); // nodesCol.xUpdate("//node[xpath='" + xpath + "']/facet", facetsTable[0]); } } if (facetsTable != null && facetsTable.length > 0) { return facetsTable[0]; } else { return null; } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
isl/FeXML
src/main/java/gr/forth/ics/isl/fexml/Query.java
7,595
//Added next line in case I use [1] etc...e.g. Συγγραφέας σε Βιβλιογραφία...
line_comment
el
/* * Copyright 2012-2017 Institute of Computer Science, * Foundation for Research and Technology - Hellas * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved * by the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software distributed * under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and limitations * under the Licence. * * Contact: POBox 1385, Heraklio Crete, GR-700 13 GREECE * Tel:+30-2810-391632 * Fax: +30-2810-391638 * E-mail: [email protected] * http://www.ics.forth.gr/isl * * Authors : Georgios Samaritakis, Konstantina Konsolaki. * * This file is part of the FeXML webapp. */ package gr.forth.ics.isl.fexml; import gr.forth.ics.isl.fexml.utilities.Utils; import gr.forth.ics.isl.fexml.utilities.XMLFragment; import isl.dbms.DBCollection; import isl.dbms.DBFile; import isl.dbms.DBMSException; import isl.dms.DMSException; import isl.dms.file.DMSTag; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringEscapeUtils; import schemareader.Element; import schemareader.SchemaFile; /** * * @author samarita */ public class Query extends BasicServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String result = ""; String xpath = request.getParameter("xpath"); String type = request.getParameter("type"); String vocabulary = request.getParameter("vocabulary"); String facet = request.getParameter("facet"); String childrenParam = request.getParameter("children"); String childrenPathsParam = request.getParameter("childrenPaths"); String lang = request.getParameter("lang"); String value = request.getParameter("value"); String sourceType = request.getParameter("sourceType"); String sourceId = request.getParameter("sourceId"); String sourceXML = request.getParameter("sourceXML"); //Prefix added so that code handles both sps_ and ics_ attribute names... String prefix = request.getParameter("prefix"); if (prefix == null) { prefix = "ics"; } if (lang == null) { lang = "gr"; } if (childrenParam == null) { if (value != null) { //Get xpath+restrictions code xpath = xpath.replaceAll("\\[\\d+\\]", ""); //Person example SchemaFile sch = new SchemaFile(schemaFolder + type + ".xsd"); ArrayList<Element> elements = sch.getElements(xpath); Element el = elements.get(0); HashMap<String, String> res = el.getRestrictions(); //Build result StringBuilder output = new StringBuilder("type=" + el.getType()); if (!res.isEmpty()) { Set<String> keys = res.keySet(); for (String key : keys) { output = output.append("^^^" + key + "=" + res.get(key)); } } result = output.toString(); } else { String id = request.getParameter("id"); if (vocabulary == null) { if (facet == null) { //Links code HashMap<String, String> queryResult = getValueFromAndType(xpath, prefix); if (queryResult == null) { result = ""; } else { String selectedType = type; for (String entityType : queryResult.keySet()) { String valueFromXpath = queryResult.get(entityType); String typeOfValueFromXpath = entityType; if (!typeOfValueFromXpath.equals(type)) { type = typeOfValueFromXpath; } StringBuilder pathCondition = new StringBuilder("["); StringBuilder pathOutput = new StringBuilder(""); valueFromXpath = calculateInlineValues(valueFromXpath, sourceType, sourceId, sourceXML); //Experimental:Changed pathOutput from // to / (Zominthos) if (valueFromXpath.contains(",")) { String[] paths = valueFromXpath.split(","); pathOutput = pathOutput.append("concat($i/"); for (String path : paths) { if (!path.endsWith("]")) {//add [1] tp avoid cardinality issues path = path + "[1]"; } pathCondition = pathCondition.append(path).append("!='' or"); pathOutput = pathOutput.append(path.trim()).append("/string(),', ',$i/"); } pathCondition = pathCondition.replace(pathCondition.length() - 2, pathCondition.length(), "]"); pathOutput = pathOutput.replace(pathOutput.length() - 9, pathOutput.length(), ")");//was 10 with // } else { pathCondition = pathCondition.append(valueFromXpath).append("!='']"); pathOutput = pathOutput.append("$i/").append(valueFromXpath).append("/string()"); } DBCollection dbc = new DBCollection(BasicServlet.DBURI, applicationCollection + "/" + type, BasicServlet.DBuser, BasicServlet.DBpassword); String digitalPath = ""; try { digitalPath = "/" + DMSTag.valueOf("xpath", "upload", type, Query.conf)[0] + "/text()"; //exume valei sto DMSTags.xml ths exist ena neo element upload sta pedia pu xreiazetai na vazume to type sto admin part } catch (DMSException ex) { } catch (ArrayIndexOutOfBoundsException e) { } String query = "let $col := collection('" + applicationCollection + "/" + type + "')" + pathCondition + "[.//lang='" + lang + "']" + "\nreturn" + "\n<select id='" + xpath + "'>" // + "\n<option value='----------" + type + "----------' data-id='0' data-type='" + type + "'>----------" + type + "----------</option>" + "\n<option value='--------------------' data-id='0' data-type='" + type + "'>--------------------</option>" + "\n<optgroup label='" + type + "'>" + "\n{for $i in $col" + "\nlet $name := " + pathOutput + "\nlet $imagePath := encode-for-uri($i" + digitalPath + ")" // + "\nlet $imagePath := $i//Οντότητα/ΨηφιακόΑντίγραφοΟντότητα/ΨηφιακόΑρχείο/string()" + "\nlet $id := $i//admin/id/string()" + "\nlet $uri := concat('.../',substring-after($i//admin/uri_id,'" + URI_Reference_Path + "'),', ')" + "\norder by $name collation '?lang=el-gr'" + "\nreturn"; String returnBlock = "\n<option value='{$uri}{$name}' data-id='{$id}' image-path='{$imagePath}' data-type='" + type + "'>{$uri}{$name}</option>}"; if (selectedType.equals(type)) { returnBlock = "\nif ($id='" + id + "') then" + "\n<option value='{$uri}{$name}' selected='' data-id='{$id}' image-path='{$imagePath}' data-type='" + type + "'>{$uri}{$name}</option>" + "\nelse" + "\n<option value='{$uri}{$name}' data-id='{$id}' image-path='{$imagePath}' data-type='" + type + "'>{$uri}{$name}</option>}"; } returnBlock = returnBlock + "\n</optgroup>" + "\n</select>"; query = query + returnBlock; // System.out.println(query); result = result + dbc.query(query)[0]; } result = result.replaceAll("(?s)</select><select[^>]+>[^<]+.*?(?=<optgroup)", ""); // System.out.println(result); } } else {//Facet code String facetProps = getFacetProperties(xpath, prefix); Utils utils = new Utils(); String themasURL = utils.getMatch(facetProps, "(?<=themasUrl=\")[^\"]*(?=\")"); String username = utils.getMatch(facetProps, "(?<=username=\")[^\"]*(?=\")"); String thesaurusName = utils.getMatch(facetProps, "(?<=thesaurusName=\")[^\"]*(?=\")"); String facetId = utils.getMatch(facetProps, "(?<=facetId=\")[^\"]*(?=\")"); // System.out.println("FACET ID is:" + facetId); if (!facetId.equals("")) { String facetURLpart = ""; if (facetId.contains("_")) {//multiple facets String[] facets = facetId.split("_"); for (String fac : facets) { facetURLpart = facetURLpart + "&input_term=topterm&op_term=refid=&inputvalue_term=" + fac; } } else { facetURLpart = "&input_term=topterm&op_term=refid=&inputvalue_term=" + facetId; } String urlEnd = "&external_user=" + username + "&external_thesaurus=" + thesaurusName; String serviceURL = themasURL + "SearchResults_Terms?updateTermCriteria=parseCriteria" + "&answerType=XMLSTREAM&pageFirstResult=SaveAll" + "&operator_term=or&output_term1=name" + urlEnd + facetURLpart; String themasServiceResponse = utils.consumeService(serviceURL); if (themasServiceResponse.contains("<terms count=\"0\">")) {//Hierarchy, not facet, should call service again System.out.println("IT'S A HIERARCHY!"); serviceURL = themasURL + "SearchResults_Terms?updateTermCriteria=parseCriteria" + "&answerType=XMLSTREAM&pageFirstResult=SaveAll" + "&operator_term=or&output_term1=name" + urlEnd + facetURLpart; themasServiceResponse = utils.consumeService(serviceURL); } // System.out.println(serviceURL); if (themasServiceResponse.length() > 0) { XMLFragment xml = new XMLFragment(themasServiceResponse); ArrayList<String> terms = xml.query("//term/descriptor/text()"); ArrayList<String> Ids = xml.query("//term/descriptor/@referenceId"); StringBuilder selectBlock = new StringBuilder(" <select id='" + xpath + "' data-thesaurusName='" + thesaurusName + "' data-username='" + username + "' data-themasURL='" + themasURL + "' data-facet='" + facetId + "'>"); selectBlock.append("<option value='-------------------' data-id='0'>-------------------</option>"); for (int i = 0; i < terms.size(); i++) { if (Ids.get(i).equals(id)) { selectBlock.append("<option selected='' value='" + terms.get(i) + "' data-id='" + Ids.get(i) + "'>" + terms.get(i) + "</option>"); } else { selectBlock.append("<option value='" + terms.get(i) + "' data-id='" + Ids.get(i) + "'>" + terms.get(i) + "</option>"); } } selectBlock.append("</select>"); result = selectBlock.toString(); } else { result = "No facet found!"; } } } } else { //Vocabulary code if (vocabulary.equals("")) { vocabulary = getVocabulary(xpath, prefix); } if (vocabulary == null || vocabulary.equals("")) { result = "No vocab found!"; } else { DBFile dbf; String parentName = ""; String childName = ""; try { dbf = new DBFile(BasicServlet.DBURI, applicationCollection + "/Vocabulary/" + lang, vocabulary, BasicServlet.DBuser, BasicServlet.DBpassword); parentName = dbf.query("//name(/*)")[0].toString(); childName = dbf.query("//name(/" + parentName + "/*[1])")[0].toString(); } catch (DBMSException ex) { DBCollection vocabCol = new DBCollection(BasicServlet.DBURI, applicationCollection + "/Vocabulary/" + lang, BasicServlet.DBuser, BasicServlet.DBpassword); String randomFileName = vocabCol.listFiles()[0]; DBFile randomFile = vocabCol.getFile(randomFileName); dbf = vocabCol.createFile(vocabulary, "XMLDBFile"); parentName = randomFile.query("//name(/*)")[0].toString(); childName = randomFile.query("//name(/" + parentName + "/*[1])")[0].toString(); dbf.setXMLAsString("<" + parentName + "><" + childName + " id='0'>-------------------</" + childName + "></" + parentName + ">"); dbf.store(); } String query = "let $voc := doc('" + applicationCollection + "/Vocabulary/" + lang + "/" + vocabulary + "')" + "\nreturn" + "\n<select id='" + xpath + "' data-vocabulary='" + vocabulary + "'>" + "\n{for $i in $voc//" + childName + "\norder by $i collation '?lang=el-gr'" + "\nreturn" + "\nif ($i/@id='" + id + "') then" + "\n<option value='{$i/string()}' selected='' data-id='{$i/@id}'>{$i/string()}</option>" + "\nelse" + "\n<option value='{$i/string()}' data-id='{$i/@id}'>{$i/string()}</option>}" + "\n</select>"; result = dbf.queryString(query)[0]; } } } } else { //Schema add/remove code //For now remove position info from xpath xpath = xpath.replaceAll("\\[\\d+\\]", ""); xpath = detectRecursion(xpath); //to solve recursion problem String[] children = null; children = childrenParam.split("___"); String[] childrenPaths = null; if (childrenPathsParam != null) { childrenPaths = childrenPathsParam.split("___"); } ArrayList childrenList = new ArrayList(Arrays.asList(children)); ArrayList childrenPathsList = new ArrayList(Arrays.asList(childrenPaths)); SchemaFile sch = new SchemaFile(schemaFolder + type + ".xsd"); ArrayList<Element> elements = sch.getElements(xpath); ArrayList<String> schemaChildren = new ArrayList<String>(); ArrayList<String> mayAdd = new ArrayList<String>(); ArrayList<String> mayRemove = childrenList; ArrayList<String> mayRemovePaths = childrenPathsList; StringBuffer output = new StringBuffer(""); String verdict = ""; for (Element el : elements) { if (el != null) { if (el.getFullPath().equals(xpath + "/" + el.getName())) { schemaChildren.add(el.getName()); int occurs = Collections.frequency(childrenList, el.getName()); if (el.getInfo().startsWith("Choice")) { int choiceMinOccurs = Integer.parseInt(el.getInfo().split("_")[1]); int choiceMaxOccurs = Integer.parseInt(el.getInfo().split("_")[2]); int actualMinOccurs = el.getMinOccurs(); if (actualMinOccurs > 0) { if (choiceMinOccurs < el.getMinOccurs()) { actualMinOccurs = choiceMinOccurs; } } int actualMaxOccurs = el.getMaxOccurs(); if (actualMinOccurs != -1) { if (choiceMaxOccurs == -1 || choiceMaxOccurs > actualMaxOccurs) { actualMaxOccurs = choiceMaxOccurs; } } String actualMaxOccursAsString = "" + actualMaxOccurs; if (actualMaxOccurs == -1) { actualMaxOccursAsString = "∞"; } StringBuilder actions = new StringBuilder("ACTIONS:"); if (actualMaxOccurs == -1 || occurs < actualMaxOccurs) { actions = actions.append(" + "); mayAdd.add(el.getName()); } if (occurs > actualMinOccurs) { actions = actions.append(" X "); } else { while (mayRemove.contains(el.getName())) { mayRemovePaths.remove(mayRemove.indexOf(el.getName())); mayRemove.remove(el.getName()); } } verdict = "Element: " + el.getName() + " ## Εμφανίσεις: " + occurs + " ## Επιτρεπτές(" + actualMinOccurs + "," + actualMaxOccursAsString + ") " + actions + " ή "; } else { if (output.length() > 0) { String lastChar = "" + output.charAt(output.length() - 2); if (lastChar.equals("ή")) { output = output.replace(output.length() - 2, output.length(), "\n"); } } String maxOccurs = "" + el.getMaxOccurs(); if (el.getMaxOccurs() == -1) { maxOccurs = "∞"; } StringBuilder actions = new StringBuilder("ACTIONS:"); if (el.getMaxOccurs() == -1 || occurs < el.getMaxOccurs()) { actions = actions.append(" + "); mayAdd.add(el.getName()); } if (occurs > el.getMinOccurs()) { actions = actions.append(" X "); } else { while (mayRemove.contains(el.getName())) { mayRemovePaths.remove(mayRemove.indexOf(el.getName())); mayRemove.remove(el.getName()); } } verdict = "Element: " + el.getName() + " ## Εμφανίσεις: " + occurs + " ## Επιτρεπτές(" + el.getMinOccurs() + "," + maxOccurs + ") " + actions + "\n"; } } } } output.append("<select id='add' style='margin-left:3px;' >"); for (String addElem : mayAdd) { if (!addElem.equals("admin")) { String fullPath = xpath + "/" + addElem; fullPath = detectRecursion(fullPath); //to solve recursion problem if (isVisibleFromXPath(type, fullPath, lang)) {//May only add if element is visible, otherwise no point... String label = getLabelFromXPath(type, fullPath, lang); if (label == null || label.equals("")) { label = "(" + addElem + ")"; } String tree = sch.createXMLSubtree(fullPath, "minimum"); System.out.println(tree); String encodedTree = StringEscapeUtils.escapeXml(tree); output.append("<option data-schemaName='").append(addElem).append("' value='").append(encodedTree).append("'>").append(label).append("</option>"); } } } output.append("</select>^^^"); //ΙΕ bad hack... output.append("<select id='remove' style='margin-left:3px;' >"); for (int i = 0; i < mayRemove.size(); i++) { String removeElem = mayRemove.get(i); if (!removeElem.equals("admin") && !removeElem.equals("")) { String removeElemPath = mayRemovePaths.get(i); String position = ""; if (removeElemPath.endsWith("]")) { position = removeElemPath.substring(removeElemPath.lastIndexOf("[")); } String label = getLabelFromXPath(type, mayRemovePaths.get(i), lang); if (label == null || label.equals("")) { label = "(" + removeElem + ")"; } output.append("<option value='").append(removeElemPath).append("'>").append(label).append(position).append("</option>"); } } output.append("</select>^^^<input type='hidden' id='schemaChildren' value='"); for (int i = 0; i < schemaChildren.size(); i++) { if (i == schemaChildren.size() - 1) { output.append(schemaChildren.get(i)); } else { output.append(schemaChildren.get(i)).append("___"); } } output.append("'/>"); result = output.toString(); } try { /* * TODO output your page here */ out.println(result); } finally { out.close(); } } private String detectRecursion(String xpath) { String[] pathComponents = xpath.split("/"); String path = ""; for (String pathComponent : pathComponents) { if (path.isEmpty()) { path = path + "/" + pathComponent + "/"; } else { if (!path.contains("/" + pathComponent + "/")) { path = path + pathComponent + "/"; } else { int index = path.indexOf("/" + pathComponent + "/") + pathComponent.length() + 2; path = path.substring(0, index); } } } return path.substring(1, path.length() - 1); } private HashMap<String, String> getValueFromAndType(String xpath, String prefix) { HashMap<String, String> result = new HashMap<String, String>(); DBCollection nodesCol = new DBCollection(BasicServlet.DBURI, applicationCollection + "/LaAndLi", BasicServlet.DBuser, BasicServlet.DBpassword); xpath = xpath.replaceAll("\\[\\d++\\]", ""); //Should be only one String[] valuesFromTable = nodesCol.query("//node[xpath='" + xpath + "']/valueFrom[.!='']/string()"); String linkToType = ""; String linkToPath = ""; //If no info in LaAndLi collection, then try querying legacy data if (valuesFromTable == null || valuesFromTable.length == 0) { DBCollection rootCol = new DBCollection(BasicServlet.DBURI, applicationCollection, BasicServlet.DBuser, BasicServlet.DBpassword); String[] typeTable = rootCol.query("//" + xpath + "/@" + prefix + "_type[.!='']/string()"); if (typeTable != null && typeTable.length > 0) { String type = typeTable[0]; if (type.equals("AP")) { } else if (type.equals("Archive")) { linkToPath = "Οντότητα/ΑρχειακόΣτοιχείοΟντότητα/Τίτλος"; } else if (type.equals("Bibliography")) { linkToPath = "Οντότητα/ΒιβλιογραφίαΟντότητα/Τίτλος"; } else if (type.equals("DigitalCopy")) { linkToPath = "Οντότητα/ΨηφιακόΑντίγραφοΟντότητα/Τίτλος"; } else if (type.equals("Equipment")) { linkToPath = "Οντότητα/ΕξοπλισμόςΟντότητα/Ονομασία"; } else if (type.equals("Event")) { linkToPath = "Οντότητα/ΣυμβάνΟντότητα/Ονομασία"; } else if (type.equals("KAP")) { } else if (type.equals("Keimena")) { linkToPath = "Οντότητα/ΚείμενοΟντότητα/Τίτλος"; } else if (type.equals("Location")) { linkToPath = "Οντότητα/ΤόποςΟντότητα/Ονομασία"; } else if (type.equals("Martyries")) { linkToPath = "Οντότητα/ΜαρτυρίαΟντότητα/Θέμα"; } else if (type.equals("Material")) { linkToPath = "Οντότητα/ΥλικόΟντότητα/Ονομασία"; } else if (type.equals("Organization")) { linkToPath = "Οντότητα/ΟργανισμόςΟντότητα/Επωνυμία"; } else if (type.equals("Part")) { linkToPath = "Οντότητα/ΤμήμαΟντότητα/Ονομασία"; } else if (type.equals("Person")) { linkToPath = "Οντότητα/ΠρόσωποΟντότητα/Ονοματεπώνυμο"; } if (linkToPath != null) { nodesCol.xUpdate("//node[xpath='" + xpath + "']/valueFrom", linkToPath); } } } String uniqueXpath = ""; if (valuesFromTable != null) { for (String valueFromTable : valuesFromTable) { linkToPath = valueFromTable; if (linkToPath.contains(",")) { uniqueXpath = linkToPath.split(",")[0]; } else { uniqueXpath = linkToPath; } //Added next<SUF> uniqueXpath = uniqueXpath.replaceAll("\\[\\d++\\]", ""); uniqueXpath = uniqueXpath.replaceAll("\\[.*\\]", ""); // System.out.println("2="+uniqueXpath); String[] typeOfvaluesFromTable = nodesCol.query("//node[xpath='" + uniqueXpath + "']/@type/string()"); if (typeOfvaluesFromTable != null && typeOfvaluesFromTable.length > 0) { result.put(typeOfvaluesFromTable[0], linkToPath); } } } return result; } private String calculateInlineValues(String paths, String sourceType, String sourceId, String sourceXML) { ArrayList<String> inlinePaths = findReg("\\{\\{.*?\\}\\}", paths, 0); for (String inPath : inlinePaths) { String modifiedPath = "//" + inPath.substring(2, inPath.length() - 2) + "/string()"; DBCollection dbc = new DBCollection(BasicServlet.DBURI, applicationCollection + "/Temp", BasicServlet.DBuser, BasicServlet.DBpassword); DBFile dbf = dbc.createFile(sourceType + sourceId + ".xml", "XMLDBFile"); dbf.setXMLAsString(sourceXML); dbf.store(); String[] res = dbf.queryString(modifiedPath); String actualValue = ""; if (res != null && res.length > 0) { actualValue = res[0]; } paths = paths.replace(inPath, actualValue); dbf.remove(); } return paths; } private String getVocabulary(String xpath, String prefix) { DBCollection nodesCol = new DBCollection(BasicServlet.DBURI, applicationCollection + "/LaAndLi", BasicServlet.DBuser, BasicServlet.DBpassword); xpath = xpath.replaceAll("\\[\\d++\\]", ""); //Should be only one String[] vocabsTable = nodesCol.query("//node[xpath='" + xpath + "']/vocabulary[.!='']/string()"); if (vocabsTable == null || vocabsTable.length == 0) { //If no info in LaAndLi collection, then try querying legacy data DBCollection rootCol = new DBCollection(BasicServlet.DBURI, applicationCollection, BasicServlet.DBuser, BasicServlet.DBpassword); vocabsTable = rootCol.query("//" + xpath + "/@" + prefix + "_vocabulary/string()"); if (vocabsTable != null && vocabsTable.length > 0) { nodesCol.xUpdate("//node[xpath='" + xpath + "']/vocabulary", vocabsTable[0]); } } if (vocabsTable != null && vocabsTable.length > 0) { return vocabsTable[0]; } else { return null; } } private String getFacetProperties(String xpath, String prefix) { DBCollection nodesCol = new DBCollection(BasicServlet.DBURI, applicationCollection + "/LaAndLi", BasicServlet.DBuser, BasicServlet.DBpassword); xpath = xpath.replaceAll("\\[\\d++\\]", ""); //Should be only one? String[] facetsTable = nodesCol.query("//node[xpath='" + xpath + "']/facet"); if (facetsTable == null || facetsTable.length == 0) { //If no info in LaAndLi collection, then try querying legacy data //TO CHECK DBCollection rootCol = new DBCollection(BasicServlet.DBURI, applicationCollection, BasicServlet.DBuser, BasicServlet.DBpassword); facetsTable = rootCol.query("//" + xpath + "/@" + prefix + "_facet"); if (facetsTable != null && facetsTable.length > 0) { System.out.println("XPATH=" + xpath); System.out.println("FT[0]=" + facetsTable[0]); // nodesCol.xUpdate("//node[xpath='" + xpath + "']/facet", facetsTable[0]); } } if (facetsTable != null && facetsTable.length > 0) { return facetsTable[0]; } else { return null; } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
6521_13
/* * Copyright 2015 Institute of Computer Science, * Foundation for Research and Technology - Hellas. * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved * by the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software distributed * under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and limitations * under the Licence. * * ============================================================================= * Contact: * ============================================================================= * Address: N. Plastira 100 Vassilika Vouton, GR-700 13 Heraklion, Crete, Greece * Tel: +30-2810-391632 * Fax: +30-2810-391638 * E-mail: [email protected] * WebSite: https://www.ics.forth.gr/isl/centre-cultural-informatics * * ============================================================================= * Authors: * ============================================================================= * Elias Tzortzakakis <[email protected]> * * This file is part of the THEMAS system. */ package Utils; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author tzortzak */ import java.util.*; import java.text.Collator; public class TaxonomicCodeComparator implements Comparator{ Locale currentLocale; public TaxonomicCodeComparator(Locale locale) { super(); currentLocale = locale; } public int compare(Object m,Object n) { TaxonomicCodeItem m1 = (TaxonomicCodeItem) m; TaxonomicCodeItem n1 = (TaxonomicCodeItem) n; int m1PartsDefined = m1.codeParts.size(); int n1PartsDefined = n1.codeParts.size(); int returnValue = 0; //Collator gr_GRCollator = Collator.getInstance(currentLocale); if(m1PartsDefined > n1PartsDefined){ for(int k=0; k< n1PartsDefined; k++){ if(m1.codeParts.get(k).compareTo(n1.codeParts.get(k))!=0){ //if(gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)) != 0){ //returnValue = gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)); returnValue = m1.codeParts.get(k).compareTo(n1.codeParts.get(k)); break; } } if(returnValue == 0){ returnValue = 1; } } else if(m1PartsDefined < n1PartsDefined){ for(int k=0; k< m1PartsDefined; k++){ //if(gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)) != 0){ if(m1.codeParts.get(k).compareTo(n1.codeParts.get(k))!=0){ //returnValue = gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)); returnValue = m1.codeParts.get(k).compareTo(n1.codeParts.get(k)); break; } } if(returnValue ==0){ returnValue = -1; } } else { for(int k=0; k< m1PartsDefined; k++){ //if(gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)) != 0){ if(m1.codeParts.get(k).compareTo(n1.codeParts.get(k))!=0){ //returnValue = gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)); returnValue = m1.codeParts.get(k).compareTo(n1.codeParts.get(k)); break; } } if(returnValue ==0) { String m1Translit = m1.nodeNameTransliteration; String n1Translit = n1.nodeNameTransliteration; if(m1Translit!=null && n1Translit!=null){ m1Translit = m1Translit.replaceAll(" ", "_"); n1Translit = n1Translit.replaceAll(" ", "_"); if(m1Translit.compareTo(n1Translit)!=0){ return m1Translit.compareTo(n1Translit); } } String m1Str = m1.nodeName; String n1Str = n1.nodeName; // bug fix by karam: Collator method compare() // does not work properly for greek strings with blanks // g.e. before the following bug fix: // "δημόσιος τομέας" < "δημόσιο χρέος" (correct is: >) // "δημόσιος Α" = "δημόσιοςΑ" (correct: <) m1Str = m1Str.replaceAll(" ", "_"); n1Str = n1Str.replaceAll(" ", "_"); //returnValue = gr_GRCollator.compare(m1Str, n1Str); returnValue = m1Str.compareTo(n1Str); //returnValue = gr_GRCollator.compare(m1.nodeName, n1.nodeName); } } // Utils.StaticClass.webAppSystemOut(Parameters.LogFilePrefix+"Compared " + m1.nodeName + " with " + n1.nodeName + " Result = " + returnValue); return returnValue; } }
isl/THEMAS
src/main/java/Utils/TaxonomicCodeComparator.java
1,485
// "δημόσιος τομέας" < "δημόσιο χρέος" (correct is: >)
line_comment
el
/* * Copyright 2015 Institute of Computer Science, * Foundation for Research and Technology - Hellas. * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved * by the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software distributed * under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and limitations * under the Licence. * * ============================================================================= * Contact: * ============================================================================= * Address: N. Plastira 100 Vassilika Vouton, GR-700 13 Heraklion, Crete, Greece * Tel: +30-2810-391632 * Fax: +30-2810-391638 * E-mail: [email protected] * WebSite: https://www.ics.forth.gr/isl/centre-cultural-informatics * * ============================================================================= * Authors: * ============================================================================= * Elias Tzortzakakis <[email protected]> * * This file is part of the THEMAS system. */ package Utils; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author tzortzak */ import java.util.*; import java.text.Collator; public class TaxonomicCodeComparator implements Comparator{ Locale currentLocale; public TaxonomicCodeComparator(Locale locale) { super(); currentLocale = locale; } public int compare(Object m,Object n) { TaxonomicCodeItem m1 = (TaxonomicCodeItem) m; TaxonomicCodeItem n1 = (TaxonomicCodeItem) n; int m1PartsDefined = m1.codeParts.size(); int n1PartsDefined = n1.codeParts.size(); int returnValue = 0; //Collator gr_GRCollator = Collator.getInstance(currentLocale); if(m1PartsDefined > n1PartsDefined){ for(int k=0; k< n1PartsDefined; k++){ if(m1.codeParts.get(k).compareTo(n1.codeParts.get(k))!=0){ //if(gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)) != 0){ //returnValue = gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)); returnValue = m1.codeParts.get(k).compareTo(n1.codeParts.get(k)); break; } } if(returnValue == 0){ returnValue = 1; } } else if(m1PartsDefined < n1PartsDefined){ for(int k=0; k< m1PartsDefined; k++){ //if(gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)) != 0){ if(m1.codeParts.get(k).compareTo(n1.codeParts.get(k))!=0){ //returnValue = gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)); returnValue = m1.codeParts.get(k).compareTo(n1.codeParts.get(k)); break; } } if(returnValue ==0){ returnValue = -1; } } else { for(int k=0; k< m1PartsDefined; k++){ //if(gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)) != 0){ if(m1.codeParts.get(k).compareTo(n1.codeParts.get(k))!=0){ //returnValue = gr_GRCollator.compare(m1.codeParts.get(k), n1.codeParts.get(k)); returnValue = m1.codeParts.get(k).compareTo(n1.codeParts.get(k)); break; } } if(returnValue ==0) { String m1Translit = m1.nodeNameTransliteration; String n1Translit = n1.nodeNameTransliteration; if(m1Translit!=null && n1Translit!=null){ m1Translit = m1Translit.replaceAll(" ", "_"); n1Translit = n1Translit.replaceAll(" ", "_"); if(m1Translit.compareTo(n1Translit)!=0){ return m1Translit.compareTo(n1Translit); } } String m1Str = m1.nodeName; String n1Str = n1.nodeName; // bug fix by karam: Collator method compare() // does not work properly for greek strings with blanks // g.e. before the following bug fix: // "δημόσιος τομέας"<SUF> // "δημόσιος Α" = "δημόσιοςΑ" (correct: <) m1Str = m1Str.replaceAll(" ", "_"); n1Str = n1Str.replaceAll(" ", "_"); //returnValue = gr_GRCollator.compare(m1Str, n1Str); returnValue = m1Str.compareTo(n1Str); //returnValue = gr_GRCollator.compare(m1.nodeName, n1.nodeName); } } // Utils.StaticClass.webAppSystemOut(Parameters.LogFilePrefix+"Compared " + m1.nodeName + " with " + n1.nodeName + " Result = " + returnValue); return returnValue; } }
5046_0
package clientTests.utils; import java.util.Date; import gr.minedu.papyros.protocol.dto.DocCategory; import gr.minedu.papyros.protocol.dto.DocumentDto; import gr.minedu.papyros.protocol.dto.Protocolin; import gr.modus.papyros.protocol.utils.DateUtils; public class ProtocolBuilder { public static Protocolin build(){ Protocolin protIn = new Protocolin(); protIn.setSenderId(100000009); protIn.setSenderProtocol(""+new Date().getTime()); protIn.setSenderProtocolDate( new DateUtils().formatDate(new Date())); protIn.setDocCategory(20); protIn.setTheme("Είναι το θέμα "); protIn.setAda("ADA1234567890"); protIn.setDescription("Δοκιμαστικό Πρώτοκολό "); //Περιγραφή συννημέννων . DocumentDto mainDoc = DocumentDtoBuilder.buildMain(); protIn.setMainDoc(mainDoc); DocumentDto attachDoc = DocumentDtoBuilder.build(); DocumentDto[] attachements = new DocumentDto[1]; attachements[0] = attachDoc; protIn.setAttachedDoc(attachements); return protIn; } }
itminedu/minedu-OpenApi-PapyrosDrivers
src/test/java/clientTests/utils/ProtocolBuilder.java
366
//Περιγραφή συννημέννων .
line_comment
el
package clientTests.utils; import java.util.Date; import gr.minedu.papyros.protocol.dto.DocCategory; import gr.minedu.papyros.protocol.dto.DocumentDto; import gr.minedu.papyros.protocol.dto.Protocolin; import gr.modus.papyros.protocol.utils.DateUtils; public class ProtocolBuilder { public static Protocolin build(){ Protocolin protIn = new Protocolin(); protIn.setSenderId(100000009); protIn.setSenderProtocol(""+new Date().getTime()); protIn.setSenderProtocolDate( new DateUtils().formatDate(new Date())); protIn.setDocCategory(20); protIn.setTheme("Είναι το θέμα "); protIn.setAda("ADA1234567890"); protIn.setDescription("Δοκιμαστικό Πρώτοκολό "); //Περιγραφή συννημέννων<SUF> DocumentDto mainDoc = DocumentDtoBuilder.buildMain(); protIn.setMainDoc(mainDoc); DocumentDto attachDoc = DocumentDtoBuilder.build(); DocumentDto[] attachements = new DocumentDto[1]; attachements[0] = attachDoc; protIn.setAttachedDoc(attachements); return protIn; } }
40_10
/* This file is part of Arcadeflex. Arcadeflex is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Arcadeflex is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Arcadeflex. If not, see <http://www.gnu.org/licenses/>. */ package convertor; /** * * @author george */ public class sndConvert { static final int snd_mem_read=15; static final int snd_mem_write=16; static final int snd_update=20; static final int snd_start=21; static final int snd_stop=22; static final int snd_interrupt=23; public static void ConvertSound() { Convertor.inpos = 0;//position of pointer inside the buffers Convertor.outpos = 0; boolean only_once_flag=false;//gia na baleis to header mono mia fora boolean line_change_flag=false; int type=0; int l=0; int k=0; label0: do { if(Convertor.inpos >= Convertor.inbuf.length)//an to megethos einai megalitero spase to loop { break; } char c = sUtil.getChar(); //pare ton character if(line_change_flag) { for(int i1 = 0; i1 < k; i1++) { sUtil.putString("\t"); } line_change_flag = false; } switch(c) { case 35: // '#' if(!sUtil.getToken("#include"))//an den einai #include min to trexeis { break; } sUtil.skipLine(); if(!only_once_flag)//trekse auto to komati mono otan bris to proto include { only_once_flag = true; sUtil.putString("/*\r\n"); sUtil.putString(" * ported to v" + Convertor.mameversion + "\r\n"); sUtil.putString(" * using automatic conversion tool v" + Convertor.convertorversion + "\r\n"); sUtil.putString(" * converted at : " + Convertor.timenow() + "\r\n"); sUtil.putString(" *\r\n"); sUtil.putString(" *\r\n"); sUtil.putString(" *\r\n"); sUtil.putString(" */ \r\n"); sUtil.putString("package sndhrdw;\r\n"); sUtil.putString("\r\n"); sUtil.putString((new StringBuilder()).append("public class ").append(Convertor.className).append("\r\n").toString()); sUtil.putString("{\r\n"); k=1; line_change_flag = true; } continue; case 10: // '\n' Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++]; line_change_flag = true; continue; case 118: // 'v' int j = Convertor.inpos; if(!sUtil.getToken("void")) { break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(sUtil.getToken("void"))//an to soma tis function einai (void) { if(sUtil.parseChar() != ')') { Convertor.inpos = j; break; } if(Convertor.token[0].contains("sh_update")) { sUtil.putString((new StringBuilder()).append("public static ShUpdatePtr ").append(Convertor.token[0]).append(" = new ShUpdatePtr() { public void handler() ").toString()); type = snd_update; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } if(Convertor.token[0].contains("sh_stop")) { sUtil.putString((new StringBuilder()).append("public static ShStopPtr ").append(Convertor.token[0]).append(" = new ShStopPtr() { public void handler() ").toString()); type = snd_stop; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } } if(!sUtil.getToken("int")) { Convertor.inpos = j; break; } sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ',') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(!sUtil.getToken("int")) { Convertor.inpos = j; break; } sUtil.skipSpace(); Convertor.token[2] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ')') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0 && Convertor.token[2].length()>0) { sUtil.putString((new StringBuilder()).append("public static WriteHandlerPtr ").append(Convertor.token[0]).append(" = new WriteHandlerPtr() { public void handler(int ").append(Convertor.token[1]).append(", int ").append(Convertor.token[2]).append(")").toString()); type = snd_mem_write; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } Convertor.inpos = j; break; case 105: // 'i' int i = Convertor.inpos; if(sUtil.getToken("if")) { sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = i; break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.getChar() == '&') { Convertor.inpos++; sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); Convertor.token[0] = (new StringBuilder()).append("(").append(Convertor.token[0]).append(" & ").append(Convertor.token[1]).append(")").toString(); } if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } sUtil.putString((new StringBuilder()).append("if (").append(Convertor.token[0]).append(" != 0)").toString()); continue; } if(!sUtil.getToken("int")) { break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = i; break; } sUtil.skipSpace(); if(sUtil.getToken("void"))//an to soma tis function einai (void) { if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } if(Convertor.token[0].contains("sh_start")) { sUtil.putString((new StringBuilder()).append("public static ShStartPtr ").append(Convertor.token[0]).append(" = new ShStartPtr() { public int handler() ").toString()); type = snd_start; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } if(Convertor.token[0].contains("sh_interrupt")) { sUtil.putString((new StringBuilder()).append("public static InterruptPtr ").append(Convertor.token[0]).append(" = new InterruptPtr() { public int handler() ").toString()); type = snd_interrupt; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } } if(sUtil.getToken("int")) { sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } sUtil.skipSpace(); if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0) { sUtil.putString((new StringBuilder()).append("public static ReadHandlerPtr ").append(Convertor.token[0]).append(" = new ReadHandlerPtr() { public int handler(int ").append(Convertor.token[1]).append(")").toString()); type = snd_mem_read; l = -1; continue label0; } } Convertor.inpos = i; break; case 45: // '-' char c3 = sUtil.getNextChar(); if(c3 != '>') { break; } Convertor.outbuf[Convertor.outpos++] = '.'; Convertor.inpos += 2; continue; case 123: // '{' l++; break; case 125: // '}' l--; if(type != snd_mem_read && type != snd_mem_write && type!=snd_update && type!=snd_start && type!=snd_stop && type!=snd_interrupt || l != -1) { break; } sUtil.putString("} };"); Convertor.inpos++; type = -1; continue; } Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++];//grapse to inputbuffer sto output }while(true); if(only_once_flag) { sUtil.putString("}\r\n"); } } }
javaemus/arcadeflex029
convertor/src/convertor/sndConvert.java
2,735
//ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση
line_comment
el
/* This file is part of Arcadeflex. Arcadeflex is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Arcadeflex is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Arcadeflex. If not, see <http://www.gnu.org/licenses/>. */ package convertor; /** * * @author george */ public class sndConvert { static final int snd_mem_read=15; static final int snd_mem_write=16; static final int snd_update=20; static final int snd_start=21; static final int snd_stop=22; static final int snd_interrupt=23; public static void ConvertSound() { Convertor.inpos = 0;//position of pointer inside the buffers Convertor.outpos = 0; boolean only_once_flag=false;//gia na baleis to header mono mia fora boolean line_change_flag=false; int type=0; int l=0; int k=0; label0: do { if(Convertor.inpos >= Convertor.inbuf.length)//an to megethos einai megalitero spase to loop { break; } char c = sUtil.getChar(); //pare ton character if(line_change_flag) { for(int i1 = 0; i1 < k; i1++) { sUtil.putString("\t"); } line_change_flag = false; } switch(c) { case 35: // '#' if(!sUtil.getToken("#include"))//an den einai #include min to trexeis { break; } sUtil.skipLine(); if(!only_once_flag)//trekse auto to komati mono otan bris to proto include { only_once_flag = true; sUtil.putString("/*\r\n"); sUtil.putString(" * ported to v" + Convertor.mameversion + "\r\n"); sUtil.putString(" * using automatic conversion tool v" + Convertor.convertorversion + "\r\n"); sUtil.putString(" * converted at : " + Convertor.timenow() + "\r\n"); sUtil.putString(" *\r\n"); sUtil.putString(" *\r\n"); sUtil.putString(" *\r\n"); sUtil.putString(" */ \r\n"); sUtil.putString("package sndhrdw;\r\n"); sUtil.putString("\r\n"); sUtil.putString((new StringBuilder()).append("public class ").append(Convertor.className).append("\r\n").toString()); sUtil.putString("{\r\n"); k=1; line_change_flag = true; } continue; case 10: // '\n' Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++]; line_change_flag = true; continue; case 118: // 'v' int j = Convertor.inpos; if(!sUtil.getToken("void")) { break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(sUtil.getToken("void"))//an to soma tis function einai (void) { if(sUtil.parseChar() != ')') { Convertor.inpos = j; break; } if(Convertor.token[0].contains("sh_update")) { sUtil.putString((new StringBuilder()).append("public static ShUpdatePtr ").append(Convertor.token[0]).append(" = new ShUpdatePtr() { public void handler() ").toString()); type = snd_update; l = -1; continue label0; //ξαναργυρνα στην<SUF> } if(Convertor.token[0].contains("sh_stop")) { sUtil.putString((new StringBuilder()).append("public static ShStopPtr ").append(Convertor.token[0]).append(" = new ShStopPtr() { public void handler() ").toString()); type = snd_stop; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } } if(!sUtil.getToken("int")) { Convertor.inpos = j; break; } sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ',') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(!sUtil.getToken("int")) { Convertor.inpos = j; break; } sUtil.skipSpace(); Convertor.token[2] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ')') { Convertor.inpos = j; break; } sUtil.skipSpace(); if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0 && Convertor.token[2].length()>0) { sUtil.putString((new StringBuilder()).append("public static WriteHandlerPtr ").append(Convertor.token[0]).append(" = new WriteHandlerPtr() { public void handler(int ").append(Convertor.token[1]).append(", int ").append(Convertor.token[2]).append(")").toString()); type = snd_mem_write; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } Convertor.inpos = j; break; case 105: // 'i' int i = Convertor.inpos; if(sUtil.getToken("if")) { sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = i; break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.getChar() == '&') { Convertor.inpos++; sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); Convertor.token[0] = (new StringBuilder()).append("(").append(Convertor.token[0]).append(" & ").append(Convertor.token[1]).append(")").toString(); } if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } sUtil.putString((new StringBuilder()).append("if (").append(Convertor.token[0]).append(" != 0)").toString()); continue; } if(!sUtil.getToken("int")) { break; } sUtil.skipSpace(); Convertor.token[0] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != '(') { Convertor.inpos = i; break; } sUtil.skipSpace(); if(sUtil.getToken("void"))//an to soma tis function einai (void) { if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } if(Convertor.token[0].contains("sh_start")) { sUtil.putString((new StringBuilder()).append("public static ShStartPtr ").append(Convertor.token[0]).append(" = new ShStartPtr() { public int handler() ").toString()); type = snd_start; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } if(Convertor.token[0].contains("sh_interrupt")) { sUtil.putString((new StringBuilder()).append("public static InterruptPtr ").append(Convertor.token[0]).append(" = new InterruptPtr() { public int handler() ").toString()); type = snd_interrupt; l = -1; continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση } } if(sUtil.getToken("int")) { sUtil.skipSpace(); Convertor.token[1] = sUtil.parseToken(); sUtil.skipSpace(); if(sUtil.parseChar() != ')') { Convertor.inpos = i; break; } sUtil.skipSpace(); if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0) { sUtil.putString((new StringBuilder()).append("public static ReadHandlerPtr ").append(Convertor.token[0]).append(" = new ReadHandlerPtr() { public int handler(int ").append(Convertor.token[1]).append(")").toString()); type = snd_mem_read; l = -1; continue label0; } } Convertor.inpos = i; break; case 45: // '-' char c3 = sUtil.getNextChar(); if(c3 != '>') { break; } Convertor.outbuf[Convertor.outpos++] = '.'; Convertor.inpos += 2; continue; case 123: // '{' l++; break; case 125: // '}' l--; if(type != snd_mem_read && type != snd_mem_write && type!=snd_update && type!=snd_start && type!=snd_stop && type!=snd_interrupt || l != -1) { break; } sUtil.putString("} };"); Convertor.inpos++; type = -1; continue; } Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++];//grapse to inputbuffer sto output }while(true); if(only_once_flag) { sUtil.putString("}\r\n"); } } }