index
int64
1
4.82k
file_id
stringlengths
6
10
content
stringlengths
233
30k
repo
stringlengths
7
108
path
stringlengths
8
133
token_length
int64
72
8.17k
original_comment
stringlengths
13
2.72k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
142
29.9k
Inclusion
stringclasses
1 value
Exclusion
stringclasses
1 value
__index_level_0__
int64
1
2.15k
1,995
8399_0
package com.unasat;_x000D_ _x000D_ import com.unasat.service.*;_x000D_ import com.unasat.utility.Messages;_x000D_ _x000D_ import java.sql.SQLException;_x000D_ import java.util.Scanner;_x000D_ _x000D_ import static com.unasat.utility.UtilityMethods.isInputNotCorrect;_x000D_ import static com.unasat.utility.UtilityMethods.isOptionCorrect;_x000D_ _x000D_ public class Main {_x000D_ _x000D_ /**_x000D_ * @Developer: Akhsaykumar Bhoendie_x000D_ * @Project: Mildred's Kookschool_x000D_ * @Description: De applicatie is gebouwd voor registratie van dagelijkse activiteiten voor de kookschool._x000D_ * Verschillende zaken worden bijgehouden nl.:_x000D_ * - Inschrijvingen_x000D_ * - Kook cursussen_x000D_ * - prestaties_x000D_ * - Klantenbestand_x000D_ * - Openstaande rekeningen_x000D_ * @Instructies: Om gebruik te kunnen maken van de applicatie moeten de volgende zaken eerst in orde gemaakt worden:_x000D_ * - Maak een database connectie met een database genoemd "kookschool"_x000D_ * - Navigeer naar de DatabaseConnection class en geef de credentials mee_x000D_ * - Navigeer naar de SQL folder in de root directory en draai de sql script in Heidi of ander database management system_x000D_ * - De mysql Java Connector zit in de applicatie structuur en kan gebruikt worden voor configuratie in geval nodig_x000D_ * - Run de main app_x000D_ * <p>_x000D_ * #@ENJOY!_x000D_ */_x000D_ _x000D_ public static void main(String[] args) throws SQLException {_x000D_ _x000D_ Messages.startApplication();_x000D_ boolean cannotProceed = true;_x000D_ Scanner scanner = new Scanner(System.in);_x000D_ String input;_x000D_ _x000D_ while (cannotProceed) {_x000D_ Messages.hoofdMenu();_x000D_ input = scanner.nextLine();_x000D_ _x000D_ if (isInputNotCorrect(input) || !isOptionCorrect(input)) {_x000D_ Messages.error1();_x000D_ } else {_x000D_ if (input.trim().equalsIgnoreCase("1")) {_x000D_ cannotProceed = false;_x000D_ Messages.goodbye();_x000D_ break;_x000D_ } else if (input.trim().equalsIgnoreCase("2")) {_x000D_ //kookcursus_x000D_ KookCursusService kookCursusService = new KookCursusService();_x000D_ kookCursusService.perform(scanner);_x000D_ } else if (input.trim().equalsIgnoreCase("3")) {_x000D_ //inschrijven_x000D_ DeelnemersService deelnemersService = new DeelnemersService();_x000D_ deelnemersService.perform(scanner);_x000D_ } else if (input.trim().equalsIgnoreCase("4")) {_x000D_ //klanten bestand_x000D_ KlantenBestandService klantenBestandService = new KlantenBestandService();_x000D_ klantenBestandService.perform(scanner);_x000D_ } else if (input.trim().equalsIgnoreCase("5")) {_x000D_ //prestaties_x000D_ PrestatieService prestatieService = new PrestatieService();_x000D_ prestatieService.perform(scanner);_x000D_ } else if (input.trim().equalsIgnoreCase("6")) {_x000D_ //schulden_x000D_ SchuldenService schuldenService = new SchuldenService();_x000D_ schuldenService.perform(scanner);_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ scanner.reset();_x000D_ scanner.close();_x000D_ Messages.finished();_x000D_ _x000D_ }_x000D_ }_x000D_
akshaybhoendie/mildred-is-cooking
src/com/unasat/Main.java
920
/**_x000D_ * @Developer: Akhsaykumar Bhoendie_x000D_ * @Project: Mildred's Kookschool_x000D_ * @Description: De applicatie is gebouwd voor registratie van dagelijkse activiteiten voor de kookschool._x000D_ * Verschillende zaken worden bijgehouden nl.:_x000D_ * - Inschrijvingen_x000D_ * - Kook cursussen_x000D_ * - prestaties_x000D_ * - Klantenbestand_x000D_ * - Openstaande rekeningen_x000D_ * @Instructies: Om gebruik te kunnen maken van de applicatie moeten de volgende zaken eerst in orde gemaakt worden:_x000D_ * - Maak een database connectie met een database genoemd "kookschool"_x000D_ * - Navigeer naar de DatabaseConnection class en geef de credentials mee_x000D_ * - Navigeer naar de SQL folder in de root directory en draai de sql script in Heidi of ander database management system_x000D_ * - De mysql Java Connector zit in de applicatie structuur en kan gebruikt worden voor configuratie in geval nodig_x000D_ * - Run de main app_x000D_ * <p>_x000D_ * #@ENJOY!_x000D_ */
block_comment
nl
package com.unasat;_x000D_ _x000D_ import com.unasat.service.*;_x000D_ import com.unasat.utility.Messages;_x000D_ _x000D_ import java.sql.SQLException;_x000D_ import java.util.Scanner;_x000D_ _x000D_ import static com.unasat.utility.UtilityMethods.isInputNotCorrect;_x000D_ import static com.unasat.utility.UtilityMethods.isOptionCorrect;_x000D_ _x000D_ public class Main {_x000D_ _x000D_ /**_x000D_ * @Developer: Akhsaykumar Bhoendie_x000D_<SUF>*/_x000D_ _x000D_ public static void main(String[] args) throws SQLException {_x000D_ _x000D_ Messages.startApplication();_x000D_ boolean cannotProceed = true;_x000D_ Scanner scanner = new Scanner(System.in);_x000D_ String input;_x000D_ _x000D_ while (cannotProceed) {_x000D_ Messages.hoofdMenu();_x000D_ input = scanner.nextLine();_x000D_ _x000D_ if (isInputNotCorrect(input) || !isOptionCorrect(input)) {_x000D_ Messages.error1();_x000D_ } else {_x000D_ if (input.trim().equalsIgnoreCase("1")) {_x000D_ cannotProceed = false;_x000D_ Messages.goodbye();_x000D_ break;_x000D_ } else if (input.trim().equalsIgnoreCase("2")) {_x000D_ //kookcursus_x000D_ KookCursusService kookCursusService = new KookCursusService();_x000D_ kookCursusService.perform(scanner);_x000D_ } else if (input.trim().equalsIgnoreCase("3")) {_x000D_ //inschrijven_x000D_ DeelnemersService deelnemersService = new DeelnemersService();_x000D_ deelnemersService.perform(scanner);_x000D_ } else if (input.trim().equalsIgnoreCase("4")) {_x000D_ //klanten bestand_x000D_ KlantenBestandService klantenBestandService = new KlantenBestandService();_x000D_ klantenBestandService.perform(scanner);_x000D_ } else if (input.trim().equalsIgnoreCase("5")) {_x000D_ //prestaties_x000D_ PrestatieService prestatieService = new PrestatieService();_x000D_ prestatieService.perform(scanner);_x000D_ } else if (input.trim().equalsIgnoreCase("6")) {_x000D_ //schulden_x000D_ SchuldenService schuldenService = new SchuldenService();_x000D_ schuldenService.perform(scanner);_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ scanner.reset();_x000D_ scanner.close();_x000D_ Messages.finished();_x000D_ _x000D_ }_x000D_ }_x000D_
True
False
1,320
1,635
39937_4
import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; public class CateringImpl extends UnicastRemoteObject implements Catering { Registrar registrar; int businessNumber; String name, address; Scanner sc; byte[] secretKey; byte[] pseudonym; String CF; JFrame frame = new JFrame("Caterer"); JPanel p = new JPanel(); JTextField NameTextField = new JTextField(); JTextField BuisinessNumberTextField = new JTextField(); JTextField AddressTextField = new JTextField(); JTextField OutputTextField = new JTextField(); JButton logInButton = new JButton("Log in"); JButton getSecretkey = new JButton("Secret key"); JButton getPseudonym = new JButton("Pseudonym"); JButton getQRCode = new JButton("QR code"); JLabel NameLabel = new JLabel("Name"); JLabel BuisinessNumberLabel = new JLabel("Buisiness Number"); JLabel AddressLabel = new JLabel("Address"); JLabel OutputLabel = new JLabel("Output"); //hashing functie om hash in qrcode te genereren MessageDigest md = MessageDigest.getInstance("SHA-256"); public CateringImpl() throws RemoteException, NoSuchAlgorithmException { setFrame(); try { // fire to localhost port 1099 Registry myRegistry = LocateRegistry.getRegistry("localhost", 1099); registrar = (Registrar) myRegistry.lookup("Registrar"); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws RemoteException, NoSuchAlgorithmException { CateringImpl catering = new CateringImpl(); //catering.register(); } public void setFrame(){ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(400,500)); NameLabel.setBounds(0,20,10,10); BuisinessNumberLabel.setBounds(0,0,10,10); AddressLabel.setBounds(0,0,10,10); NameTextField.setVisible(true); BuisinessNumberTextField.setVisible(true); AddressTextField.setVisible(true); OutputLabel.setVisible(false); OutputTextField.setVisible(false); p.setLayout(new GridLayout(5,2)); p.add(NameLabel); p.add(NameTextField); p.add(BuisinessNumberLabel); p.add(BuisinessNumberTextField); p.add(AddressLabel); p.add(AddressTextField); p.add(OutputLabel); p.add(OutputTextField); p.add(logInButton); frame.add(p, BorderLayout.CENTER); JPanel panel = new JPanel(); panel.add(getQRCode); panel.add(getPseudonym); panel.add(getSecretkey); frame.add(panel, BorderLayout.PAGE_END); frame.setSize(400,500); getPseudonym.setVisible(false); getSecretkey.setVisible(false); getQRCode.setVisible(false); NameTextField.setEditable(true); BuisinessNumberTextField.setEditable(true); AddressTextField.setEditable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.pack(); getQRCode.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try{ genQRCode(); }catch (Exception ex){ ex.printStackTrace(); } } }); getSecretkey.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try{ OutputTextField.setText(Arrays.toString(secretKey)); }catch (Exception ex){ ex.printStackTrace(); } } }); getPseudonym.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try{ OutputTextField.setText(Arrays.toString(pseudonym)); }catch (Exception ex){ ex.printStackTrace(); } } }); logInButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try{ tryLogIn(); }catch (Exception ex){ ex.printStackTrace(); } } }); } public void tryLogIn()throws Exception{ if(!Objects.equals(NameTextField,"") && !Objects.equals(BuisinessNumberTextField,"") && !Objects.equals(AddressTextField,"")){ this.name = NameTextField.getText(); this.businessNumber = Integer.parseInt(BuisinessNumberTextField.getText()); this.address = AddressTextField.getText(); this.CF = businessNumber + name + address; p.remove(NameTextField); p.remove(BuisinessNumberTextField); p.remove(AddressTextField); p.remove(NameLabel); p.remove(BuisinessNumberLabel); p.remove(AddressLabel); p.remove(logInButton); OutputLabel.setVisible(true); OutputTextField.setVisible(true); getQRCode.setVisible(true); getSecretkey.setVisible(true); getPseudonym.setVisible(true); register(); String response = registrar.helloTo(name); OutputTextField.setText(response); } } //stuur een referentie naar onze eigen interface door naar de server zodat deze ons ook kan contacteren public void register() throws IOException, WriterException { registrar.register(this); } private static void printMenu() throws RemoteException, NoSuchAlgorithmException { Scanner s = new Scanner(System.in); int choice = 0; System.out.println("-----Enroll BarOwner-----"); //CateringImpl catering = new CateringImpl(); //catering.register(); while (choice != -1) { System.out.println(); System.out.println("1.Exit"); System.out.println("2. Print secret key"); System.out.println("3. Print pseudonym"); System.out.println("Enter your choice"); choice = s.nextInt(); switch (choice) { case 1: choice = -1; break; case 2: //System.out.println(Arrays.toString(catering.secretKey)); break; case 3: //System.out.println(Arrays.toString(catering.pseudonym)); } } s.close(); } //qr code generaten van random nummer, identifier en hash van pseudonym met randon nummer public void genQRCode() throws IOException, WriterException { Random rand = new Random(); int random = rand.nextInt(1000); String tbhash = String.valueOf(random) + Arrays.toString(pseudonym); md.update(tbhash.getBytes(StandardCharsets.UTF_8)); byte[] digest = md.digest(); String data = String.valueOf(random) + "|" + CF + "|" + Base64.getEncoder().encodeToString(digest); BitMatrix matrix = new MultiFormatWriter().encode( new String(data.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8), BarcodeFormat.QR_CODE, 200, 200); String path = "code" + businessNumber; //TODO tonen in gui path += ".png"; MatrixToImageWriter.writeToFile( matrix, path.substring(path.lastIndexOf('.') + 1), new File(path)); OutputTextField.setText(data); System.out.println("qr: " + data); System.out.println("random: " + random); System.out.println("nym: " + pseudonym); System.out.println("CF: " + CF); } @Override public int getBusinessNumber() throws RemoteException { return businessNumber; } @Override public String getName() throws RemoteException { return name; } @Override public void setSecretKey(byte[] secretKey) throws RemoteException { this.secretKey = secretKey; } @Override public String getCF() throws RemoteException { return CF; } @Override public String getLocation() throws RemoteException { return address; } @Override public void setPseudonym(byte[] pseudonym) throws IOException, WriterException { System.out.println("nym bij ontvangst: " + pseudonym); this.pseudonym = pseudonym; this.genQRCode(); } }
SprietMarthe/CoronaOpdracht_Robin_Lukas_Marthe
CF/src/CateringImpl.java
2,606
//qr code generaten van random nummer, identifier en hash van pseudonym met randon nummer
line_comment
nl
import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; public class CateringImpl extends UnicastRemoteObject implements Catering { Registrar registrar; int businessNumber; String name, address; Scanner sc; byte[] secretKey; byte[] pseudonym; String CF; JFrame frame = new JFrame("Caterer"); JPanel p = new JPanel(); JTextField NameTextField = new JTextField(); JTextField BuisinessNumberTextField = new JTextField(); JTextField AddressTextField = new JTextField(); JTextField OutputTextField = new JTextField(); JButton logInButton = new JButton("Log in"); JButton getSecretkey = new JButton("Secret key"); JButton getPseudonym = new JButton("Pseudonym"); JButton getQRCode = new JButton("QR code"); JLabel NameLabel = new JLabel("Name"); JLabel BuisinessNumberLabel = new JLabel("Buisiness Number"); JLabel AddressLabel = new JLabel("Address"); JLabel OutputLabel = new JLabel("Output"); //hashing functie om hash in qrcode te genereren MessageDigest md = MessageDigest.getInstance("SHA-256"); public CateringImpl() throws RemoteException, NoSuchAlgorithmException { setFrame(); try { // fire to localhost port 1099 Registry myRegistry = LocateRegistry.getRegistry("localhost", 1099); registrar = (Registrar) myRegistry.lookup("Registrar"); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws RemoteException, NoSuchAlgorithmException { CateringImpl catering = new CateringImpl(); //catering.register(); } public void setFrame(){ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(400,500)); NameLabel.setBounds(0,20,10,10); BuisinessNumberLabel.setBounds(0,0,10,10); AddressLabel.setBounds(0,0,10,10); NameTextField.setVisible(true); BuisinessNumberTextField.setVisible(true); AddressTextField.setVisible(true); OutputLabel.setVisible(false); OutputTextField.setVisible(false); p.setLayout(new GridLayout(5,2)); p.add(NameLabel); p.add(NameTextField); p.add(BuisinessNumberLabel); p.add(BuisinessNumberTextField); p.add(AddressLabel); p.add(AddressTextField); p.add(OutputLabel); p.add(OutputTextField); p.add(logInButton); frame.add(p, BorderLayout.CENTER); JPanel panel = new JPanel(); panel.add(getQRCode); panel.add(getPseudonym); panel.add(getSecretkey); frame.add(panel, BorderLayout.PAGE_END); frame.setSize(400,500); getPseudonym.setVisible(false); getSecretkey.setVisible(false); getQRCode.setVisible(false); NameTextField.setEditable(true); BuisinessNumberTextField.setEditable(true); AddressTextField.setEditable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.pack(); getQRCode.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try{ genQRCode(); }catch (Exception ex){ ex.printStackTrace(); } } }); getSecretkey.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try{ OutputTextField.setText(Arrays.toString(secretKey)); }catch (Exception ex){ ex.printStackTrace(); } } }); getPseudonym.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try{ OutputTextField.setText(Arrays.toString(pseudonym)); }catch (Exception ex){ ex.printStackTrace(); } } }); logInButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try{ tryLogIn(); }catch (Exception ex){ ex.printStackTrace(); } } }); } public void tryLogIn()throws Exception{ if(!Objects.equals(NameTextField,"") && !Objects.equals(BuisinessNumberTextField,"") && !Objects.equals(AddressTextField,"")){ this.name = NameTextField.getText(); this.businessNumber = Integer.parseInt(BuisinessNumberTextField.getText()); this.address = AddressTextField.getText(); this.CF = businessNumber + name + address; p.remove(NameTextField); p.remove(BuisinessNumberTextField); p.remove(AddressTextField); p.remove(NameLabel); p.remove(BuisinessNumberLabel); p.remove(AddressLabel); p.remove(logInButton); OutputLabel.setVisible(true); OutputTextField.setVisible(true); getQRCode.setVisible(true); getSecretkey.setVisible(true); getPseudonym.setVisible(true); register(); String response = registrar.helloTo(name); OutputTextField.setText(response); } } //stuur een referentie naar onze eigen interface door naar de server zodat deze ons ook kan contacteren public void register() throws IOException, WriterException { registrar.register(this); } private static void printMenu() throws RemoteException, NoSuchAlgorithmException { Scanner s = new Scanner(System.in); int choice = 0; System.out.println("-----Enroll BarOwner-----"); //CateringImpl catering = new CateringImpl(); //catering.register(); while (choice != -1) { System.out.println(); System.out.println("1.Exit"); System.out.println("2. Print secret key"); System.out.println("3. Print pseudonym"); System.out.println("Enter your choice"); choice = s.nextInt(); switch (choice) { case 1: choice = -1; break; case 2: //System.out.println(Arrays.toString(catering.secretKey)); break; case 3: //System.out.println(Arrays.toString(catering.pseudonym)); } } s.close(); } //qr code<SUF> public void genQRCode() throws IOException, WriterException { Random rand = new Random(); int random = rand.nextInt(1000); String tbhash = String.valueOf(random) + Arrays.toString(pseudonym); md.update(tbhash.getBytes(StandardCharsets.UTF_8)); byte[] digest = md.digest(); String data = String.valueOf(random) + "|" + CF + "|" + Base64.getEncoder().encodeToString(digest); BitMatrix matrix = new MultiFormatWriter().encode( new String(data.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8), BarcodeFormat.QR_CODE, 200, 200); String path = "code" + businessNumber; //TODO tonen in gui path += ".png"; MatrixToImageWriter.writeToFile( matrix, path.substring(path.lastIndexOf('.') + 1), new File(path)); OutputTextField.setText(data); System.out.println("qr: " + data); System.out.println("random: " + random); System.out.println("nym: " + pseudonym); System.out.println("CF: " + CF); } @Override public int getBusinessNumber() throws RemoteException { return businessNumber; } @Override public String getName() throws RemoteException { return name; } @Override public void setSecretKey(byte[] secretKey) throws RemoteException { this.secretKey = secretKey; } @Override public String getCF() throws RemoteException { return CF; } @Override public String getLocation() throws RemoteException { return address; } @Override public void setPseudonym(byte[] pseudonym) throws IOException, WriterException { System.out.println("nym bij ontvangst: " + pseudonym); this.pseudonym = pseudonym; this.genQRCode(); } }
True
False
1,321
386
7822_0
package controllers; import dal.repositories.DatabaseExecutionContext; import dal.repositories.JPARecipeRepository; import dal.repositories.JPAUserRepository; import models.*; import play.db.jpa.JPAApi; import play.db.jpa.Transactional; import play.mvc.*; import views.html.*; import views.html.shared.getResults; import views.html.shared.index; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import java.util.List; public class Application extends Controller { private JPAUserRepository userRepo; private JPARecipeRepository recipeRepo; @Inject public Application(JPAUserRepository userRepo, JPARecipeRepository recipeRepo) { this.userRepo = userRepo; this.recipeRepo = recipeRepo; } @Transactional public Result index() { User user = new User("harry", "[email protected]", "hallo123"); Recipe recipe = new Recipe("Rijst", "De perfecte rijst voor bodybuilders!", false); Ingredient ingredient = new Ingredient("Water", 20, "water.pjg", Measurement.ml); Kitchenware kitchenware = new Kitchenware("Vork"); userRepo.add(user); recipeRepo.add(recipe); // TODO: // De recipe klasse persisten lukt niet, zou je hier naar kunnen kijken, // waarom hij een error geeft? return ok(index.render()); } public Result getResults() { List<User> users = userRepo.list(); List<Recipe> recipes = recipeRepo.list(); return ok(getResults.render(users, recipes)); } /*public List<User> findAll() { return entityManager.createNamedQuery("User.getAll", User.class) .getResultList(); } */ }
Daniel-Lin1/BoodschappenlijstApp
BoodschappenLijst/app/controllers/Application.java
528
// De recipe klasse persisten lukt niet, zou je hier naar kunnen kijken,
line_comment
nl
package controllers; import dal.repositories.DatabaseExecutionContext; import dal.repositories.JPARecipeRepository; import dal.repositories.JPAUserRepository; import models.*; import play.db.jpa.JPAApi; import play.db.jpa.Transactional; import play.mvc.*; import views.html.*; import views.html.shared.getResults; import views.html.shared.index; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import java.util.List; public class Application extends Controller { private JPAUserRepository userRepo; private JPARecipeRepository recipeRepo; @Inject public Application(JPAUserRepository userRepo, JPARecipeRepository recipeRepo) { this.userRepo = userRepo; this.recipeRepo = recipeRepo; } @Transactional public Result index() { User user = new User("harry", "[email protected]", "hallo123"); Recipe recipe = new Recipe("Rijst", "De perfecte rijst voor bodybuilders!", false); Ingredient ingredient = new Ingredient("Water", 20, "water.pjg", Measurement.ml); Kitchenware kitchenware = new Kitchenware("Vork"); userRepo.add(user); recipeRepo.add(recipe); // TODO: // De recipe<SUF> // waarom hij een error geeft? return ok(index.render()); } public Result getResults() { List<User> users = userRepo.list(); List<Recipe> recipes = recipeRepo.list(); return ok(getResults.render(users, recipes)); } /*public List<User> findAll() { return entityManager.createNamedQuery("User.getAll", User.class) .getResultList(); } */ }
True
False
1,324
1,410
79494_7
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class level1 here. * * @author (your name) * @version (a version number or a date) */ public class Level1 extends World { private CollisionEngine ce; Counter counter = new Counter(); LifeCounter lifecounter = new LifeCounter(); KeyBlue key = new KeyBlue(); GemBlue gem = new GemBlue(); /** * Constructor for objects of class level1. * */ public Level1() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,4,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {25,25,25,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,14,14,14,14,14,5,5,5,5,5,14,14,14,14,14,14,14,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,25,25,25,25,25,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,24,24,24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 400, 700); addObject(counter, 900, 30); addObject(lifecounter, 71, 30); addObject(new Cross(), 70, 120); addObject(new CoinSilver(), 210, 810); addObject(new CoinSilver(), 1470, 870); addObject(new CoinSilver(), 2550, 990); addObject(new CoinSilver(), 3630, 750); addObject(new CoinSilver(), 4230, 750); addObject(new CoinGold(), 4950, 390); addObject(new KeyBlue(), 4230, 390); addObject(new GemBlue(), 5370, 390); addObject(new Slak(), 1275, 947); addObject(new Slak(), 4950, 947); addObject(new Door_closedMid(), 5730, 925); addObject(new Door_closedTop(), 5730, 865); // hoogte/breedte * 60 + 30 // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); prepare(); } @Override public void act() { ce.update(); if (key.keyCollected == true){ addObject(new Sleutel(), 50, 70); } if (gem.dGemCollected == true){ addObject(new DisplayGem(), 100, 70); } } /** * Prepare the world for the start of the program. * That is: create the initial objects and add them to the world. */ private void prepare() { } }
ROCMondriaanTIN/project-greenfoot-game-dannykuijpers
level1.java
5,028
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class level1 here. * * @author (your name) * @version (a version number or a date) */ public class Level1 extends World { private CollisionEngine ce; Counter counter = new Counter(); LifeCounter lifecounter = new LifeCounter(); KeyBlue key = new KeyBlue(); GemBlue gem = new GemBlue(); /** * Constructor for objects of class level1. * */ public Level1() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,4,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {25,25,25,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,14,14,14,14,14,5,5,5,5,5,14,14,14,14,14,14,14,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,25,25,25,25,25,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,24,24,24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en<SUF> // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 400, 700); addObject(counter, 900, 30); addObject(lifecounter, 71, 30); addObject(new Cross(), 70, 120); addObject(new CoinSilver(), 210, 810); addObject(new CoinSilver(), 1470, 870); addObject(new CoinSilver(), 2550, 990); addObject(new CoinSilver(), 3630, 750); addObject(new CoinSilver(), 4230, 750); addObject(new CoinGold(), 4950, 390); addObject(new KeyBlue(), 4230, 390); addObject(new GemBlue(), 5370, 390); addObject(new Slak(), 1275, 947); addObject(new Slak(), 4950, 947); addObject(new Door_closedMid(), 5730, 925); addObject(new Door_closedTop(), 5730, 865); // hoogte/breedte * 60 + 30 // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); prepare(); } @Override public void act() { ce.update(); if (key.keyCollected == true){ addObject(new Sleutel(), 50, 70); } if (gem.dGemCollected == true){ addObject(new DisplayGem(), 100, 70); } } /** * Prepare the world for the start of the program. * That is: create the initial objects and add them to the world. */ private void prepare() { } }
True
False
1,327
228
28778_4
import java.io.File;_x000D_ import java.io.FileNotFoundException;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Scanner;_x000D_ import java.util.HashSet;_x000D_ _x000D_ /**_x000D_ * Een klasse om klanteninformatie te lezen uit een csv bestand_x000D_ * DE klantenfile bevat naaminfromatie, adresinformatie en contactinformatie_x000D_ * van 88 klanten verspreid over de wereld._x000D_ * <p>_x000D_ * Het bestand bevat volgende informatie_x000D_ * CustomerID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax_x000D_ * Informatie van 1 klant bevindt zich op 1 lijn en wordt gescheiden door ;_x000D_ *_x000D_ * @author Marc De Caluwé_x000D_ * @version 2019-12-01_x000D_ */_x000D_ public class ContactReader {_x000D_ private String format;_x000D_ private ArrayList<ContactEntry> entries;_x000D_ _x000D_ public ContactReader() {_x000D_ this("contacts.csv");_x000D_ }_x000D_ _x000D_ public ContactReader(String filename) {_x000D_ // The format for the data._x000D_ format = "CustomerID;Namelient;NameContact;TitleContact;Addresd;City;Region;ZIP;Country;Phone;Fax";_x000D_ // Where to store the data._x000D_ entries = new ArrayList<>();_x000D_ _x000D_ // Attempt to read the complete set of data from file._x000D_ try {_x000D_ File pFile = new File("");_x000D_ File klantFile = new File(pFile.getAbsolutePath() + "/data/" + filename);_x000D_ Scanner klantfile = new Scanner(klantFile);_x000D_ // Lees het klantenbestand tot de laatste lijn_x000D_ while (klantfile.hasNextLine()) {_x000D_ String klantlijn = klantfile.nextLine();_x000D_ // Splits de klant en maak er een nieuw Klant-object van_x000D_ ContactEntry entry = new ContactEntry(klantlijn);_x000D_ entries.add(entry);_x000D_ }_x000D_ klantfile.close();_x000D_ } catch (FileNotFoundException e) {_x000D_ System.out.println("Er dook een probleem op: " + e.getMessage());_x000D_ }_x000D_ }_x000D_ _x000D_ public ArrayList<ContactEntry> getEntries() {_x000D_ return entries;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Print de data._x000D_ */_x000D_ public void printData() {_x000D_ for (ContactEntry entry : entries) {_x000D_ System.out.println(entry);_x000D_ }_x000D_ }_x000D_ _x000D_ public HashSet<Contact> loadContacts() {_x000D_ HashSet<Contact> klanten = new HashSet<>();_x000D_ for(ContactEntry ke : getEntries()) {_x000D_ String[] data = ke.getData();_x000D_ Contact k = new Contact(data[ContactEntry.ID]);_x000D_ k.setName(data[ContactEntry.NAMECONTACT]);_x000D_ k.setTitle(data[ContactEntry.TITLECONTACT]);_x000D_ k.setCity(data[ContactEntry.CITY]);_x000D_ k.setRegion(data[ContactEntry.REGION]);_x000D_ k.setCountry(data[ContactEntry.COUNTRY]);_x000D_ klanten.add(k);_x000D_ }_x000D_ return klanten;_x000D_ }_x000D_ _x000D_ public static void main(String[] args) {_x000D_ try {_x000D_ ContactReader kr = new ContactReader();_x000D_ kr.printData();_x000D_ System.out.println("---------------------------------------------------------------");_x000D_ for (ContactEntry ke : kr.getEntries()) {_x000D_ String[] data = ke.getData();_x000D_ // we drukken het ID en bijhorende naam van elke klant_x000D_ System.out.println("ID=" + data[ContactEntry.ID] + ", name=" + data[ContactEntry.NAMECLIENT]);_x000D_ }_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ }_x000D_
Boutoku/OOP-test-repository
oefeningen/src/ContactReader.java
956
// Lees het klantenbestand tot de laatste lijn_x000D_
line_comment
nl
import java.io.File;_x000D_ import java.io.FileNotFoundException;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Scanner;_x000D_ import java.util.HashSet;_x000D_ _x000D_ /**_x000D_ * Een klasse om klanteninformatie te lezen uit een csv bestand_x000D_ * DE klantenfile bevat naaminfromatie, adresinformatie en contactinformatie_x000D_ * van 88 klanten verspreid over de wereld._x000D_ * <p>_x000D_ * Het bestand bevat volgende informatie_x000D_ * CustomerID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax_x000D_ * Informatie van 1 klant bevindt zich op 1 lijn en wordt gescheiden door ;_x000D_ *_x000D_ * @author Marc De Caluwé_x000D_ * @version 2019-12-01_x000D_ */_x000D_ public class ContactReader {_x000D_ private String format;_x000D_ private ArrayList<ContactEntry> entries;_x000D_ _x000D_ public ContactReader() {_x000D_ this("contacts.csv");_x000D_ }_x000D_ _x000D_ public ContactReader(String filename) {_x000D_ // The format for the data._x000D_ format = "CustomerID;Namelient;NameContact;TitleContact;Addresd;City;Region;ZIP;Country;Phone;Fax";_x000D_ // Where to store the data._x000D_ entries = new ArrayList<>();_x000D_ _x000D_ // Attempt to read the complete set of data from file._x000D_ try {_x000D_ File pFile = new File("");_x000D_ File klantFile = new File(pFile.getAbsolutePath() + "/data/" + filename);_x000D_ Scanner klantfile = new Scanner(klantFile);_x000D_ // Lees het<SUF> while (klantfile.hasNextLine()) {_x000D_ String klantlijn = klantfile.nextLine();_x000D_ // Splits de klant en maak er een nieuw Klant-object van_x000D_ ContactEntry entry = new ContactEntry(klantlijn);_x000D_ entries.add(entry);_x000D_ }_x000D_ klantfile.close();_x000D_ } catch (FileNotFoundException e) {_x000D_ System.out.println("Er dook een probleem op: " + e.getMessage());_x000D_ }_x000D_ }_x000D_ _x000D_ public ArrayList<ContactEntry> getEntries() {_x000D_ return entries;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Print de data._x000D_ */_x000D_ public void printData() {_x000D_ for (ContactEntry entry : entries) {_x000D_ System.out.println(entry);_x000D_ }_x000D_ }_x000D_ _x000D_ public HashSet<Contact> loadContacts() {_x000D_ HashSet<Contact> klanten = new HashSet<>();_x000D_ for(ContactEntry ke : getEntries()) {_x000D_ String[] data = ke.getData();_x000D_ Contact k = new Contact(data[ContactEntry.ID]);_x000D_ k.setName(data[ContactEntry.NAMECONTACT]);_x000D_ k.setTitle(data[ContactEntry.TITLECONTACT]);_x000D_ k.setCity(data[ContactEntry.CITY]);_x000D_ k.setRegion(data[ContactEntry.REGION]);_x000D_ k.setCountry(data[ContactEntry.COUNTRY]);_x000D_ klanten.add(k);_x000D_ }_x000D_ return klanten;_x000D_ }_x000D_ _x000D_ public static void main(String[] args) {_x000D_ try {_x000D_ ContactReader kr = new ContactReader();_x000D_ kr.printData();_x000D_ System.out.println("---------------------------------------------------------------");_x000D_ for (ContactEntry ke : kr.getEntries()) {_x000D_ String[] data = ke.getData();_x000D_ // we drukken het ID en bijhorende naam van elke klant_x000D_ System.out.println("ID=" + data[ContactEntry.ID] + ", name=" + data[ContactEntry.NAMECLIENT]);_x000D_ }_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ }_x000D_
True
False
1,329
1,028
22062_0
public class PartTimeWerknemer extends Werknemer { public int urenGewerkt; public PartTimeWerknemer( String voornaam, String achternaam, int nr, float sal, int urengw) { super(voornaam, achternaam, nr, sal); this.urenGewerkt=urengw; } public float getWeekLoon() { return this.salaris * (float)urenGewerkt; } public void salarisVerhogen(int percentage) { if (percentage>5) { System.out.println("Fout: parttimewerknemer kunnen niet meer dan 5% opslag krijgen"); } else super.salarisVerhogen(percentage); // roep methode van Werknemer aan } }
MTA-Digital-Broadcast-2/I-Willems-Andy-Hendrickx-Matthias-Project-MHP
Willems-Andy/blz31/Oef7/PartTimeWerknemer.java
209
// roep methode van Werknemer aan
line_comment
nl
public class PartTimeWerknemer extends Werknemer { public int urenGewerkt; public PartTimeWerknemer( String voornaam, String achternaam, int nr, float sal, int urengw) { super(voornaam, achternaam, nr, sal); this.urenGewerkt=urengw; } public float getWeekLoon() { return this.salaris * (float)urenGewerkt; } public void salarisVerhogen(int percentage) { if (percentage>5) { System.out.println("Fout: parttimewerknemer kunnen niet meer dan 5% opslag krijgen"); } else super.salarisVerhogen(percentage); // roep methode<SUF> } }
True
False
1,330
4,265
23541_4
package org.firstinspires.ftc.teamcode; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import org.firstinspires.ftc.robotcore.external.Telemetry; import org.firstinspires.ftc.teamcode.classes.Drivetrain; import org.firstinspires.ftc.teamcode.classes.Hardware; import org.firstinspires.ftc.teamcode.classes.Lift; import org.firstinspires.ftc.teamcode.classes.Camera; import org.firstinspires.ftc.teamcode.classes.extra.GethPath; import org.firstinspires.ftc.teamcode.classes.extra.Position; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.TouchSensor; import static org.firstinspires.ftc.teamcode.classes.Hardware.*; import static org.firstinspires.ftc.teamcode.classes.extra.StartingPositions.*; @Autonomous(name = "Autonomous :)", group = "Centerstage") public class AutonomousCenterstage extends LinearOpMode { //Robot parts Hardware RobotHardware = new Hardware(); TouchSensor None; public Drivetrain CenterstageDriveTrain; public Lift Slides; public Lift Arm; public Lift Slider; public Camera Cam1; //Auton data StartPos sPos = StartPos.UNKNOWN; public String StartPosString; public void runOpMode() { RobotHardware.StartHardware(hardwareMap); CenterstageDriveTrain = new Drivetrain(imu, lfront, lback, rfront, rback, lfront, lback, rfront, 1,1,1,1,1); // TODO add odometry pod stuf Arm = new Lift(armMotor, Lift.LiftType.SinlejointedArm, 100, 32, 0, 0.00755190904, false, 1, ArmLimit); Slider = new Lift(SliderMotor, Lift.LiftType.LinearSlides, 100, 32, 1, 0, true, 1, ArmLimit); Cam1 = new Camera(cam, vsPortal, AprilProcessor, TfodProcessor); telemetry.addData("Status: ", "Calibrating..."); CenterstageDriveTrain.Init(); Arm.Init(); Cam1.initVSProcesor(); telemetry.update(); try { File startPosFile = new File("org\\firstinspires\\ftc\\teamcode\\classes\\extra\\datafiles\\StartingPosition.txt"); BufferedReader fileReader = new BufferedReader(new FileReader(startPosFile)); StartPosString = fileReader.readLine(); } catch (IOException e) { telemetry.addData("Error: ", e); } telemetry.addData("Status: ", "Selecting start pos..."); telemetry.addData("StartPos: ", StartPosString); telemetry.update(); //Autonomous selecting pos while(!gamepad1.back && !isStopRequested()) { if (gamepad1.a) sPos = StartPos.BLUE1; if (gamepad1.b) sPos = StartPos.BLUE2; if (gamepad1.x) sPos = StartPos.RED1; if (gamepad1.y) sPos = StartPos.RED2; telemetry.addData("Status: ", "Selecting start pos..."); telemetry.addData("StartPos: ", sPos); telemetry.update(); } telemetry.addData("Status: ", "Waiting for start..."); telemetry.update(); // hier blijven herkennen tot start waitForStart(); // Code after start is pressed------------------------------------------------------------------------------------ while(!isStopRequested()) { Position TeamEllementPos = Cam1.GetTfodLocation(Cam1.HighestRecon()); telemetry.addData("pos X: ", TeamEllementPos.x); telemetry.addData("pos Y: ", TeamEllementPos.y); telemetry.update(); //if( positie, 1, 2 of 3; rijd naar de juiste plek } } }
screwlooosescientists/FtcRobotController-master_ScrewLoooseScientists
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/AutonomousCenterstage.java
1,201
//if( positie, 1, 2 of 3; rijd naar de juiste plek
line_comment
nl
package org.firstinspires.ftc.teamcode; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import org.firstinspires.ftc.robotcore.external.Telemetry; import org.firstinspires.ftc.teamcode.classes.Drivetrain; import org.firstinspires.ftc.teamcode.classes.Hardware; import org.firstinspires.ftc.teamcode.classes.Lift; import org.firstinspires.ftc.teamcode.classes.Camera; import org.firstinspires.ftc.teamcode.classes.extra.GethPath; import org.firstinspires.ftc.teamcode.classes.extra.Position; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.TouchSensor; import static org.firstinspires.ftc.teamcode.classes.Hardware.*; import static org.firstinspires.ftc.teamcode.classes.extra.StartingPositions.*; @Autonomous(name = "Autonomous :)", group = "Centerstage") public class AutonomousCenterstage extends LinearOpMode { //Robot parts Hardware RobotHardware = new Hardware(); TouchSensor None; public Drivetrain CenterstageDriveTrain; public Lift Slides; public Lift Arm; public Lift Slider; public Camera Cam1; //Auton data StartPos sPos = StartPos.UNKNOWN; public String StartPosString; public void runOpMode() { RobotHardware.StartHardware(hardwareMap); CenterstageDriveTrain = new Drivetrain(imu, lfront, lback, rfront, rback, lfront, lback, rfront, 1,1,1,1,1); // TODO add odometry pod stuf Arm = new Lift(armMotor, Lift.LiftType.SinlejointedArm, 100, 32, 0, 0.00755190904, false, 1, ArmLimit); Slider = new Lift(SliderMotor, Lift.LiftType.LinearSlides, 100, 32, 1, 0, true, 1, ArmLimit); Cam1 = new Camera(cam, vsPortal, AprilProcessor, TfodProcessor); telemetry.addData("Status: ", "Calibrating..."); CenterstageDriveTrain.Init(); Arm.Init(); Cam1.initVSProcesor(); telemetry.update(); try { File startPosFile = new File("org\\firstinspires\\ftc\\teamcode\\classes\\extra\\datafiles\\StartingPosition.txt"); BufferedReader fileReader = new BufferedReader(new FileReader(startPosFile)); StartPosString = fileReader.readLine(); } catch (IOException e) { telemetry.addData("Error: ", e); } telemetry.addData("Status: ", "Selecting start pos..."); telemetry.addData("StartPos: ", StartPosString); telemetry.update(); //Autonomous selecting pos while(!gamepad1.back && !isStopRequested()) { if (gamepad1.a) sPos = StartPos.BLUE1; if (gamepad1.b) sPos = StartPos.BLUE2; if (gamepad1.x) sPos = StartPos.RED1; if (gamepad1.y) sPos = StartPos.RED2; telemetry.addData("Status: ", "Selecting start pos..."); telemetry.addData("StartPos: ", sPos); telemetry.update(); } telemetry.addData("Status: ", "Waiting for start..."); telemetry.update(); // hier blijven herkennen tot start waitForStart(); // Code after start is pressed------------------------------------------------------------------------------------ while(!isStopRequested()) { Position TeamEllementPos = Cam1.GetTfodLocation(Cam1.HighestRecon()); telemetry.addData("pos X: ", TeamEllementPos.x); telemetry.addData("pos Y: ", TeamEllementPos.y); telemetry.update(); //if( positie,<SUF> } } }
True
False
1,333
902
43984_4
package nl.han.ica.oopd.bubbletrouble; import java.util.List; import java.util.Random; import nl.han.ica.oopg.collision.CollidedTile; import nl.han.ica.oopg.collision.CollisionSide; import nl.han.ica.oopg.collision.ICollidableWithGameObjects; import nl.han.ica.oopg.collision.ICollidableWithTiles; import nl.han.ica.oopg.exceptions.TileNotFoundException; import nl.han.ica.oopg.objects.GameObject; import nl.han.ica.oopg.objects.Sprite; import nl.han.ica.oopg.objects.SpriteObject; import processing.core.PGraphics; import processing.core.PVector; public class Bubble extends SpriteObject implements ICollidableWithTiles, ICollidableWithGameObjects { private BubbleTrouble bubbleTrouble; private Powerup powerupMovespeed; private Powerup powerupProjectilespeed; private Projectile projectile; private Player player; private Random random; private int bubbleSize; public Bubble(int bubbleSize, BubbleTrouble bubbleTrouble, Sprite sprite, Player player, Projectile projectile) { super(sprite); this.bubbleTrouble = bubbleTrouble; this.player = player; this.projectile = projectile; powerupMovespeed = new PowerupMoveSpeed(new Sprite("src/main/resources/bubble-trouble/movespeedpowerup.png"), bubbleTrouble, player); powerupProjectilespeed = new PowerupProjectileSpeed( new Sprite("src/main/resources/bubble-trouble/projectilespeedpowerup.png"), bubbleTrouble, player, projectile); this.bubbleSize = bubbleSize; random = new Random(); setGravity(0.20f); setySpeed(-bubbleSize / 10f); setxSpeed(-bubbleSize / 8f); setHeight(bubbleSize); setWidth(bubbleSize); } @Override public void update() { } @Override public void tileCollisionOccurred(List<CollidedTile> collidedTiles) { PVector vector; for (CollidedTile ct : collidedTiles) { if (ct.getTile() instanceof FloorTile) { try { if (CollisionSide.BOTTOM.equals(ct.getCollisionSide())) { vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile()); setY(vector.y - getHeight()); setySpeed(-getySpeed()); setDirection(225); } if (CollisionSide.LEFT.equals(ct.getCollisionSide())) { vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile()); setX(vector.x - getWidth()); setxSpeed(-getxSpeed()); setDirection(345); } if (CollisionSide.TOP.equals(ct.getCollisionSide())) { vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile()); setY(vector.y - getHeight()); setySpeed(-getySpeed()); if (getDirection() <= 180) { setDirection(15); } else { setDirection(345); } } if (CollisionSide.RIGHT.equals(ct.getCollisionSide())) { vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile()); System.out.println(bubbleSize); if (bubbleSize == 64) { setX(vector.x + getWidth()); } else if (bubbleSize == 32) { setX(vector.x + getWidth()+32); } else if (bubbleSize == 16) { setX(vector.x + getWidth()+64); } setxSpeed(-getxSpeed()); setDirection(15); } } catch (TileNotFoundException e) { e.printStackTrace(); } } } } @Override public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) { for (GameObject g : collidedGameObjects) { if (g instanceof Projectile || g instanceof ProjectileTrail) { // Projectile projectile = (Projectile) g; // bubbleTrouble.deleteGameObject(this); if (bubbleSize > 16) { System.out.println("Bubble groter dan 16: splitsen"); int smallerBubbleSize = bubbleSize / 2; Bubble newBubble1 = new Bubble(smallerBubbleSize, bubbleTrouble, new Sprite("src/main/resources/bubble-trouble/bubbleblue.png"), player, player.getProjectile()); newBubble1.setxSpeed(-getxSpeed()); // De twee nieuwe bubbles moeten verplaatst om te voorkomen dat ze direct weer // botsen. // En wellicht daardoor direct verdwijnen, omdat projectiel niet direct // verdwijnt bij botsing. // TODO: Mooier om in plaats hiervan nieuwe bubbels na aanmaken even tijdje // 'onbotsbaar te maken' // Dit via ander stukje bubble logica, dan verschieten ze niet opeens. final int VERPLAATSEN_BIJ_BOTSING = 40; newBubble1.setX(getX() + VERPLAATSEN_BIJ_BOTSING); newBubble1.setY(getY()); newBubble1.setySpeed(getySpeed()); bubbleTrouble.addGameObject(newBubble1); // Maak ook de huidige bubbel kleiner. this.bubbleSize = smallerBubbleSize; setWidth(bubbleSize); setX(getX() - VERPLAATSEN_BIJ_BOTSING); setHeight(bubbleSize); } else { bubbleTrouble.deleteGameObject(this); } int powerupRoll = random.nextInt(4); System.out.println(powerupRoll); if (powerupRoll == 0) { if (bubbleTrouble.isProjectilePowerupSpawned() == false) { bubbleTrouble.addGameObject(powerupProjectilespeed, getX(), getY() + 10); bubbleTrouble.setProjectilePowerupSpawned(true); } } else if (powerupRoll == 1) { if (bubbleTrouble.isMovespeedPowerupSpawned() == false) { bubbleTrouble.addGameObject(powerupMovespeed, getX(), getY() + 10); bubbleTrouble.setMovespeedPowerupSpawned(true); } } } else if (g instanceof Bubble) { // bubble } } } @Override public void draw(PGraphics g) { // g.fill(120, 120, 230); // g.ellipse(x, y, bubbleSize, bubbleSize); g.image(getImage(), x, y, getWidth(), getHeight()); } }
Kafune/oopd-bp-bubble-trouble
src/main/java/nl/han/ica/oopd/bubbletrouble/Bubble.java
2,025
// TODO: Mooier om in plaats hiervan nieuwe bubbels na aanmaken even tijdje
line_comment
nl
package nl.han.ica.oopd.bubbletrouble; import java.util.List; import java.util.Random; import nl.han.ica.oopg.collision.CollidedTile; import nl.han.ica.oopg.collision.CollisionSide; import nl.han.ica.oopg.collision.ICollidableWithGameObjects; import nl.han.ica.oopg.collision.ICollidableWithTiles; import nl.han.ica.oopg.exceptions.TileNotFoundException; import nl.han.ica.oopg.objects.GameObject; import nl.han.ica.oopg.objects.Sprite; import nl.han.ica.oopg.objects.SpriteObject; import processing.core.PGraphics; import processing.core.PVector; public class Bubble extends SpriteObject implements ICollidableWithTiles, ICollidableWithGameObjects { private BubbleTrouble bubbleTrouble; private Powerup powerupMovespeed; private Powerup powerupProjectilespeed; private Projectile projectile; private Player player; private Random random; private int bubbleSize; public Bubble(int bubbleSize, BubbleTrouble bubbleTrouble, Sprite sprite, Player player, Projectile projectile) { super(sprite); this.bubbleTrouble = bubbleTrouble; this.player = player; this.projectile = projectile; powerupMovespeed = new PowerupMoveSpeed(new Sprite("src/main/resources/bubble-trouble/movespeedpowerup.png"), bubbleTrouble, player); powerupProjectilespeed = new PowerupProjectileSpeed( new Sprite("src/main/resources/bubble-trouble/projectilespeedpowerup.png"), bubbleTrouble, player, projectile); this.bubbleSize = bubbleSize; random = new Random(); setGravity(0.20f); setySpeed(-bubbleSize / 10f); setxSpeed(-bubbleSize / 8f); setHeight(bubbleSize); setWidth(bubbleSize); } @Override public void update() { } @Override public void tileCollisionOccurred(List<CollidedTile> collidedTiles) { PVector vector; for (CollidedTile ct : collidedTiles) { if (ct.getTile() instanceof FloorTile) { try { if (CollisionSide.BOTTOM.equals(ct.getCollisionSide())) { vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile()); setY(vector.y - getHeight()); setySpeed(-getySpeed()); setDirection(225); } if (CollisionSide.LEFT.equals(ct.getCollisionSide())) { vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile()); setX(vector.x - getWidth()); setxSpeed(-getxSpeed()); setDirection(345); } if (CollisionSide.TOP.equals(ct.getCollisionSide())) { vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile()); setY(vector.y - getHeight()); setySpeed(-getySpeed()); if (getDirection() <= 180) { setDirection(15); } else { setDirection(345); } } if (CollisionSide.RIGHT.equals(ct.getCollisionSide())) { vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile()); System.out.println(bubbleSize); if (bubbleSize == 64) { setX(vector.x + getWidth()); } else if (bubbleSize == 32) { setX(vector.x + getWidth()+32); } else if (bubbleSize == 16) { setX(vector.x + getWidth()+64); } setxSpeed(-getxSpeed()); setDirection(15); } } catch (TileNotFoundException e) { e.printStackTrace(); } } } } @Override public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) { for (GameObject g : collidedGameObjects) { if (g instanceof Projectile || g instanceof ProjectileTrail) { // Projectile projectile = (Projectile) g; // bubbleTrouble.deleteGameObject(this); if (bubbleSize > 16) { System.out.println("Bubble groter dan 16: splitsen"); int smallerBubbleSize = bubbleSize / 2; Bubble newBubble1 = new Bubble(smallerBubbleSize, bubbleTrouble, new Sprite("src/main/resources/bubble-trouble/bubbleblue.png"), player, player.getProjectile()); newBubble1.setxSpeed(-getxSpeed()); // De twee nieuwe bubbles moeten verplaatst om te voorkomen dat ze direct weer // botsen. // En wellicht daardoor direct verdwijnen, omdat projectiel niet direct // verdwijnt bij botsing. // TODO: Mooier<SUF> // 'onbotsbaar te maken' // Dit via ander stukje bubble logica, dan verschieten ze niet opeens. final int VERPLAATSEN_BIJ_BOTSING = 40; newBubble1.setX(getX() + VERPLAATSEN_BIJ_BOTSING); newBubble1.setY(getY()); newBubble1.setySpeed(getySpeed()); bubbleTrouble.addGameObject(newBubble1); // Maak ook de huidige bubbel kleiner. this.bubbleSize = smallerBubbleSize; setWidth(bubbleSize); setX(getX() - VERPLAATSEN_BIJ_BOTSING); setHeight(bubbleSize); } else { bubbleTrouble.deleteGameObject(this); } int powerupRoll = random.nextInt(4); System.out.println(powerupRoll); if (powerupRoll == 0) { if (bubbleTrouble.isProjectilePowerupSpawned() == false) { bubbleTrouble.addGameObject(powerupProjectilespeed, getX(), getY() + 10); bubbleTrouble.setProjectilePowerupSpawned(true); } } else if (powerupRoll == 1) { if (bubbleTrouble.isMovespeedPowerupSpawned() == false) { bubbleTrouble.addGameObject(powerupMovespeed, getX(), getY() + 10); bubbleTrouble.setMovespeedPowerupSpawned(true); } } } else if (g instanceof Bubble) { // bubble } } } @Override public void draw(PGraphics g) { // g.fill(120, 120, 230); // g.ellipse(x, y, bubbleSize, bubbleSize); g.image(getImage(), x, y, getWidth(), getHeight()); } }
True
False
1,334
701
8349_7
package nl.hsleiden.game; import java.util.ArrayList; /** * Dit is een level. Hier kun je een aantal methoden aanroepen om informatie over het level te krijgen, * of om tiles en/of elementen toe te voegen aan het spel. * */ public class Level { private Tile[][] tiles; private ArrayList<Element> elements; private Element focusedElement; private ArrayList<Element> bufferedElements; public Level() { bufferedElements = new ArrayList<>(); } /** * @return het element dat door de camera gefocussed wordt. * */ public Element getFocusedElement() { return focusedElement; } /** * Set het element dat door de camera gefocussed moet worden. * @param focusedElement het element waarop gefocussed moet worden. * */ public void setFocusedElement(Element focusedElement) { this.focusedElement = focusedElement; } /** * Met deze methode kun je de tiles van dit level opvragen. * @return de tiles van dit level. * */ public Tile[][] getTiles() { return tiles; } /** * Met deze methode kun je de elementen van dit level opvragen. * @return de elementen van dit level. * */ public ArrayList<Element> getElements() { return elements; } /** * @return de breedte van het level. * */ public int getWidth() { return tiles[0].length * 80; } /** * @return de hoogte van het level. * */ public int getHeigt() { return tiles.length * 80; } /** * Plaats de tiles in dit level. * @param tiles de tiles die in dit level moeten. * */ public void setTiles(Tile[][] tiles) { this.tiles = tiles; } /** * Plaats de elements in dit level. * @param elements de tiles die in dit level moeten. * */ public void setElements(ArrayList<Element> elements) { this.elements = elements; } public void refreshElements(){ this.bufferedElements.clear(); this.bufferedElements.addAll(elements); } public ArrayList<Element> getBufferedElements() { return bufferedElements; } }
Hogeschool-Leiden/GameEngine
src/main/java/nl/hsleiden/game/Level.java
622
/** * Plaats de tiles in dit level. * @param tiles de tiles die in dit level moeten. * */
block_comment
nl
package nl.hsleiden.game; import java.util.ArrayList; /** * Dit is een level. Hier kun je een aantal methoden aanroepen om informatie over het level te krijgen, * of om tiles en/of elementen toe te voegen aan het spel. * */ public class Level { private Tile[][] tiles; private ArrayList<Element> elements; private Element focusedElement; private ArrayList<Element> bufferedElements; public Level() { bufferedElements = new ArrayList<>(); } /** * @return het element dat door de camera gefocussed wordt. * */ public Element getFocusedElement() { return focusedElement; } /** * Set het element dat door de camera gefocussed moet worden. * @param focusedElement het element waarop gefocussed moet worden. * */ public void setFocusedElement(Element focusedElement) { this.focusedElement = focusedElement; } /** * Met deze methode kun je de tiles van dit level opvragen. * @return de tiles van dit level. * */ public Tile[][] getTiles() { return tiles; } /** * Met deze methode kun je de elementen van dit level opvragen. * @return de elementen van dit level. * */ public ArrayList<Element> getElements() { return elements; } /** * @return de breedte van het level. * */ public int getWidth() { return tiles[0].length * 80; } /** * @return de hoogte van het level. * */ public int getHeigt() { return tiles.length * 80; } /** * Plaats de tiles<SUF>*/ public void setTiles(Tile[][] tiles) { this.tiles = tiles; } /** * Plaats de elements in dit level. * @param elements de tiles die in dit level moeten. * */ public void setElements(ArrayList<Element> elements) { this.elements = elements; } public void refreshElements(){ this.bufferedElements.clear(); this.bufferedElements.addAll(elements); } public ArrayList<Element> getBufferedElements() { return bufferedElements; } }
True
False
1,336
3,685
100994_2
package pipeline; public abstract class BasePipeline implements IPipeline{ private Boolean running = false; private Boolean success = false; protected BasePipeline(boolean autostart) { if(autostart){ this.startPipeline(); } } protected BasePipeline() { } @Override public void startPipeline(){ System.out.println("Started pipeline"); this.running = true; this.onPipelineStarts(); Boolean sourcesPhaseSuccess; try { sourcesPhaseSuccess = this.runSources(); }catch(Exception e){ sourcesPhaseSuccess = false; } if(Boolean.FALSE.equals(sourcesPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean packagePhaseSuccess; try { packagePhaseSuccess = this.runPackage(); }catch(Exception e){ packagePhaseSuccess = false; } if(Boolean.FALSE.equals(packagePhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean buildPhaseSuccess; try { buildPhaseSuccess = this.runBuild(); }catch(Exception e){ buildPhaseSuccess = false; } if(Boolean.FALSE.equals(buildPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean testPhaseSuccess; try { testPhaseSuccess = this.runTest(); }catch(Exception e){ testPhaseSuccess = false; } if(Boolean.FALSE.equals(testPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean analysisPhaseSuccess; try { analysisPhaseSuccess = this.runAnalysis(); }catch(Exception e){ analysisPhaseSuccess = false; } if(Boolean.FALSE.equals(analysisPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean deployPhaseSuccess; try { deployPhaseSuccess = this.runDeploy(); }catch(Exception e){ deployPhaseSuccess = false; } if(Boolean.FALSE.equals(deployPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean utilityPhaseSuccess; try { utilityPhaseSuccess = this.runUtility(); }catch(Exception e){ utilityPhaseSuccess = false; } if(Boolean.FALSE.equals(utilityPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } this.running = false; this.success = true; this.onPipelineEnds(); } @Override public void onPipelineStarts() { System.out.println("Callback not overriden"); } @Override public Boolean runSources() { System.out.println("1. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runPackage() { System.out.println("2. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runBuild() { System.out.println("3. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runTest() { System.out.println("4. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runAnalysis() { System.out.println("5. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runDeploy() { System.out.println("6. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runUtility() { System.out.println("7. Running this phases default activity. For different functionality, please override method on initialization."); return true; } @Override public void endPipeline(){ System.out.println("Ended pipeline"); this.running = false; this.onPipelineEnds(); } @Override public void onPipelineEnds() { // this.running = false; System.out.println("Callback not overriden"); if(this.getSuccess()){ this.onPipelineSuccess(); } else{ this.onPipelineFail(); } } @Override public void onPipelineSuccess(){ System.out.println("Pipepeline succeeded"); } @Override public void onPipelineFail(){ System.out.println("Pipeline failed"); } @Override public Boolean getRunning() { return running; } @Override public void setRunning(Boolean running) { this.running = running; } @Override public Boolean getSuccess() { return success; } @Override public void setSuccess(Boolean success) { this.success = success; } // TODO: Read this better and also keep this logic into account or somehting idk // Een deployment sprint is gekoppeld aan een development pipeline die eindigt met deployment. //Andere sprints kunnen ook worden gekoppeld aan een development pipeline die //automatisch/handmatig wordt uitgevoerd. Daarvan kan het einde ook deployment zijn (naar bv een //testomgeving), maar het kan ook eindigen na het uitvoeren van de tests en publicatie van //testresultaten. }
mjlpjacoavans/avans-devops-project
src/main/java/pipeline/BasePipeline.java
1,621
// Een deployment sprint is gekoppeld aan een development pipeline die eindigt met deployment.
line_comment
nl
package pipeline; public abstract class BasePipeline implements IPipeline{ private Boolean running = false; private Boolean success = false; protected BasePipeline(boolean autostart) { if(autostart){ this.startPipeline(); } } protected BasePipeline() { } @Override public void startPipeline(){ System.out.println("Started pipeline"); this.running = true; this.onPipelineStarts(); Boolean sourcesPhaseSuccess; try { sourcesPhaseSuccess = this.runSources(); }catch(Exception e){ sourcesPhaseSuccess = false; } if(Boolean.FALSE.equals(sourcesPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean packagePhaseSuccess; try { packagePhaseSuccess = this.runPackage(); }catch(Exception e){ packagePhaseSuccess = false; } if(Boolean.FALSE.equals(packagePhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean buildPhaseSuccess; try { buildPhaseSuccess = this.runBuild(); }catch(Exception e){ buildPhaseSuccess = false; } if(Boolean.FALSE.equals(buildPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean testPhaseSuccess; try { testPhaseSuccess = this.runTest(); }catch(Exception e){ testPhaseSuccess = false; } if(Boolean.FALSE.equals(testPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean analysisPhaseSuccess; try { analysisPhaseSuccess = this.runAnalysis(); }catch(Exception e){ analysisPhaseSuccess = false; } if(Boolean.FALSE.equals(analysisPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean deployPhaseSuccess; try { deployPhaseSuccess = this.runDeploy(); }catch(Exception e){ deployPhaseSuccess = false; } if(Boolean.FALSE.equals(deployPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } Boolean utilityPhaseSuccess; try { utilityPhaseSuccess = this.runUtility(); }catch(Exception e){ utilityPhaseSuccess = false; } if(Boolean.FALSE.equals(utilityPhaseSuccess)){ this.running = false; this.success = false; this.onPipelineEnds(); return; } this.running = false; this.success = true; this.onPipelineEnds(); } @Override public void onPipelineStarts() { System.out.println("Callback not overriden"); } @Override public Boolean runSources() { System.out.println("1. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runPackage() { System.out.println("2. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runBuild() { System.out.println("3. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runTest() { System.out.println("4. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runAnalysis() { System.out.println("5. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runDeploy() { System.out.println("6. Running this phases default activity. For defferent fcuntionality, please override methon on initialization."); return true; } @Override public Boolean runUtility() { System.out.println("7. Running this phases default activity. For different functionality, please override method on initialization."); return true; } @Override public void endPipeline(){ System.out.println("Ended pipeline"); this.running = false; this.onPipelineEnds(); } @Override public void onPipelineEnds() { // this.running = false; System.out.println("Callback not overriden"); if(this.getSuccess()){ this.onPipelineSuccess(); } else{ this.onPipelineFail(); } } @Override public void onPipelineSuccess(){ System.out.println("Pipepeline succeeded"); } @Override public void onPipelineFail(){ System.out.println("Pipeline failed"); } @Override public Boolean getRunning() { return running; } @Override public void setRunning(Boolean running) { this.running = running; } @Override public Boolean getSuccess() { return success; } @Override public void setSuccess(Boolean success) { this.success = success; } // TODO: Read this better and also keep this logic into account or somehting idk // Een deployment<SUF> //Andere sprints kunnen ook worden gekoppeld aan een development pipeline die //automatisch/handmatig wordt uitgevoerd. Daarvan kan het einde ook deployment zijn (naar bv een //testomgeving), maar het kan ook eindigen na het uitvoeren van de tests en publicatie van //testresultaten. }
True
False
1,337
2,997
23390_5
package novi.basics; import java.util.Scanner; public class Main { public static Scanner PLAYERINPUT = new Scanner(System.in); public static void main(String[] args) { // -- vanaf hier gaan we het spel opnieuw spelen met andere spelers (nadat op het eind keuze 2 gekozen is) // de 1e speler om zijn naam vragen System.out.println("Player 1, what is your name?"); // de naam van de 1e speler opslaan String player1Name = PLAYERINPUT.next(); Player player1 = new Player(player1Name,'x'); // de 2e speler om zijn naam vragen System.out.println("Player 2, what is your name?"); // de naam van de 2e speler opslaan String player2Name = PLAYERINPUT.next(); Player player2 = new Player(player2Name,'o'); TicTacToe game = new TicTacToe(player1, player2); int spelkeuze; spelkeuze = ChooseGame(); if (spelkeuze == 1) { TicTactoe.play(); } else { TripleDigits.play; } // speler spel laten kiezen --> TicTacToe of TripleDigits } // vragen of de spelers nog een keer willen spelen //1: nog een keer spelen //2: van spelers wisselen //3: afsluiten // speler keuze opslaan // bij keuze 1: terug naar het maken van het bord // bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen // bij keuze 3: het spel en de applicatie helemaal afsluiten } private static int ChooseGame() { System.out.println("Which game do you wish to play?"); System.out.println("Press 1 for Tictactoe or press 2 for TripleDigits"); Scanner welkspel = new Scanner(System.in); int inputInt; inputInt = welkspel.nextInt(); return inputInt; } }
hogeschoolnovi/tic-tac-toe-SunshineSummerville
src/novi/basics/Main.java
578
// speler spel laten kiezen --> TicTacToe of TripleDigits
line_comment
nl
package novi.basics; import java.util.Scanner; public class Main { public static Scanner PLAYERINPUT = new Scanner(System.in); public static void main(String[] args) { // -- vanaf hier gaan we het spel opnieuw spelen met andere spelers (nadat op het eind keuze 2 gekozen is) // de 1e speler om zijn naam vragen System.out.println("Player 1, what is your name?"); // de naam van de 1e speler opslaan String player1Name = PLAYERINPUT.next(); Player player1 = new Player(player1Name,'x'); // de 2e speler om zijn naam vragen System.out.println("Player 2, what is your name?"); // de naam van de 2e speler opslaan String player2Name = PLAYERINPUT.next(); Player player2 = new Player(player2Name,'o'); TicTacToe game = new TicTacToe(player1, player2); int spelkeuze; spelkeuze = ChooseGame(); if (spelkeuze == 1) { TicTactoe.play(); } else { TripleDigits.play; } // speler spel<SUF> } // vragen of de spelers nog een keer willen spelen //1: nog een keer spelen //2: van spelers wisselen //3: afsluiten // speler keuze opslaan // bij keuze 1: terug naar het maken van het bord // bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen // bij keuze 3: het spel en de applicatie helemaal afsluiten } private static int ChooseGame() { System.out.println("Which game do you wish to play?"); System.out.println("Press 1 for Tictactoe or press 2 for TripleDigits"); Scanner welkspel = new Scanner(System.in); int inputInt; inputInt = welkspel.nextInt(); return inputInt; } }
True
False
1,341
1,237
74014_3
package HZ2_TimeOfDay; import static org.junit.jupiter.api.Assertions.*; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; class MyMathTest { /** * Returns the square root (rounded down) of the given nonnegative number. * * @pre The given number must be nonnegative. * | 0 <= x * @post The result is the greatest nonnegative integer whose square is not greater than the given number. * | 0 <= result && * | result * result <= x && * | x < (result + 1) * (result + 1) */ int sqrt(int x) { int result = 0; while ((result + 1) * (result + 1) <= x) result++; return result; } /** * Geeft het grootste van de drie gegeven getallen terug. * * @post Het resultaat is groeter dan of gelijk aan de gegeven getallen. * | result >= x && result >= y && result >= z * @post Het resultaat is gelijk aan één van de gegeven getallen. * | result == x || result == y || result == z */ int max3(int x, int y, int z) { return x > y ? x > z ? x : z : y > z ? y : z; } /** * Geeft de mediaan van de drie verschillende gegeven getallen terug. * TODO: Schrijf volledige formele documentatie. */ int mediaan(int x, int y, int z) { return 0; // TODO: Implementeer. } /** * Geeft het aantal voorkomens van 'waarde' in 'getallen' terug. * @pre Het argument `getallen` wijst naar een array; het is geen null-verwijzing. * | getallen != null * @post Het resultaat is gelijk aan het aantal indices in `getallen` waarop `waarde` voorkomt. * | result == IntStream.range(0, getallen.length).filter(i -> getallen[i] == waarde).count() */ int tel(int[] getallen, int waarde) { int result = 0; for (int i = 0; i < getallen.length; i++) if (getallen[i] == waarde) result++; return result; } /** * Verhoogt het element op index `index` in array `array` met `bedrag`. * * @pre Het argument `array` wijst naar een array. * | array != null * @pre De gegeven index is een geldige index voor `array`. * | 0 <= index && index < array.length * @post De waarde in `array` op de gegeven index is gelijk aan de oude waarde plus het gegeven bedrag. * | array[index] == old(array[index]) + bedrag */ void verhoogElement(int[] array, int index, int bedrag) { array[index] += bedrag; } /** * Verwisselt de elementen op de gegeven indices in de gegeven array met elkaar. * TODO: Schrijf volledige informele en formele documentatie. */ void verwissel(int[] getallen, int index1, int index2) { // TODO: Implementeer } /** * Vervangt elk getal in de gegeven array door zijn negatie. * @pre Het argument `getallen` wijst naar een array. * | getallen != null * @post Voor elke positie in `getallen` geldt dat de nieuwe waarde op die positie gelijk is aan de negatie van de oude waarde op die positie. * | IntStream.range(0, getallen.length).allMatch(i -> getallen[i] == -old(getallen.clone())[i]) */ // voeg bovenaan (tussen de package-regel en de class-regel) 'import java.util.stream.IntStream;' toe als Eclipse dit niet zelf doet. void negatie(int[] getallen) { for (int i = 0; i < getallen.length; i++) getallen[i] = -getallen[i]; } /** * Geeft de index terug van het eerste voorkomen van `needle` in `haystack`, of -1 als `needle` niet voorkomt in `haystack`. * * @pre | haystack != null * @post Als de needle zich op index 0 bevindt, dan is het resultaat gelijk aan 0 (Deze postconditie is een speciaal geval van de laatste, ter illustratie.) * | !(haystack.length > 0 && haystack[0] == needle) || result == 0 * @post Als het resultaat -1 is, dan ... * | result != -1 || IntStream.range(0, haystack.length).allMatch(i -> haystack[i] != needle) * @post Als het resultaat niet -1 is, dan ... * | result == -1 || true // VERVANG 'true' DOOR DE VOORWAARDE */ int find(int[] haystack, int needle) { return 0; // TODO: Implementeer } /** * Sorteert de getallen in de gegeven array van klein naar groot. * @post VUL AAN * | true // VUL AAN */ void sort(int[] values) { // TODO: Implementeer } @Test void testSqrt() { assertEquals(3, sqrt(9)); assertEquals(0, sqrt(0)); assertEquals(3, sqrt(15)); assertEquals(4, sqrt(16)); } @Test void testMax3() { assertEquals(30, max3(10, 20, 30)); assertEquals(30, max3(20, 10, 30)); assertEquals(30, max3(10, 30, 20)); assertEquals(30, max3(20, 30, 10)); assertEquals(30, max3(30, 10, 20)); assertEquals(30, max3(30, 20, 10)); } // TODO: Schrijf grondige tests voor mediaan, verwissel, find, en sort. @Test void testTel() { assertEquals(0, tel(new int[] {10, 20, 30}, 15)); assertEquals(1, tel(new int[] {10, 20, 30}, 20)); assertEquals(2, tel(new int[] {10, 20, 30, 20}, 20)); assertEquals(3, tel(new int[] {10, 20, 10, 30, 10}, 10)); } @Test void testVerhoogElement() { int[] mijnArray = {10, 20, 30}; verhoogElement(mijnArray, 1, 5); assertArrayEquals(new int[] {10, 25, 30}, mijnArray); } @Test void testNegatie() { int[] mijnArray = {10, -20, 30}; negatie(mijnArray); assertArrayEquals(new int[] {-10, 20, -30}, mijnArray); } }
OndaLH/OGP
OGP/src/HZ2_TimeOfDay/MyMathTest.java
1,958
/** * Geeft het aantal voorkomens van 'waarde' in 'getallen' terug. * @pre Het argument `getallen` wijst naar een array; het is geen null-verwijzing. * | getallen != null * @post Het resultaat is gelijk aan het aantal indices in `getallen` waarop `waarde` voorkomt. * | result == IntStream.range(0, getallen.length).filter(i -> getallen[i] == waarde).count() */
block_comment
nl
package HZ2_TimeOfDay; import static org.junit.jupiter.api.Assertions.*; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; class MyMathTest { /** * Returns the square root (rounded down) of the given nonnegative number. * * @pre The given number must be nonnegative. * | 0 <= x * @post The result is the greatest nonnegative integer whose square is not greater than the given number. * | 0 <= result && * | result * result <= x && * | x < (result + 1) * (result + 1) */ int sqrt(int x) { int result = 0; while ((result + 1) * (result + 1) <= x) result++; return result; } /** * Geeft het grootste van de drie gegeven getallen terug. * * @post Het resultaat is groeter dan of gelijk aan de gegeven getallen. * | result >= x && result >= y && result >= z * @post Het resultaat is gelijk aan één van de gegeven getallen. * | result == x || result == y || result == z */ int max3(int x, int y, int z) { return x > y ? x > z ? x : z : y > z ? y : z; } /** * Geeft de mediaan van de drie verschillende gegeven getallen terug. * TODO: Schrijf volledige formele documentatie. */ int mediaan(int x, int y, int z) { return 0; // TODO: Implementeer. } /** * Geeft het aantal<SUF>*/ int tel(int[] getallen, int waarde) { int result = 0; for (int i = 0; i < getallen.length; i++) if (getallen[i] == waarde) result++; return result; } /** * Verhoogt het element op index `index` in array `array` met `bedrag`. * * @pre Het argument `array` wijst naar een array. * | array != null * @pre De gegeven index is een geldige index voor `array`. * | 0 <= index && index < array.length * @post De waarde in `array` op de gegeven index is gelijk aan de oude waarde plus het gegeven bedrag. * | array[index] == old(array[index]) + bedrag */ void verhoogElement(int[] array, int index, int bedrag) { array[index] += bedrag; } /** * Verwisselt de elementen op de gegeven indices in de gegeven array met elkaar. * TODO: Schrijf volledige informele en formele documentatie. */ void verwissel(int[] getallen, int index1, int index2) { // TODO: Implementeer } /** * Vervangt elk getal in de gegeven array door zijn negatie. * @pre Het argument `getallen` wijst naar een array. * | getallen != null * @post Voor elke positie in `getallen` geldt dat de nieuwe waarde op die positie gelijk is aan de negatie van de oude waarde op die positie. * | IntStream.range(0, getallen.length).allMatch(i -> getallen[i] == -old(getallen.clone())[i]) */ // voeg bovenaan (tussen de package-regel en de class-regel) 'import java.util.stream.IntStream;' toe als Eclipse dit niet zelf doet. void negatie(int[] getallen) { for (int i = 0; i < getallen.length; i++) getallen[i] = -getallen[i]; } /** * Geeft de index terug van het eerste voorkomen van `needle` in `haystack`, of -1 als `needle` niet voorkomt in `haystack`. * * @pre | haystack != null * @post Als de needle zich op index 0 bevindt, dan is het resultaat gelijk aan 0 (Deze postconditie is een speciaal geval van de laatste, ter illustratie.) * | !(haystack.length > 0 && haystack[0] == needle) || result == 0 * @post Als het resultaat -1 is, dan ... * | result != -1 || IntStream.range(0, haystack.length).allMatch(i -> haystack[i] != needle) * @post Als het resultaat niet -1 is, dan ... * | result == -1 || true // VERVANG 'true' DOOR DE VOORWAARDE */ int find(int[] haystack, int needle) { return 0; // TODO: Implementeer } /** * Sorteert de getallen in de gegeven array van klein naar groot. * @post VUL AAN * | true // VUL AAN */ void sort(int[] values) { // TODO: Implementeer } @Test void testSqrt() { assertEquals(3, sqrt(9)); assertEquals(0, sqrt(0)); assertEquals(3, sqrt(15)); assertEquals(4, sqrt(16)); } @Test void testMax3() { assertEquals(30, max3(10, 20, 30)); assertEquals(30, max3(20, 10, 30)); assertEquals(30, max3(10, 30, 20)); assertEquals(30, max3(20, 30, 10)); assertEquals(30, max3(30, 10, 20)); assertEquals(30, max3(30, 20, 10)); } // TODO: Schrijf grondige tests voor mediaan, verwissel, find, en sort. @Test void testTel() { assertEquals(0, tel(new int[] {10, 20, 30}, 15)); assertEquals(1, tel(new int[] {10, 20, 30}, 20)); assertEquals(2, tel(new int[] {10, 20, 30, 20}, 20)); assertEquals(3, tel(new int[] {10, 20, 10, 30, 10}, 10)); } @Test void testVerhoogElement() { int[] mijnArray = {10, 20, 30}; verhoogElement(mijnArray, 1, 5); assertArrayEquals(new int[] {10, 25, 30}, mijnArray); } @Test void testNegatie() { int[] mijnArray = {10, -20, 30}; negatie(mijnArray); assertArrayEquals(new int[] {-10, 20, -30}, mijnArray); } }
True
False
1,343
1,414
70576_15
import greenfoot.*; import java.util.List; /** * * @author R. Springer */ public class TileEngine { public static int TILE_WIDTH; public static int TILE_HEIGHT; public static int SCREEN_HEIGHT; public static int SCREEN_WIDTH; public static int MAP_WIDTH; public static int MAP_HEIGHT; public static boolean isSolid = true; private World world; private int[][] map; private Tile[][] generateMap; private TileFactory tileFactory; /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations */ public TileEngine(World world, int tileWidth, int tileHeight) { this.world = world; TILE_WIDTH = tileWidth; TILE_HEIGHT = tileHeight; SCREEN_WIDTH = world.getWidth(); SCREEN_HEIGHT = world.getHeight(); this.tileFactory = new TileFactory(); } /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations * @param map A tilemap with numbers */ public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) { this(world, tileWidth, tileHeight); this.setMap(map); } /** * The setMap method used to set a map. This method also clears the previous * map and generates a new one. * * @param map */ public void setMap(int[][] map) { this.clearTilesWorld(); this.map = map; MAP_HEIGHT = this.map.length; MAP_WIDTH = this.map[0].length; this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH]; this.generateWorld(); } /** * The setTileFactory sets a tilefactory. You can use this if you want to * create you own tilefacory and use it in the class. * * @param tf A Tilefactory or extend of it. */ public void setTileFactory(TileFactory tf) { this.tileFactory = tf; } /** * Removes al the tiles from the world. */ public void clearTilesWorld() { List<Tile> removeObjects = this.world.getObjects(Tile.class); this.world.removeObjects(removeObjects); this.map = null; this.generateMap = null; MAP_HEIGHT = 0; MAP_WIDTH = 0; } /** * Creates the tile world based on the TileFactory and the map icons. */ public void generateWorld() { int mapID = 0; for (int y = 0; y < MAP_HEIGHT; y++) { for (int x = 0; x < MAP_WIDTH; x++) { // Nummer ophalen in de int array mapID++; int mapIcon = this.map[y][x]; if (mapIcon == -1) { continue; } // Als de mapIcon -1 is dan wordt de code hieronder overgeslagen // Dus er wordt geen tile aangemaakt. -1 is dus geen tile; Tile createdTile = this.tileFactory.createTile(mapIcon); createdTile.setMapID(mapID); createdTile.setMapIcon(mapIcon); addTileAt(createdTile, x, y); } } } /** * Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and * TILE_HEIGHT * * @param tile The Tile * @param colom The colom where the tile exist in the map * @param row The row where the tile exist in the map */ public void addTileAt(Tile tile, int colom, int row) { // De X en Y positie zitten het midden van de Actor. // De tilemap genereerd een wereld gebaseerd op dat de X en Y // positie links boven in zitten. Vandaar de we de helft van de // breedte en hoogte optellen zodat de X en Y links boven zit voor // het toevoegen van het object. this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2); // Toevoegen aan onze lokale array. Makkelijk om de tile op te halen // op basis van een x en y positie van de map this.generateMap[row][colom] = tile; tile.setColom(colom); tile.setRow(row); } /** * Retrieves a tile at the location based on colom and row in the map * * @param colom * @param row * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return null; } return this.generateMap[row][colom]; } /** * Retrieves a tile based on a x and y position in the world * * @param x X-position in the world * @param y Y-position in the world * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); Tile tile = getTileAt(col, row); return tile; } /** * Removes tile at the given colom and row * * @param colom * @param row * @return true if the tile has successfully been removed */ public boolean removeTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return false; } Tile tile = this.generateMap[row][colom]; if (tile != null) { this.world.removeObject(tile); this.generateMap[row][colom] = null; return true; } return false; } /** * Removes tile at the given x and y position * * @param x X-position in the world * @param y Y-position in the world * @return true if the tile has successfully been removed */ public boolean removeTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); return removeTileAt(col, row); } /** * Removes the tile based on a tile * * @param tile Tile from the tilemap * @return true if the tile has successfully been removed */ public boolean removeTile(Tile tile) { int colom = tile.getColom(); int row = tile.getRow(); if (colom != -1 && row != -1) { return this.removeTileAt(colom, row); } return false; } /** * This methode checks if a tile on a x and y position in the world is solid * or not. * * @param x X-position in the world * @param y Y-position in the world * @return Tile at location is solid */ public boolean checkTileSolid(int x, int y) { Tile tile = getTileAtXY(x, y); if (tile != null && tile.isSolid) { return true; } return false; } /** * This methode returns a colom based on a x position. * * @param x * @return the colom */ public int getColumn(int x) { return (int) Math.floor(x / TILE_WIDTH); } /** * This methode returns a row based on a y position. * * @param y * @return the row */ public int getRow(int y) { return (int) Math.floor(y / TILE_HEIGHT); } /** * This methode returns a x position based on the colom * * @param col * @return The x position */ public int getX(int col) { return col * TILE_WIDTH; } /** * This methode returns a y position based on the row * * @param row * @return The y position */ public int getY(int row) { return row * TILE_HEIGHT; } }
ROCMondriaanTIN/project-greenfoot-game-ilyassahr
TileEngine.java
2,436
// het toevoegen van het object.
line_comment
nl
import greenfoot.*; import java.util.List; /** * * @author R. Springer */ public class TileEngine { public static int TILE_WIDTH; public static int TILE_HEIGHT; public static int SCREEN_HEIGHT; public static int SCREEN_WIDTH; public static int MAP_WIDTH; public static int MAP_HEIGHT; public static boolean isSolid = true; private World world; private int[][] map; private Tile[][] generateMap; private TileFactory tileFactory; /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations */ public TileEngine(World world, int tileWidth, int tileHeight) { this.world = world; TILE_WIDTH = tileWidth; TILE_HEIGHT = tileHeight; SCREEN_WIDTH = world.getWidth(); SCREEN_HEIGHT = world.getHeight(); this.tileFactory = new TileFactory(); } /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations * @param map A tilemap with numbers */ public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) { this(world, tileWidth, tileHeight); this.setMap(map); } /** * The setMap method used to set a map. This method also clears the previous * map and generates a new one. * * @param map */ public void setMap(int[][] map) { this.clearTilesWorld(); this.map = map; MAP_HEIGHT = this.map.length; MAP_WIDTH = this.map[0].length; this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH]; this.generateWorld(); } /** * The setTileFactory sets a tilefactory. You can use this if you want to * create you own tilefacory and use it in the class. * * @param tf A Tilefactory or extend of it. */ public void setTileFactory(TileFactory tf) { this.tileFactory = tf; } /** * Removes al the tiles from the world. */ public void clearTilesWorld() { List<Tile> removeObjects = this.world.getObjects(Tile.class); this.world.removeObjects(removeObjects); this.map = null; this.generateMap = null; MAP_HEIGHT = 0; MAP_WIDTH = 0; } /** * Creates the tile world based on the TileFactory and the map icons. */ public void generateWorld() { int mapID = 0; for (int y = 0; y < MAP_HEIGHT; y++) { for (int x = 0; x < MAP_WIDTH; x++) { // Nummer ophalen in de int array mapID++; int mapIcon = this.map[y][x]; if (mapIcon == -1) { continue; } // Als de mapIcon -1 is dan wordt de code hieronder overgeslagen // Dus er wordt geen tile aangemaakt. -1 is dus geen tile; Tile createdTile = this.tileFactory.createTile(mapIcon); createdTile.setMapID(mapID); createdTile.setMapIcon(mapIcon); addTileAt(createdTile, x, y); } } } /** * Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and * TILE_HEIGHT * * @param tile The Tile * @param colom The colom where the tile exist in the map * @param row The row where the tile exist in the map */ public void addTileAt(Tile tile, int colom, int row) { // De X en Y positie zitten het midden van de Actor. // De tilemap genereerd een wereld gebaseerd op dat de X en Y // positie links boven in zitten. Vandaar de we de helft van de // breedte en hoogte optellen zodat de X en Y links boven zit voor // het toevoegen<SUF> this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2); // Toevoegen aan onze lokale array. Makkelijk om de tile op te halen // op basis van een x en y positie van de map this.generateMap[row][colom] = tile; tile.setColom(colom); tile.setRow(row); } /** * Retrieves a tile at the location based on colom and row in the map * * @param colom * @param row * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return null; } return this.generateMap[row][colom]; } /** * Retrieves a tile based on a x and y position in the world * * @param x X-position in the world * @param y Y-position in the world * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); Tile tile = getTileAt(col, row); return tile; } /** * Removes tile at the given colom and row * * @param colom * @param row * @return true if the tile has successfully been removed */ public boolean removeTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return false; } Tile tile = this.generateMap[row][colom]; if (tile != null) { this.world.removeObject(tile); this.generateMap[row][colom] = null; return true; } return false; } /** * Removes tile at the given x and y position * * @param x X-position in the world * @param y Y-position in the world * @return true if the tile has successfully been removed */ public boolean removeTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); return removeTileAt(col, row); } /** * Removes the tile based on a tile * * @param tile Tile from the tilemap * @return true if the tile has successfully been removed */ public boolean removeTile(Tile tile) { int colom = tile.getColom(); int row = tile.getRow(); if (colom != -1 && row != -1) { return this.removeTileAt(colom, row); } return false; } /** * This methode checks if a tile on a x and y position in the world is solid * or not. * * @param x X-position in the world * @param y Y-position in the world * @return Tile at location is solid */ public boolean checkTileSolid(int x, int y) { Tile tile = getTileAtXY(x, y); if (tile != null && tile.isSolid) { return true; } return false; } /** * This methode returns a colom based on a x position. * * @param x * @return the colom */ public int getColumn(int x) { return (int) Math.floor(x / TILE_WIDTH); } /** * This methode returns a row based on a y position. * * @param y * @return the row */ public int getRow(int y) { return (int) Math.floor(y / TILE_HEIGHT); } /** * This methode returns a x position based on the colom * * @param col * @return The x position */ public int getX(int col) { return col * TILE_WIDTH; } /** * This methode returns a y position based on the row * * @param row * @return The y position */ public int getY(int row) { return row * TILE_HEIGHT; } }
True
False
1,344
3,728
39965_6
_x000D_ package domeinLaag;_x000D_ _x000D_ // Imports_x000D_ import java.util.HashSet;_x000D_ import java.util.Iterator;_x000D_ import java.util.TreeMap;_x000D_ _x000D_ /**_x000D_ * Een object van deze klasse representeert één luchthaven._x000D_ * Een Luchthaven heeft een naam en een code (afkorting)._x000D_ * Eventueel heeft de luchthaven ook een werkplaats._x000D_ * Tot slot ligt de luchthaven in een land._x000D_ */_x000D_ public class Luchthaven_x000D_ {_x000D_ // Attributes_x000D_ private String naam = ""; // De naam van de luchthaven._x000D_ private String code = ""; // De code (afkorting) van de luchthaven._x000D_ private boolean werkPlaats = false; // Of de luchthaven een werkplaats heeft of niet._x000D_ _x000D_ // Relaties_x000D_ private Land land; // In welk land de luchthaven ligt._x000D_ private static HashSet<Luchthaven> alleLuchthavens = new HashSet<Luchthaven>(); // Een statische HashSet van alle luchthavens._x000D_ _x000D_ // Constructors_x000D_ /**_x000D_ * Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt door Main om de boel even te vullen._x000D_ * Dit zodat er ook wat te testen valt._x000D_ * @param nm de naam van de luchthaven_x000D_ * @param cd de code (afkorting) van de luchthaven_x000D_ * @param wp true als de luchthaven een werkplaats heeft, anders false_x000D_ * @param ln het land waar de luchthaven in ligt_x000D_ */_x000D_ public Luchthaven (String nm, String cd, boolean wp, Land ln)_x000D_ {_x000D_ this.naam = nm;_x000D_ this.code = cd;_x000D_ this.werkPlaats = wp;_x000D_ this.land = ln;_x000D_ alleLuchthavens.add(this);_x000D_ land.addLuchthaven(this);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt om in_x000D_ * de RegLuchthavenController. De diverse attributen worden met zet-methoden naderhand gevuld._x000D_ */_x000D_ public Luchthaven ()_x000D_ {_x000D_ } _x000D_ _x000D_ // Setters_x000D_ /**_x000D_ * Deze methode zet de naam van het Luchthaven._x000D_ * @param nm de naam van de Luchthaven_x000D_ * @throws java.lang.IllegalArgumentException als de naam al bestaat in dat land_x000D_ * of als de naam geen geldige waarde heeft_x000D_ */_x000D_ public void setNaam (String nm) throws IllegalArgumentException_x000D_ {_x000D_ if (land.getLuchthavens().get(nm.trim()) != null)_x000D_ {_x000D_ throw new IllegalArgumentException("Naam bestaat al!");_x000D_ }_x000D_ else if (nm.trim().length() == 0)_x000D_ {_x000D_ throw new IllegalArgumentException("Naam heeft geen geldige waarde!");_x000D_ }_x000D_ else_x000D_ {_x000D_ this.naam = nm.trim();_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode zet de code (afkorting) van de Luchthaven._x000D_ * @param code de code (afkorting) van de Luchthaven_x000D_ */_x000D_ public void setCode (String code)_x000D_ {_x000D_ this.code = code;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode zet het land waar de Luchthaven in ligt._x000D_ * Hiertoe moet ook een aanpassing gedaan worden in het land._x000D_ * Eerst moet de luchthaven namelijk uit het oude land verwijderd worden._x000D_ * Het toevoegen aan het nieuwe land (en het verwijderen uit het oude) hoeft_x000D_ * alleen te gebeuren als de luchthaven al aan alleLuchthavens toegevoegd._x000D_ * Zo niet, dan deze luchthaven namelijk nog nooit bewaard._x000D_ * @param land het land waar de Luchthaven in ligt_x000D_ */_x000D_ public void setLand (Land land)_x000D_ {_x000D_ if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard._x000D_ {_x000D_ this.land.removeLuchthaven(this); // Eerst de luchthaven verwijderen uit het oude land._x000D_ }_x000D_ this.land = land; // Vervolgens het land veranderen._x000D_ if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard._x000D_ {_x000D_ this.land.addLuchthaven(this); // Tot slot de luchthaven toevoegen aan het nieuwe land._x000D_ }_x000D_ } _x000D_ _x000D_ /**_x000D_ * Deze methode zet of de Luchthaven een werkplaats heeft of niet._x000D_ * @param wp true als de Luchthaven een werkplaats heeft en anders false_x000D_ */_x000D_ public void setWerkPlaats (boolean wp)_x000D_ {_x000D_ werkPlaats = wp;_x000D_ } _x000D_ _x000D_ // Getters_x000D_ /**_x000D_ * Deze methode geeft de naam van de Luchthaven._x000D_ * @return de naam van de Luchthaven_x000D_ */_x000D_ public String getNaam ()_x000D_ {_x000D_ return naam;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode geeft de code van de Luchthaven._x000D_ * @return de code (afkorting) van de Luchthaven_x000D_ */_x000D_ public String getCode ()_x000D_ {_x000D_ return this.code;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode geeft true als er een werkplaats is en anders false._x000D_ * @return true als er een werkplaats is op de Luchthaven_x000D_ */_x000D_ public boolean getWerkPlaats ()_x000D_ {_x000D_ return werkPlaats;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode geeft het Land waar de Luchthaven ligt._x000D_ * @return het Land waar de Luchthaven ligt_x000D_ */_x000D_ public Land getLand ()_x000D_ {_x000D_ return land;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze statische methode geeft alle luchthavennamen en Luchthavens terug._x000D_ * @return een TreeMap van luchthavennamen en Luchthavens_x000D_ */_x000D_ public static TreeMap<String, Luchthaven> getAlleLuchthavens ()_x000D_ {_x000D_ TreeMap<String, Luchthaven> alleLh = new TreeMap<String, Luchthaven>();_x000D_ for (Iterator<Luchthaven> i = alleLuchthavens.iterator(); i.hasNext();)_x000D_ {_x000D_ Luchthaven lh = i.next();_x000D_ alleLh.put(lh.naam, lh);_x000D_ }_x000D_ return alleLh;_x000D_ } _x000D_ _x000D_ // Overige Methodes_x000D_ /**_x000D_ * Deze methode bewaart deze Luchthaven door hem toe te voegen aan de Luchthavens van het land en alleLuchthavens._x000D_ * @throws domeinLaag.LuchthavenException als nog niet alle attributen een waarde hebben_x000D_ */_x000D_ public void bewaar () throws LuchthavenException_x000D_ {_x000D_ if (land == null)_x000D_ {_x000D_ throw new LuchthavenException("Land niet ingevuld!");_x000D_ }_x000D_ else if (naam.isEmpty())_x000D_ {_x000D_ throw new LuchthavenException("Naam niet ingevuld!");_x000D_ }_x000D_ else if (code.isEmpty())_x000D_ {_x000D_ throw new LuchthavenException("Code niet ingevuld!");_x000D_ }_x000D_ else_x000D_ {_x000D_ alleLuchthavens.add(this);_x000D_ land.addLuchthaven(this);_x000D_ }_x000D_ }_x000D_ }_x000D_
mpkossen/1ooto1project
src/domeinLaag/Luchthaven.java
2,024
/**_x000D_ * Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt door Main om de boel even te vullen._x000D_ * Dit zodat er ook wat te testen valt._x000D_ * @param nm de naam van de luchthaven_x000D_ * @param cd de code (afkorting) van de luchthaven_x000D_ * @param wp true als de luchthaven een werkplaats heeft, anders false_x000D_ * @param ln het land waar de luchthaven in ligt_x000D_ */
block_comment
nl
_x000D_ package domeinLaag;_x000D_ _x000D_ // Imports_x000D_ import java.util.HashSet;_x000D_ import java.util.Iterator;_x000D_ import java.util.TreeMap;_x000D_ _x000D_ /**_x000D_ * Een object van deze klasse representeert één luchthaven._x000D_ * Een Luchthaven heeft een naam en een code (afkorting)._x000D_ * Eventueel heeft de luchthaven ook een werkplaats._x000D_ * Tot slot ligt de luchthaven in een land._x000D_ */_x000D_ public class Luchthaven_x000D_ {_x000D_ // Attributes_x000D_ private String naam = ""; // De naam van de luchthaven._x000D_ private String code = ""; // De code (afkorting) van de luchthaven._x000D_ private boolean werkPlaats = false; // Of de luchthaven een werkplaats heeft of niet._x000D_ _x000D_ // Relaties_x000D_ private Land land; // In welk land de luchthaven ligt._x000D_ private static HashSet<Luchthaven> alleLuchthavens = new HashSet<Luchthaven>(); // Een statische HashSet van alle luchthavens._x000D_ _x000D_ // Constructors_x000D_ /**_x000D_ * Constructor voor het<SUF>*/_x000D_ public Luchthaven (String nm, String cd, boolean wp, Land ln)_x000D_ {_x000D_ this.naam = nm;_x000D_ this.code = cd;_x000D_ this.werkPlaats = wp;_x000D_ this.land = ln;_x000D_ alleLuchthavens.add(this);_x000D_ land.addLuchthaven(this);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt om in_x000D_ * de RegLuchthavenController. De diverse attributen worden met zet-methoden naderhand gevuld._x000D_ */_x000D_ public Luchthaven ()_x000D_ {_x000D_ } _x000D_ _x000D_ // Setters_x000D_ /**_x000D_ * Deze methode zet de naam van het Luchthaven._x000D_ * @param nm de naam van de Luchthaven_x000D_ * @throws java.lang.IllegalArgumentException als de naam al bestaat in dat land_x000D_ * of als de naam geen geldige waarde heeft_x000D_ */_x000D_ public void setNaam (String nm) throws IllegalArgumentException_x000D_ {_x000D_ if (land.getLuchthavens().get(nm.trim()) != null)_x000D_ {_x000D_ throw new IllegalArgumentException("Naam bestaat al!");_x000D_ }_x000D_ else if (nm.trim().length() == 0)_x000D_ {_x000D_ throw new IllegalArgumentException("Naam heeft geen geldige waarde!");_x000D_ }_x000D_ else_x000D_ {_x000D_ this.naam = nm.trim();_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode zet de code (afkorting) van de Luchthaven._x000D_ * @param code de code (afkorting) van de Luchthaven_x000D_ */_x000D_ public void setCode (String code)_x000D_ {_x000D_ this.code = code;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode zet het land waar de Luchthaven in ligt._x000D_ * Hiertoe moet ook een aanpassing gedaan worden in het land._x000D_ * Eerst moet de luchthaven namelijk uit het oude land verwijderd worden._x000D_ * Het toevoegen aan het nieuwe land (en het verwijderen uit het oude) hoeft_x000D_ * alleen te gebeuren als de luchthaven al aan alleLuchthavens toegevoegd._x000D_ * Zo niet, dan deze luchthaven namelijk nog nooit bewaard._x000D_ * @param land het land waar de Luchthaven in ligt_x000D_ */_x000D_ public void setLand (Land land)_x000D_ {_x000D_ if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard._x000D_ {_x000D_ this.land.removeLuchthaven(this); // Eerst de luchthaven verwijderen uit het oude land._x000D_ }_x000D_ this.land = land; // Vervolgens het land veranderen._x000D_ if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard._x000D_ {_x000D_ this.land.addLuchthaven(this); // Tot slot de luchthaven toevoegen aan het nieuwe land._x000D_ }_x000D_ } _x000D_ _x000D_ /**_x000D_ * Deze methode zet of de Luchthaven een werkplaats heeft of niet._x000D_ * @param wp true als de Luchthaven een werkplaats heeft en anders false_x000D_ */_x000D_ public void setWerkPlaats (boolean wp)_x000D_ {_x000D_ werkPlaats = wp;_x000D_ } _x000D_ _x000D_ // Getters_x000D_ /**_x000D_ * Deze methode geeft de naam van de Luchthaven._x000D_ * @return de naam van de Luchthaven_x000D_ */_x000D_ public String getNaam ()_x000D_ {_x000D_ return naam;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode geeft de code van de Luchthaven._x000D_ * @return de code (afkorting) van de Luchthaven_x000D_ */_x000D_ public String getCode ()_x000D_ {_x000D_ return this.code;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode geeft true als er een werkplaats is en anders false._x000D_ * @return true als er een werkplaats is op de Luchthaven_x000D_ */_x000D_ public boolean getWerkPlaats ()_x000D_ {_x000D_ return werkPlaats;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode geeft het Land waar de Luchthaven ligt._x000D_ * @return het Land waar de Luchthaven ligt_x000D_ */_x000D_ public Land getLand ()_x000D_ {_x000D_ return land;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze statische methode geeft alle luchthavennamen en Luchthavens terug._x000D_ * @return een TreeMap van luchthavennamen en Luchthavens_x000D_ */_x000D_ public static TreeMap<String, Luchthaven> getAlleLuchthavens ()_x000D_ {_x000D_ TreeMap<String, Luchthaven> alleLh = new TreeMap<String, Luchthaven>();_x000D_ for (Iterator<Luchthaven> i = alleLuchthavens.iterator(); i.hasNext();)_x000D_ {_x000D_ Luchthaven lh = i.next();_x000D_ alleLh.put(lh.naam, lh);_x000D_ }_x000D_ return alleLh;_x000D_ } _x000D_ _x000D_ // Overige Methodes_x000D_ /**_x000D_ * Deze methode bewaart deze Luchthaven door hem toe te voegen aan de Luchthavens van het land en alleLuchthavens._x000D_ * @throws domeinLaag.LuchthavenException als nog niet alle attributen een waarde hebben_x000D_ */_x000D_ public void bewaar () throws LuchthavenException_x000D_ {_x000D_ if (land == null)_x000D_ {_x000D_ throw new LuchthavenException("Land niet ingevuld!");_x000D_ }_x000D_ else if (naam.isEmpty())_x000D_ {_x000D_ throw new LuchthavenException("Naam niet ingevuld!");_x000D_ }_x000D_ else if (code.isEmpty())_x000D_ {_x000D_ throw new LuchthavenException("Code niet ingevuld!");_x000D_ }_x000D_ else_x000D_ {_x000D_ alleLuchthavens.add(this);_x000D_ land.addLuchthaven(this);_x000D_ }_x000D_ }_x000D_ }_x000D_
True
False
1,359
2,959
74879_0
package nl.novi.javaprogrammeren; import nl.novi.javaprogrammeren.overerving.Rocket; import nl.novi.javaprogrammeren.overerving.SpaceXRocket; public class Main { /* Bekijk onderstaande code. Er zijn twee klasse, twee objecten. SpaceXRocket extends Rocket. Op dit moment vliegen beide raketten 100 meter per 1 fuel-eenheid. Pas de code zo aan dat de SpaceXRocket 150 meter per 1 fuel-eendheid omhoog gaat. Gebruik hiervoor super() of Override. Je hoeft alleen code aan te passen in SpaceXRocket */ public static void main(String[] args) { Rocket genericRocket = new Rocket(100); genericRocket.fly(10); System.out.println(genericRocket.toString()); SpaceXRocket spaceXRocket = new SpaceXRocket(100); spaceXRocket.fly(10); System.out.println(spaceXRocket.toString()); } }
hogeschoolnovi/SD-BE-JP-Overerving-01a
src/nl/novi/javaprogrammeren/Main.java
285
/* Bekijk onderstaande code. Er zijn twee klasse, twee objecten. SpaceXRocket extends Rocket. Op dit moment vliegen beide raketten 100 meter per 1 fuel-eenheid. Pas de code zo aan dat de SpaceXRocket 150 meter per 1 fuel-eendheid omhoog gaat. Gebruik hiervoor super() of Override. Je hoeft alleen code aan te passen in SpaceXRocket */
block_comment
nl
package nl.novi.javaprogrammeren; import nl.novi.javaprogrammeren.overerving.Rocket; import nl.novi.javaprogrammeren.overerving.SpaceXRocket; public class Main { /* Bekijk onderstaande code.<SUF>*/ public static void main(String[] args) { Rocket genericRocket = new Rocket(100); genericRocket.fly(10); System.out.println(genericRocket.toString()); SpaceXRocket spaceXRocket = new SpaceXRocket(100); spaceXRocket.fly(10); System.out.println(spaceXRocket.toString()); } }
True
False
1,364
4,084
52511_0
package ui.view; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class ValidHtmlTest { private WebDriver driver; @Before public void setUp() { // vul hier JOUW pad naar chromedriver in // Voor Windows (vergeet "\" niet te escapen met een tweede "\") // System.setProperty("webdriver.chrome.driver", "C:\\Users\\...\\chromedriver.exe"); // Voor mac: System.setProperty("webdriver.chrome.driver", "C:\\Applications\\chromedriver\\chromedriver.exe"); driver = new ChromeDriver(); } @After public void clean() { driver.quit(); } @Test // Voer deze test uit als je je project opgeladen hebt public void isValidHtml() { driver.get("https://validator.w3.org/#validate_by_uri+with_options"); WebElement invulveld = driver.findElement(By.id("uri")); // verander naar de url die je wil valideren invulveld.sendKeys("https://webontwerp.ucll.be/web1/reeksen/"); Select dropdown = new Select(driver.findElement(By.id("uri-doctype"))); dropdown.selectByValue("HTML5"); WebElement button = driver.findElement(By.cssSelector(".submit_button")); button.click(); WebElement pass = driver.findElement(By.cssSelector("p.success")); assertEquals("Document checking completed. No errors or warnings to show.", pass.getText()); } }
quinten-bosch/Web-2-Labo
Labo 3 GET en Selenium/src/test/java/ui/view/ValidHtmlTest.java
526
// vul hier JOUW pad naar chromedriver in
line_comment
nl
package ui.view; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class ValidHtmlTest { private WebDriver driver; @Before public void setUp() { // vul hier<SUF> // Voor Windows (vergeet "\" niet te escapen met een tweede "\") // System.setProperty("webdriver.chrome.driver", "C:\\Users\\...\\chromedriver.exe"); // Voor mac: System.setProperty("webdriver.chrome.driver", "C:\\Applications\\chromedriver\\chromedriver.exe"); driver = new ChromeDriver(); } @After public void clean() { driver.quit(); } @Test // Voer deze test uit als je je project opgeladen hebt public void isValidHtml() { driver.get("https://validator.w3.org/#validate_by_uri+with_options"); WebElement invulveld = driver.findElement(By.id("uri")); // verander naar de url die je wil valideren invulveld.sendKeys("https://webontwerp.ucll.be/web1/reeksen/"); Select dropdown = new Select(driver.findElement(By.id("uri-doctype"))); dropdown.selectByValue("HTML5"); WebElement button = driver.findElement(By.cssSelector(".submit_button")); button.click(); WebElement pass = driver.findElement(By.cssSelector("p.success")); assertEquals("Document checking completed. No errors or warnings to show.", pass.getText()); } }
True
False
1,367
367
41440_24
import java.util.*; //importeren van java.util_x000D_ import java.io.*; //importeren van java.io_x000D_ _x000D_ public class Phonebook {_x000D_ Vector <Person> people;_x000D_ int n; //class variable omdat het niet in de methode zelf mocht voor recursie_x000D_ _x000D_ public Phonebook(String file) {_x000D_ people = new Vector <Person> ();_x000D_ read(file);_x000D_ }_x000D_ _x000D_ public void read (String file) {//begin functie inlezen bestand_x000D_ try {//try catch voor fouten_x000D_ File bestandnaam = new File(file); //bestandsnaam doorgeven_x000D_ Scanner lezer = new Scanner(bestandnaam); //scanner voor het inlezen van het bestand_x000D_ while (lezer.hasNextLine()) {//while loop om door alle regels in het bestand te gaan_x000D_ String data = lezer.nextLine(); //volgende line in het bestand _x000D_ StringTokenizer st = new StringTokenizer(data, ",");//naam los van de nummers maken in tokenizer_x000D_ Person L = new Person(st.nextToken(), st.nextToken());//object L aanmaken en de naam en het nummer erin invoegen _x000D_ people.add(L); //naam toevoegen aan vector_x000D_ }_x000D_ lezer.close();_x000D_ } catch (Exception error) {// als er een fout gevonden is_x000D_ System.out.println("Fout gevonden.");_x000D_ error.printStackTrace();_x000D_ }_x000D_ }_x000D_ _x000D_ public String toString() {_x000D_ String allesin1 = ""; //lege string die gevuld wordt met de namen en nummers_x000D_ for (Person L: people) {//loop om door alle people te gaan_x000D_ //printen van name en number in de vector die onderdeel zijn van class Person_x000D_ allesin1 = allesin1 + L.name + " " + L.number + "\n";_x000D_ }_x000D_ return allesin1; //returnen van de string met alles erin _x000D_ }_x000D_ _x000D_ public String number(String name) {_x000D_ for (Person L: people) {//loop om door alle people te gaan_x000D_ if (name.equals(L.name)) {_x000D_ return L.name + " " + L.number;_x000D_ }_x000D_ }_x000D_ return "Geen overeenkomsten gevonden."; //als er geen overeenkomsten zijn_x000D_ _x000D_ _x000D_ }_x000D_ _x000D_ public void sort(){_x000D_ n = people.size();_x000D_ people = sort(people);//eerste aanroep recursie_x000D_ _x000D_ _x000D_ }_x000D_ private Vector <Person> sort (Vector <Person> tosort) {_x000D_ _x000D_ //Bubblesort base case_x000D_ if (n == 1) {_x000D_ return tosort;_x000D_ }//body_x000D_ int count = 0; //zodat de recursie niet onnodig in wordt gegaan_x000D_ for (int i = 0; i < n-1; i++) {_x000D_ Person P = tosort.get(i); //haalt huidige in de vector op_x000D_ Person L = tosort.get(i+1); // haalt de volgende in de vector op_x000D_ String s2 = P.name; //zet type person om in string name_x000D_ String s1 = L.name; //zet type person om in string name_x000D_ if (isSmaller(s1, s2)) { //isSmaller om te vergelijken of s1 kleiner is dan s2 _x000D_ tosort.set(i, L); // draait de namen om_x000D_ tosort.set(i + 1, P);_x000D_ count = count +1;_x000D_ }_x000D_ }_x000D_ if (count == 0) {_x000D_ return tosort;_x000D_ }_x000D_ n = n-1;_x000D_ return sort(tosort);// recursie_x000D_ }_x000D_ private boolean isSmaller (String s1, String s2) {_x000D_ // returns true if s1 <s2 alphabetically_x000D_ _x000D_ boolean builtdifferent = false; //boolean voor de while loop_x000D_ boolean iskleiner = false; //boolean voor als s1 kleiner is dan s2 dus s2 bovenaan moet zijn_x000D_ int i = 0;//teller om de letters te vergelijken op pos i in de string_x000D_ while (!builtdifferent) {//while loop die doorgaat tot er een verschil is tussen de 2 strings_x000D_ if (s1.toLowerCase().charAt(i) != s2.toLowerCase().charAt(i)) {_x000D_ if ((int)s1.toLowerCase().charAt(i) < (int)s2.toLowerCase().charAt(i)) {// hoe lager getal hoe eerder alfabet_x000D_ iskleiner = true; //als s1 kleiner is dan s2_x000D_ }_x000D_ builtdifferent = true; //voor het eindigen van de while loop_x000D_ _x000D_ }else {_x000D_ i++; //om door te gaan naar het volgende character van de string_x000D_ }_x000D_ }_x000D_ return iskleiner;_x000D_ _x000D_ }_x000D_ }_x000D_
DMR-max/symbolic-AI-0
Phonebook.java
1,271
//zet type person om in string name_x000D_
line_comment
nl
import java.util.*; //importeren van java.util_x000D_ import java.io.*; //importeren van java.io_x000D_ _x000D_ public class Phonebook {_x000D_ Vector <Person> people;_x000D_ int n; //class variable omdat het niet in de methode zelf mocht voor recursie_x000D_ _x000D_ public Phonebook(String file) {_x000D_ people = new Vector <Person> ();_x000D_ read(file);_x000D_ }_x000D_ _x000D_ public void read (String file) {//begin functie inlezen bestand_x000D_ try {//try catch voor fouten_x000D_ File bestandnaam = new File(file); //bestandsnaam doorgeven_x000D_ Scanner lezer = new Scanner(bestandnaam); //scanner voor het inlezen van het bestand_x000D_ while (lezer.hasNextLine()) {//while loop om door alle regels in het bestand te gaan_x000D_ String data = lezer.nextLine(); //volgende line in het bestand _x000D_ StringTokenizer st = new StringTokenizer(data, ",");//naam los van de nummers maken in tokenizer_x000D_ Person L = new Person(st.nextToken(), st.nextToken());//object L aanmaken en de naam en het nummer erin invoegen _x000D_ people.add(L); //naam toevoegen aan vector_x000D_ }_x000D_ lezer.close();_x000D_ } catch (Exception error) {// als er een fout gevonden is_x000D_ System.out.println("Fout gevonden.");_x000D_ error.printStackTrace();_x000D_ }_x000D_ }_x000D_ _x000D_ public String toString() {_x000D_ String allesin1 = ""; //lege string die gevuld wordt met de namen en nummers_x000D_ for (Person L: people) {//loop om door alle people te gaan_x000D_ //printen van name en number in de vector die onderdeel zijn van class Person_x000D_ allesin1 = allesin1 + L.name + " " + L.number + "\n";_x000D_ }_x000D_ return allesin1; //returnen van de string met alles erin _x000D_ }_x000D_ _x000D_ public String number(String name) {_x000D_ for (Person L: people) {//loop om door alle people te gaan_x000D_ if (name.equals(L.name)) {_x000D_ return L.name + " " + L.number;_x000D_ }_x000D_ }_x000D_ return "Geen overeenkomsten gevonden."; //als er geen overeenkomsten zijn_x000D_ _x000D_ _x000D_ }_x000D_ _x000D_ public void sort(){_x000D_ n = people.size();_x000D_ people = sort(people);//eerste aanroep recursie_x000D_ _x000D_ _x000D_ }_x000D_ private Vector <Person> sort (Vector <Person> tosort) {_x000D_ _x000D_ //Bubblesort base case_x000D_ if (n == 1) {_x000D_ return tosort;_x000D_ }//body_x000D_ int count = 0; //zodat de recursie niet onnodig in wordt gegaan_x000D_ for (int i = 0; i < n-1; i++) {_x000D_ Person P = tosort.get(i); //haalt huidige in de vector op_x000D_ Person L = tosort.get(i+1); // haalt de volgende in de vector op_x000D_ String s2 = P.name; //zet type person om in string name_x000D_ String s1 = L.name; //zet type<SUF> if (isSmaller(s1, s2)) { //isSmaller om te vergelijken of s1 kleiner is dan s2 _x000D_ tosort.set(i, L); // draait de namen om_x000D_ tosort.set(i + 1, P);_x000D_ count = count +1;_x000D_ }_x000D_ }_x000D_ if (count == 0) {_x000D_ return tosort;_x000D_ }_x000D_ n = n-1;_x000D_ return sort(tosort);// recursie_x000D_ }_x000D_ private boolean isSmaller (String s1, String s2) {_x000D_ // returns true if s1 <s2 alphabetically_x000D_ _x000D_ boolean builtdifferent = false; //boolean voor de while loop_x000D_ boolean iskleiner = false; //boolean voor als s1 kleiner is dan s2 dus s2 bovenaan moet zijn_x000D_ int i = 0;//teller om de letters te vergelijken op pos i in de string_x000D_ while (!builtdifferent) {//while loop die doorgaat tot er een verschil is tussen de 2 strings_x000D_ if (s1.toLowerCase().charAt(i) != s2.toLowerCase().charAt(i)) {_x000D_ if ((int)s1.toLowerCase().charAt(i) < (int)s2.toLowerCase().charAt(i)) {// hoe lager getal hoe eerder alfabet_x000D_ iskleiner = true; //als s1 kleiner is dan s2_x000D_ }_x000D_ builtdifferent = true; //voor het eindigen van de while loop_x000D_ _x000D_ }else {_x000D_ i++; //om door te gaan naar het volgende character van de string_x000D_ }_x000D_ }_x000D_ return iskleiner;_x000D_ _x000D_ }_x000D_ }_x000D_
True
False
1,368
3,402
45216_8
package repairshop; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class TestRepairshop { public static void main(String[] args) throws IOException { Repairshop r1 = new Repairshop(); Klant k1 = new Klant("Jos","De Wolf", "04/52455313" ,"[email protected]"); Klant k2 = new Klant("Jes","De vis", "04/52455313" ,"[email protected]"); Bedrijf b1 = new Bedrijf("Jef","De Kat","04/2369745","bedr@opn&co.com","opn&co"); Item i1 = new Item("horloge", "geeft tijd niet goed aan",50, "bezig met reparatie"); Item i2 = new Item("Jas","mouw gescheurd",100,"bezig met reparatie"); Item i3 = new Item("autozetels","versleten(gescheurd, krakken,...)",500,"in werking"); // corrigeert statussen naar statussen dat ik in andere methods gebruik i1.corigeerstatus(); i2.corigeerstatus(); i3.corigeerstatus(); // klant brengt item binnen k1.addItem(i1); k1.addItem(i2); b1.addItem(i3); // alle items van een klant die binnen zijn k1.showItems(); System.out.println("------------"); // zorgt ervoor dat een item klaar is met reparatie i1.statusComplete(); k1.showItems(); System.out.println("------------"); // klant kan met een status opzoeken en zien welke items mezig zijn met reparatie of klaar om op te halen System.out.println(k1.searchItem("bezig met reparatie")); System.out.println("------------"); // korting op prijs System.out.println(k1.kortingscoupon(i1)); System.out.println(b1.kortingscoupon(i3)); System.out.println("--------------"); // onders functie staat in commentaar omdat hij een nieuwe map op uw computer maakt met daarin een txt bestand // // de file komt op uw c schijf terecht dan user/username/ dan zal er een mapje bijgekomen zijn repairshop met een txt bestand met daarin klant // r1.WriteObjectToFile(k1); // // // btw op prijs zodat klant weet wat hij/zij uiteintelijk betaalt k1.betaling(i3); b1.betaling(i3); System.out.println("--------------"); // voeg item toe aan hashmap r1.wachtrij(i1); r1.wachtrij(i2); // laat alle items zien in hashmap System.out.println(r1.getItems()); // verwijder items die klaar zijn r1.deleteKlaar(); System.out.println(r1.getItems()); System.out.println("---------------"); // zet klant in hasmap r1.voegKlantToe(k1); r1.voegKlantToe(k2); r1.voegKlantToe(b1); // System.out.println(r1.getContacten()); System.out.println("-------------------"); // print klant uit met al zijn items die in de winkel is r1.klantEnHunItems(); r1.ExportToCSV(); } }
kristofmoons/repairshop
src/repairshop/TestRepairshop.java
948
// btw op prijs zodat klant weet wat hij/zij uiteintelijk betaalt
line_comment
nl
package repairshop; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class TestRepairshop { public static void main(String[] args) throws IOException { Repairshop r1 = new Repairshop(); Klant k1 = new Klant("Jos","De Wolf", "04/52455313" ,"[email protected]"); Klant k2 = new Klant("Jes","De vis", "04/52455313" ,"[email protected]"); Bedrijf b1 = new Bedrijf("Jef","De Kat","04/2369745","bedr@opn&co.com","opn&co"); Item i1 = new Item("horloge", "geeft tijd niet goed aan",50, "bezig met reparatie"); Item i2 = new Item("Jas","mouw gescheurd",100,"bezig met reparatie"); Item i3 = new Item("autozetels","versleten(gescheurd, krakken,...)",500,"in werking"); // corrigeert statussen naar statussen dat ik in andere methods gebruik i1.corigeerstatus(); i2.corigeerstatus(); i3.corigeerstatus(); // klant brengt item binnen k1.addItem(i1); k1.addItem(i2); b1.addItem(i3); // alle items van een klant die binnen zijn k1.showItems(); System.out.println("------------"); // zorgt ervoor dat een item klaar is met reparatie i1.statusComplete(); k1.showItems(); System.out.println("------------"); // klant kan met een status opzoeken en zien welke items mezig zijn met reparatie of klaar om op te halen System.out.println(k1.searchItem("bezig met reparatie")); System.out.println("------------"); // korting op prijs System.out.println(k1.kortingscoupon(i1)); System.out.println(b1.kortingscoupon(i3)); System.out.println("--------------"); // onders functie staat in commentaar omdat hij een nieuwe map op uw computer maakt met daarin een txt bestand // // de file komt op uw c schijf terecht dan user/username/ dan zal er een mapje bijgekomen zijn repairshop met een txt bestand met daarin klant // r1.WriteObjectToFile(k1); // // // btw op<SUF> k1.betaling(i3); b1.betaling(i3); System.out.println("--------------"); // voeg item toe aan hashmap r1.wachtrij(i1); r1.wachtrij(i2); // laat alle items zien in hashmap System.out.println(r1.getItems()); // verwijder items die klaar zijn r1.deleteKlaar(); System.out.println(r1.getItems()); System.out.println("---------------"); // zet klant in hasmap r1.voegKlantToe(k1); r1.voegKlantToe(k2); r1.voegKlantToe(b1); // System.out.println(r1.getContacten()); System.out.println("-------------------"); // print klant uit met al zijn items die in de winkel is r1.klantEnHunItems(); r1.ExportToCSV(); } }
True
False
1,371
110
43508_11
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.exceptions.RecordNotFoundException; import nl.novi.techiteasy.models.Television; import nl.novi.techiteasy.repositories.TelevisionRepository; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; import java.util.List; import java.util.Optional; @RestController // @RequestMapping("/persons") // Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen public class TelevisionController { // Vorige week maakten we nog gebruik van een List<String>, nu gebruiken we de repository met een echte database. // We injecteren de repository hier via de constructor, maar je mag ook @Autowired gebruiken. private final TelevisionRepository televisionRepository; // Constructor injection public TelevisionController(TelevisionRepository televisionRepository) { this.televisionRepository = televisionRepository; } // Show all televisions @GetMapping("/televisions") public ResponseEntity<List<Television>> getAllTelevisions(@RequestParam(value = "brand", required = false) String brand) { // Of ResponseEntity<String> List<Television> televisions; // Als geen merk ingevuld, geen parameters, geef dan alle entries weer. if (brand == null) { // Vul de televisions lijst met alle televisions televisions = televisionRepository.findAll(); // Als wel een merk ingevuld, geef dan alle televisies van dit merk weer } else { // Vul de televisions lijst met alle television die een bepaald merk hebben televisions = televisionRepository.findAllTelevisionsByBrandEqualsIgnoreCase(brand); } // return ResponseEntity.ok().body(televisions); return new ResponseEntity<>(televisions, HttpStatus.OK); // 200 OK } // Geef 1 television met een specifieke id weer @GetMapping("televisions/{id}") public ResponseEntity<Television> getTelevision(@PathVariable("id") Long id) { // Verschil met: @PathVariable int id? // Haal de television met het gegeven id uit de database. // Het Optional datatype betekend "wel of niet". Als er geen television gevonden wordt, dan is de Optional empty, // maar als er wel een television gevonden wordt, dan staat de television in de Optional en kun je deze er uit // halen met de get-methode. Op deze manier krijg je niet meteen een error als de tv niet in de database voorkomt. // Je kunt dat probleem zelf oplossen. In dit geval doen we dat door een RecordNotFoundException op te gooien met een message. Optional<Television> television = televisionRepository.findById(id); // Check of de optional empty is. Het tegenovergestelde alternatief is "television.isPresent()" if (television.isEmpty()) { // Als er geen television in de optional staat, roepen we hier de RecordNotFoundException constructor aan met message. throw new RecordNotFoundException("No television found with id: " + id); } else { // Als er wel een television in de optional staat, dan halen we die uit de optional met de get-methode. Television television1 = television.get(); // Haal het uit de optional en stop het in television1 // Return de television en een 200 status return ResponseEntity.ok().body(television1); } } // We geven hier een television mee in de parameter. Zorg dat je JSON object exact overeenkomt met het Television object. @PostMapping("/televisions") public ResponseEntity<Television> addTelevision(@RequestBody Television television) { // Er vanuit gaande dat televisies direct in de applicatie worden toegevoegd als ze gekocht zijn. television.setOriginalStock(LocalDate.now()); // Wat doet dit in de database? // Sla de nieuwe tv in de database op met de save-methode van de repository Television returnTelevision = televisionRepository.save(television); // Hier moet eigen nog een URI uri response. // Return de gemaakte television en een 201 status return ResponseEntity.created(null).body(returnTelevision); } @DeleteMapping("/televisions/{id}") public ResponseEntity<Object> deleteTelevision(@PathVariable("id") Long id) { // Verwijder de television met het opgegeven id uit de database. televisionRepository.deleteById(id); // Return een 204 status return ResponseEntity.noContent().build(); } // Update a television @PutMapping("/televisions/{id}") public ResponseEntity<Television> updateTelevision(@PathVariable Long id, @RequestBody Television newTelevision) { // Haal de aan te passen tv uit de database met het gegeven id Optional<Television> television = televisionRepository.findById(id); // Als eerste checken we of de aan te passen tv wel in de database bestaat. if (television.isEmpty()) { throw new RecordNotFoundException("No television found with id: " + id); } else { // Verander alle waardes van de television uit de database naar de waardes van de television uit de parameters. // Behalve de id. Als je de id veranderd, dan wordt er een nieuw object gemaakt in de database. Television television1 = television.get(); television1.setAvailableSize(newTelevision.getAvailableSize()); television1.setAmbiLight(newTelevision.getAmbiLight()); television1.setBluetooth(newTelevision.getBluetooth()); television1.setBrand(newTelevision.getBrand()); television1.setHdr(newTelevision.getHdr()); television1.setName(newTelevision.getName()); television1.setOriginalStock(newTelevision.getOriginalStock()); television1.setPrice(newTelevision.getPrice()); television1.setRefreshRate(newTelevision.getRefreshRate()); television1.setScreenQuality(newTelevision.getScreenQuality()); television1.setScreenType(newTelevision.getScreenType()); television1.setSmartTv(newTelevision.getSmartTv()); television1.setSold(newTelevision.getSold()); television1.setType(newTelevision.getType()); television1.setVoiceControl(newTelevision.getVoiceControl()); television1.setWifi(newTelevision.getWifi()); // Sla de gewijzigde waarden op in de database onder dezelfde id. Dit moet je niet vergeten. Television returnTelevision = televisionRepository.save(television1); // Return de nieuwe versie van deze tv en een 200 code return ResponseEntity.ok().body(returnTelevision); } } // Televisie gedeeltelijk bijwerken @PatchMapping("/televisions/{id}") public ResponseEntity<Television> updatePartialTelevision(@PathVariable Long id, @RequestBody Television newTelevision) { Optional<Television> television = televisionRepository.findById(id); if (television.isEmpty()) { throw new RecordNotFoundException("No television found with id: " + id); } else { // Het verschil tussen een patch en een put methode is dat een put een compleet object update, // waar een patch een gedeeltelijk object kan updaten. // Zet alles in een null-check, om te voorkomen dat je perongelijk bestaande waardes overschrijft met null-waardes. // Intellij heeft een handige postfix voor null-checks. Dit doe je door bijvoorbeeld "newTelevision.getBrand().notnull" te typen en dan op tab te drukken. Television television1 = television.get(); if (newTelevision.getAmbiLight() != null) { television1.setAmbiLight(newTelevision.getAmbiLight()); } if (newTelevision.getAvailableSize() != null) { television1.setAvailableSize(newTelevision.getAvailableSize()); } if (newTelevision.getBluetooth()) { television1.setBluetooth(newTelevision.getBluetooth()); } if (newTelevision.getBrand() != null) { television1.setBrand(newTelevision.getBrand()); } if (newTelevision.getHdr() != null) { television1.setHdr(newTelevision.getHdr()); } if (newTelevision.getName() != null) { television1.setName(newTelevision.getName()); } if (newTelevision.getOriginalStock() != null) { television1.setOriginalStock(newTelevision.getOriginalStock()); } if (newTelevision.getPrice() != null) { television1.setPrice(newTelevision.getPrice()); } if (newTelevision.getRefreshRate() != null) { television1.setRefreshRate(newTelevision.getRefreshRate()); } if (newTelevision.getScreenQuality() != null) { television1.setScreenQuality(newTelevision.getScreenQuality()); } if (newTelevision.getScreenType() != null) { television1.setScreenType(newTelevision.getScreenType()); } if (newTelevision.getSmartTv() != null) { television1.setSmartTv(newTelevision.getSmartTv()); } if (newTelevision.getSold() != null) { television1.setSold(newTelevision.getSold()); } if (newTelevision.getType() != null) { television1.setType(newTelevision.getType()); } if (newTelevision.getVoiceControl() != null) { television1.setVoiceControl(newTelevision.getVoiceControl()); } if (newTelevision.getWifi() != null) { television1.setWifi(newTelevision.getWifi()); } Television returnTelevision = televisionRepository.save(television1); return ResponseEntity.ok().body(returnTelevision); } } }
Aphelion-im/Les-11-uitwerking-opdracht-backend-spring-boot-tech-it-easy-model
src/main/java/nl/novi/techiteasy/controllers/TelevisionController.java
2,825
// Het Optional datatype betekend "wel of niet". Als er geen television gevonden wordt, dan is de Optional empty,
line_comment
nl
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.exceptions.RecordNotFoundException; import nl.novi.techiteasy.models.Television; import nl.novi.techiteasy.repositories.TelevisionRepository; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; import java.util.List; import java.util.Optional; @RestController // @RequestMapping("/persons") // Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen public class TelevisionController { // Vorige week maakten we nog gebruik van een List<String>, nu gebruiken we de repository met een echte database. // We injecteren de repository hier via de constructor, maar je mag ook @Autowired gebruiken. private final TelevisionRepository televisionRepository; // Constructor injection public TelevisionController(TelevisionRepository televisionRepository) { this.televisionRepository = televisionRepository; } // Show all televisions @GetMapping("/televisions") public ResponseEntity<List<Television>> getAllTelevisions(@RequestParam(value = "brand", required = false) String brand) { // Of ResponseEntity<String> List<Television> televisions; // Als geen merk ingevuld, geen parameters, geef dan alle entries weer. if (brand == null) { // Vul de televisions lijst met alle televisions televisions = televisionRepository.findAll(); // Als wel een merk ingevuld, geef dan alle televisies van dit merk weer } else { // Vul de televisions lijst met alle television die een bepaald merk hebben televisions = televisionRepository.findAllTelevisionsByBrandEqualsIgnoreCase(brand); } // return ResponseEntity.ok().body(televisions); return new ResponseEntity<>(televisions, HttpStatus.OK); // 200 OK } // Geef 1 television met een specifieke id weer @GetMapping("televisions/{id}") public ResponseEntity<Television> getTelevision(@PathVariable("id") Long id) { // Verschil met: @PathVariable int id? // Haal de television met het gegeven id uit de database. // Het Optional<SUF> // maar als er wel een television gevonden wordt, dan staat de television in de Optional en kun je deze er uit // halen met de get-methode. Op deze manier krijg je niet meteen een error als de tv niet in de database voorkomt. // Je kunt dat probleem zelf oplossen. In dit geval doen we dat door een RecordNotFoundException op te gooien met een message. Optional<Television> television = televisionRepository.findById(id); // Check of de optional empty is. Het tegenovergestelde alternatief is "television.isPresent()" if (television.isEmpty()) { // Als er geen television in de optional staat, roepen we hier de RecordNotFoundException constructor aan met message. throw new RecordNotFoundException("No television found with id: " + id); } else { // Als er wel een television in de optional staat, dan halen we die uit de optional met de get-methode. Television television1 = television.get(); // Haal het uit de optional en stop het in television1 // Return de television en een 200 status return ResponseEntity.ok().body(television1); } } // We geven hier een television mee in de parameter. Zorg dat je JSON object exact overeenkomt met het Television object. @PostMapping("/televisions") public ResponseEntity<Television> addTelevision(@RequestBody Television television) { // Er vanuit gaande dat televisies direct in de applicatie worden toegevoegd als ze gekocht zijn. television.setOriginalStock(LocalDate.now()); // Wat doet dit in de database? // Sla de nieuwe tv in de database op met de save-methode van de repository Television returnTelevision = televisionRepository.save(television); // Hier moet eigen nog een URI uri response. // Return de gemaakte television en een 201 status return ResponseEntity.created(null).body(returnTelevision); } @DeleteMapping("/televisions/{id}") public ResponseEntity<Object> deleteTelevision(@PathVariable("id") Long id) { // Verwijder de television met het opgegeven id uit de database. televisionRepository.deleteById(id); // Return een 204 status return ResponseEntity.noContent().build(); } // Update a television @PutMapping("/televisions/{id}") public ResponseEntity<Television> updateTelevision(@PathVariable Long id, @RequestBody Television newTelevision) { // Haal de aan te passen tv uit de database met het gegeven id Optional<Television> television = televisionRepository.findById(id); // Als eerste checken we of de aan te passen tv wel in de database bestaat. if (television.isEmpty()) { throw new RecordNotFoundException("No television found with id: " + id); } else { // Verander alle waardes van de television uit de database naar de waardes van de television uit de parameters. // Behalve de id. Als je de id veranderd, dan wordt er een nieuw object gemaakt in de database. Television television1 = television.get(); television1.setAvailableSize(newTelevision.getAvailableSize()); television1.setAmbiLight(newTelevision.getAmbiLight()); television1.setBluetooth(newTelevision.getBluetooth()); television1.setBrand(newTelevision.getBrand()); television1.setHdr(newTelevision.getHdr()); television1.setName(newTelevision.getName()); television1.setOriginalStock(newTelevision.getOriginalStock()); television1.setPrice(newTelevision.getPrice()); television1.setRefreshRate(newTelevision.getRefreshRate()); television1.setScreenQuality(newTelevision.getScreenQuality()); television1.setScreenType(newTelevision.getScreenType()); television1.setSmartTv(newTelevision.getSmartTv()); television1.setSold(newTelevision.getSold()); television1.setType(newTelevision.getType()); television1.setVoiceControl(newTelevision.getVoiceControl()); television1.setWifi(newTelevision.getWifi()); // Sla de gewijzigde waarden op in de database onder dezelfde id. Dit moet je niet vergeten. Television returnTelevision = televisionRepository.save(television1); // Return de nieuwe versie van deze tv en een 200 code return ResponseEntity.ok().body(returnTelevision); } } // Televisie gedeeltelijk bijwerken @PatchMapping("/televisions/{id}") public ResponseEntity<Television> updatePartialTelevision(@PathVariable Long id, @RequestBody Television newTelevision) { Optional<Television> television = televisionRepository.findById(id); if (television.isEmpty()) { throw new RecordNotFoundException("No television found with id: " + id); } else { // Het verschil tussen een patch en een put methode is dat een put een compleet object update, // waar een patch een gedeeltelijk object kan updaten. // Zet alles in een null-check, om te voorkomen dat je perongelijk bestaande waardes overschrijft met null-waardes. // Intellij heeft een handige postfix voor null-checks. Dit doe je door bijvoorbeeld "newTelevision.getBrand().notnull" te typen en dan op tab te drukken. Television television1 = television.get(); if (newTelevision.getAmbiLight() != null) { television1.setAmbiLight(newTelevision.getAmbiLight()); } if (newTelevision.getAvailableSize() != null) { television1.setAvailableSize(newTelevision.getAvailableSize()); } if (newTelevision.getBluetooth()) { television1.setBluetooth(newTelevision.getBluetooth()); } if (newTelevision.getBrand() != null) { television1.setBrand(newTelevision.getBrand()); } if (newTelevision.getHdr() != null) { television1.setHdr(newTelevision.getHdr()); } if (newTelevision.getName() != null) { television1.setName(newTelevision.getName()); } if (newTelevision.getOriginalStock() != null) { television1.setOriginalStock(newTelevision.getOriginalStock()); } if (newTelevision.getPrice() != null) { television1.setPrice(newTelevision.getPrice()); } if (newTelevision.getRefreshRate() != null) { television1.setRefreshRate(newTelevision.getRefreshRate()); } if (newTelevision.getScreenQuality() != null) { television1.setScreenQuality(newTelevision.getScreenQuality()); } if (newTelevision.getScreenType() != null) { television1.setScreenType(newTelevision.getScreenType()); } if (newTelevision.getSmartTv() != null) { television1.setSmartTv(newTelevision.getSmartTv()); } if (newTelevision.getSold() != null) { television1.setSold(newTelevision.getSold()); } if (newTelevision.getType() != null) { television1.setType(newTelevision.getType()); } if (newTelevision.getVoiceControl() != null) { television1.setVoiceControl(newTelevision.getVoiceControl()); } if (newTelevision.getWifi() != null) { television1.setWifi(newTelevision.getWifi()); } Television returnTelevision = televisionRepository.save(television1); return ResponseEntity.ok().body(returnTelevision); } } }
True
False
1,376
1,089
165279_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 ui.controller; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import ui.VIVESbike; /** * FXML Controller class * * @author Martijn */ public class StartschermController implements Initializable { // referentie naar VIVESbike (main) private VIVESbike parent; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } /** * Referentie naar parent (start) instellen * * @param parent referentie naar de runnable class die alle oproepen naar de * schermen bestuurt */ public void setParent(VIVESbike p) { parent = p; } }
MaximilianCoutuer/vivesbike
src/ui/controller/StartschermController.java
280
/** * Referentie naar parent (start) instellen * * @param parent referentie naar de runnable class die alle oproepen naar de * schermen bestuurt */
block_comment
nl
/* * 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 ui.controller; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import ui.VIVESbike; /** * FXML Controller class * * @author Martijn */ public class StartschermController implements Initializable { // referentie naar VIVESbike (main) private VIVESbike parent; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } /** * Referentie naar parent<SUF>*/ public void setParent(VIVESbike p) { parent = p; } }
True
False
1,379
929
53002_9
/* * 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 bigdata; import java.awt.event.ActionEvent; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.swing.AbstractAction; import javax.swing.JFileChooser; import javax.swing.SwingWorker; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileSystemView; /** * * @author HP */ public class Controller { private ParserGUI pGui; public Controller(ParserGUI pGui) { this.pGui = pGui; this.pGui.setVisible(true); this.pGui.setActions(new BrowseAction(), new OutputAction(), new ParseAction(), new CloseAction()); } //button action for selecting file to parse class BrowseAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { JFileChooser input = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); input.setDialogTitle("Select a list file"); input.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter(".list files", "list"); input.addChoosableFileFilter(filter); int result = input.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = input.getSelectedFile(); pGui.updateInputPath(selectedFile.getPath()); } } } //button action for selecting directory to export .csv file into class OutputAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e){ JFileChooser output = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); output.setDialogTitle("Choose a directory to save your file in:"); output.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // output.setAcceptAllFileFilterUsed(false); int result = output.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { pGui.updateOutputPath(output.getCurrentDirectory().getPath() + "/"); } } } //button action to begin parsing file class ParseAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { pGui.addLog("---------------------------------------"); File f = new File(pGui.getInputPath()); FileReader fr; BufferedReader br; int linesToSkip = 0; String pattern; String[] header; String substitution; String result; String option = "test"; String outpath; int[] substitutions; try { fr = new FileReader(f); br = new BufferedReader(fr); //Path path = Paths.get(pGui.getInputPath()); //Stream<String> stream = Files.lines(path); } catch (IOException err) { pGui.addLog(err.toString()); return; } switch (f.getName()) { case "countries.list": { pattern = "\"?(.*?)\"?\\s\\((.{4,7}|\\?\\?\\?\\?|\\d{4}\\/.*)\\)\\s*(\\((.*)\\))?\\s*(\\{([^\\{}]*)\\})?\\s(\\{(SUSPENDED)\\})?\\s*(.*)"; substitution = "$1; $2; $6; $9"; header = new String[]{}; linesToSkip = 14; substitutions = null; result = "countries.csv"; break; } case "movies.list": { pattern = "\\s?([^\"].*[^\"])\\s(?:\\((\\d{4}|\\?{4})(?:\\/([IVXCM]+))?\\))\\s(\\((.{1,2})\\))?\\s*(\\{\\{(.*?)\\}\\})?\\s*(\\d{4}|\\?{4})"; substitution = "$1; $2; $8"; header = new String[]{}; linesToSkip = 14; substitutions = null; result = "movies.csv"; break; } case "series.list": { pattern = "\\\"(.*?)\\\"\\s\\((.*?)\\)\\s(\\{([^\\{].*?[^\\}])\\})?\\s*(\\{(.*?)\\})?\\s*(.{4,9})"; substitution = "$1; $2; $4; $7"; header = new String[]{}; linesToSkip = 15; substitutions = null; result = "series.csv"; break; } case "actors.list": { pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?"; substitution = "$1; $3; $6; $9; $12; $15; $18"; header = new String[]{}; linesToSkip = 239; option = "tabbed"; substitutions = new int[]{3, 6, 9, 12, 15, 18}; result = "actors.csv"; break; } case "actresses.list": { pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?"; substitution = "$1; $3; $6; $9; $12; $15; $18"; header = new String[]{}; linesToSkip = 241; option = "tabbed"; substitutions = new int[]{3, 6, 9, 12, 15, 18}; result = "actresses.csv"; break; } case "directors.list": { pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?"; substitution = "$1; $3; $6; $9; $11; $15"; header = new String[]{}; linesToSkip = 235; option = "tabbed"; substitutions = new int[]{3, 6, 9, 11, 15}; result = "directors.csv"; break; } case "producers.list": { pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?"; substitution = "$1; $3; $6; $9; $11; $15"; header = new String[]{}; linesToSkip = 219; option = "tabbed"; substitutions = new int[]{3, 6, 9, 11, 15}; result = "producers.csv"; break; } case "ratings.list": { pattern = "(.{20}) ([0-9]\\.[0-9]) (.+) (?:\\((\\d{4}|\\?{4})(?:\\/([IVXCM]+))?\\)) ?(\\{(.+)\\}?)?"; substitution = "$2; $3; $4; $7"; header = new String[]{}; linesToSkip = 28; substitutions = null; result = "ratings.csv"; break; } case "running-times.list": { pattern = "(?:\")(.*)(?:\") \\((\\d{4}|[?]{4})\\W(?:.*\\{|.*\\))?(.*\\))?(?:.*\\t|.*:)((\\d)?(\\d))(?:.*)"; substitution = "$1, $2, $3, $4"; header = new String[]{}; linesToSkip = 14; substitutions = null; result = "running-times.csv"; break; } default: { pattern = ""; substitution = ""; header = new String[]{}; pGui.addLog("List not found."); result = null; option = null; substitutions = null; linesToSkip = 0; break; } } outpath = pGui.getOutputPath() + result; new Parser(pattern, substitution, header, outpath, br, fr, linesToSkip, option, substitutions).execute(); } } //de hele parser klasse staat hieronder en is ge-extend naar swingworker zodat de parse-operatie in een achtergroundthread gebeurt zodat //de UI niet tijdens de operatie vast loopt. Er wordt in de vorige switch-case gekeken wat voor lijst is geselecteerd en daarvan wordt de filepath (outpath) //doorgegeven aan de Parser. class Parser extends SwingWorker<Void, Void> { private String pattern; private String substitution; private String[] header; private String outpath; private BufferedReader br; private FileReader fr; private String nextLine; private String result; private Matcher matcher; private Pattern r; private int count; private String current; private int linesToSkip; private String option; private int[] subs; public Parser(String pattern, String substitution, String[] header, String outpath, BufferedReader br, FileReader fr, int linesToSkip, String option, int[] subs) { this.pattern = pattern; this.substitution = substitution; this.header = header; this.outpath = outpath; this.br = br; this.fr = fr; this.linesToSkip = linesToSkip; this.option = option; count = 0; current = ""; this.subs = subs; } public int countLines(String filename) throws IOException { InputStream is = new BufferedInputStream(new FileInputStream(filename)); try { byte[] c = new byte[1024]; int cnt = 0; int readChars = 0; boolean empty = true; while ((readChars = is.read(c)) != -1) { empty = false; for (int i = 0; i < readChars; ++i) { if (c[i] == '\n') { ++cnt; } } } return (cnt == 0 && !empty) ? 1 : cnt; } finally { is.close(); } } @Override protected Void doInBackground() throws IOException{ int lineNumber = 0; int lts = this.linesToSkip; pGui.setProgressBar(countLines(pGui.getInputPath()) - lts); //set progress bar length to amount of lines in file minus lts switch(option){ case "tabbed": { String prevName = ""; try (BufferedWriter writer = new BufferedWriter(new FileWriter(outpath))) { r = Pattern.compile(pattern); while ((nextLine = br.readLine()) != null) { if (++lineNumber <= lts) continue; matcher = r.matcher(nextLine); List<String> rows = new ArrayList<>(); if (matcher.find()) { if (Objects.equals("", matcher.group(1))) { rows.add(prevName); for (int i : subs) { rows.add("\t" + matcher.group(i)); } } else { rows.add(matcher.group(1)); for (int i : subs) { rows.add("\t" + matcher.group(i)); } prevName = matcher.group(1); } } //if (!nextLine.startsWith("\"")) { // System.out.println(nextLine); StringBuilder lineString = new StringBuilder(); for (String row : rows) { if (row != null) { row = row.trim(); } // System.out.println(lineString); assert row != null; lineString.append(row.trim()).append(";\t"); } result = matcher.replaceAll(substitution); System.out.println(result); if (lineString.length() != 0) { count++; //update current line count writer.write(lineString.toString()); pGui.addLog(result); //prints converted data to log pGui.updateProgressBar(count); //update progress bar writer.newLine(); } //} else continue; } writer.close(); } catch (IOException e) { pGui.addLog(e.toString()); } break; } default: { try (BufferedWriter writer = new BufferedWriter(new FileWriter(outpath))) { r = Pattern.compile(pattern); while ((nextLine = br.readLine()) != null) { if (++lineNumber <= lts) continue; //if (!nextLine.startsWith("\"")) { // System.out.println(nextLine); matcher = r.matcher(nextLine); result = matcher.replaceAll(substitution); System.out.println(result); if (result.length() != 0) { count++; writer.write(result); writer.newLine(); pGui.addLog(result); pGui.updateProgressBar(count); } //} else continue; } writer.close(); } catch (IOException e) { pGui.addLog(e.toString()); } break; } } return null; } @Override protected void done() { pGui.addLog("Conversion finished!"); pGui.addLog("--------------------------------------"); } } //button action to close the program class CloseAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { pGui.dispose(); } } }
Koenzk/bigmovie
BigDataGUI/src/bigdata/Controller.java
4,354
//doorgegeven aan de Parser.
line_comment
nl
/* * 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 bigdata; import java.awt.event.ActionEvent; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.swing.AbstractAction; import javax.swing.JFileChooser; import javax.swing.SwingWorker; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileSystemView; /** * * @author HP */ public class Controller { private ParserGUI pGui; public Controller(ParserGUI pGui) { this.pGui = pGui; this.pGui.setVisible(true); this.pGui.setActions(new BrowseAction(), new OutputAction(), new ParseAction(), new CloseAction()); } //button action for selecting file to parse class BrowseAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { JFileChooser input = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); input.setDialogTitle("Select a list file"); input.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter(".list files", "list"); input.addChoosableFileFilter(filter); int result = input.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = input.getSelectedFile(); pGui.updateInputPath(selectedFile.getPath()); } } } //button action for selecting directory to export .csv file into class OutputAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e){ JFileChooser output = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); output.setDialogTitle("Choose a directory to save your file in:"); output.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // output.setAcceptAllFileFilterUsed(false); int result = output.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { pGui.updateOutputPath(output.getCurrentDirectory().getPath() + "/"); } } } //button action to begin parsing file class ParseAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { pGui.addLog("---------------------------------------"); File f = new File(pGui.getInputPath()); FileReader fr; BufferedReader br; int linesToSkip = 0; String pattern; String[] header; String substitution; String result; String option = "test"; String outpath; int[] substitutions; try { fr = new FileReader(f); br = new BufferedReader(fr); //Path path = Paths.get(pGui.getInputPath()); //Stream<String> stream = Files.lines(path); } catch (IOException err) { pGui.addLog(err.toString()); return; } switch (f.getName()) { case "countries.list": { pattern = "\"?(.*?)\"?\\s\\((.{4,7}|\\?\\?\\?\\?|\\d{4}\\/.*)\\)\\s*(\\((.*)\\))?\\s*(\\{([^\\{}]*)\\})?\\s(\\{(SUSPENDED)\\})?\\s*(.*)"; substitution = "$1; $2; $6; $9"; header = new String[]{}; linesToSkip = 14; substitutions = null; result = "countries.csv"; break; } case "movies.list": { pattern = "\\s?([^\"].*[^\"])\\s(?:\\((\\d{4}|\\?{4})(?:\\/([IVXCM]+))?\\))\\s(\\((.{1,2})\\))?\\s*(\\{\\{(.*?)\\}\\})?\\s*(\\d{4}|\\?{4})"; substitution = "$1; $2; $8"; header = new String[]{}; linesToSkip = 14; substitutions = null; result = "movies.csv"; break; } case "series.list": { pattern = "\\\"(.*?)\\\"\\s\\((.*?)\\)\\s(\\{([^\\{].*?[^\\}])\\})?\\s*(\\{(.*?)\\})?\\s*(.{4,9})"; substitution = "$1; $2; $4; $7"; header = new String[]{}; linesToSkip = 15; substitutions = null; result = "series.csv"; break; } case "actors.list": { pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?"; substitution = "$1; $3; $6; $9; $12; $15; $18"; header = new String[]{}; linesToSkip = 239; option = "tabbed"; substitutions = new int[]{3, 6, 9, 12, 15, 18}; result = "actors.csv"; break; } case "actresses.list": { pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?"; substitution = "$1; $3; $6; $9; $12; $15; $18"; header = new String[]{}; linesToSkip = 241; option = "tabbed"; substitutions = new int[]{3, 6, 9, 12, 15, 18}; result = "actresses.csv"; break; } case "directors.list": { pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?"; substitution = "$1; $3; $6; $9; $11; $15"; header = new String[]{}; linesToSkip = 235; option = "tabbed"; substitutions = new int[]{3, 6, 9, 11, 15}; result = "directors.csv"; break; } case "producers.list": { pattern = "(.*?)(\\t{1,3})(.+?(?=\\())(\\s+)?(\\((.+?(?=\\)))\\))(\\s)(\\{(.+)\\})?( +)?(\\((\\w{1})\\))?( +)?(\\((.*)\\))?( +)?(\\[(.+)\\])?( +)?(\\<(.*)\\>)?"; substitution = "$1; $3; $6; $9; $11; $15"; header = new String[]{}; linesToSkip = 219; option = "tabbed"; substitutions = new int[]{3, 6, 9, 11, 15}; result = "producers.csv"; break; } case "ratings.list": { pattern = "(.{20}) ([0-9]\\.[0-9]) (.+) (?:\\((\\d{4}|\\?{4})(?:\\/([IVXCM]+))?\\)) ?(\\{(.+)\\}?)?"; substitution = "$2; $3; $4; $7"; header = new String[]{}; linesToSkip = 28; substitutions = null; result = "ratings.csv"; break; } case "running-times.list": { pattern = "(?:\")(.*)(?:\") \\((\\d{4}|[?]{4})\\W(?:.*\\{|.*\\))?(.*\\))?(?:.*\\t|.*:)((\\d)?(\\d))(?:.*)"; substitution = "$1, $2, $3, $4"; header = new String[]{}; linesToSkip = 14; substitutions = null; result = "running-times.csv"; break; } default: { pattern = ""; substitution = ""; header = new String[]{}; pGui.addLog("List not found."); result = null; option = null; substitutions = null; linesToSkip = 0; break; } } outpath = pGui.getOutputPath() + result; new Parser(pattern, substitution, header, outpath, br, fr, linesToSkip, option, substitutions).execute(); } } //de hele parser klasse staat hieronder en is ge-extend naar swingworker zodat de parse-operatie in een achtergroundthread gebeurt zodat //de UI niet tijdens de operatie vast loopt. Er wordt in de vorige switch-case gekeken wat voor lijst is geselecteerd en daarvan wordt de filepath (outpath) //doorgegeven aan<SUF> class Parser extends SwingWorker<Void, Void> { private String pattern; private String substitution; private String[] header; private String outpath; private BufferedReader br; private FileReader fr; private String nextLine; private String result; private Matcher matcher; private Pattern r; private int count; private String current; private int linesToSkip; private String option; private int[] subs; public Parser(String pattern, String substitution, String[] header, String outpath, BufferedReader br, FileReader fr, int linesToSkip, String option, int[] subs) { this.pattern = pattern; this.substitution = substitution; this.header = header; this.outpath = outpath; this.br = br; this.fr = fr; this.linesToSkip = linesToSkip; this.option = option; count = 0; current = ""; this.subs = subs; } public int countLines(String filename) throws IOException { InputStream is = new BufferedInputStream(new FileInputStream(filename)); try { byte[] c = new byte[1024]; int cnt = 0; int readChars = 0; boolean empty = true; while ((readChars = is.read(c)) != -1) { empty = false; for (int i = 0; i < readChars; ++i) { if (c[i] == '\n') { ++cnt; } } } return (cnt == 0 && !empty) ? 1 : cnt; } finally { is.close(); } } @Override protected Void doInBackground() throws IOException{ int lineNumber = 0; int lts = this.linesToSkip; pGui.setProgressBar(countLines(pGui.getInputPath()) - lts); //set progress bar length to amount of lines in file minus lts switch(option){ case "tabbed": { String prevName = ""; try (BufferedWriter writer = new BufferedWriter(new FileWriter(outpath))) { r = Pattern.compile(pattern); while ((nextLine = br.readLine()) != null) { if (++lineNumber <= lts) continue; matcher = r.matcher(nextLine); List<String> rows = new ArrayList<>(); if (matcher.find()) { if (Objects.equals("", matcher.group(1))) { rows.add(prevName); for (int i : subs) { rows.add("\t" + matcher.group(i)); } } else { rows.add(matcher.group(1)); for (int i : subs) { rows.add("\t" + matcher.group(i)); } prevName = matcher.group(1); } } //if (!nextLine.startsWith("\"")) { // System.out.println(nextLine); StringBuilder lineString = new StringBuilder(); for (String row : rows) { if (row != null) { row = row.trim(); } // System.out.println(lineString); assert row != null; lineString.append(row.trim()).append(";\t"); } result = matcher.replaceAll(substitution); System.out.println(result); if (lineString.length() != 0) { count++; //update current line count writer.write(lineString.toString()); pGui.addLog(result); //prints converted data to log pGui.updateProgressBar(count); //update progress bar writer.newLine(); } //} else continue; } writer.close(); } catch (IOException e) { pGui.addLog(e.toString()); } break; } default: { try (BufferedWriter writer = new BufferedWriter(new FileWriter(outpath))) { r = Pattern.compile(pattern); while ((nextLine = br.readLine()) != null) { if (++lineNumber <= lts) continue; //if (!nextLine.startsWith("\"")) { // System.out.println(nextLine); matcher = r.matcher(nextLine); result = matcher.replaceAll(substitution); System.out.println(result); if (result.length() != 0) { count++; writer.write(result); writer.newLine(); pGui.addLog(result); pGui.updateProgressBar(count); } //} else continue; } writer.close(); } catch (IOException e) { pGui.addLog(e.toString()); } break; } } return null; } @Override protected void done() { pGui.addLog("Conversion finished!"); pGui.addLog("--------------------------------------"); } } //button action to close the program class CloseAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { pGui.dispose(); } } }
True
False
1,380
4,705
177532_14
package nl.wildlands.wildlandseducation.Activities; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; import com.github.nkzawa.emitter.Emitter; import com.github.nkzawa.socketio.client.Socket; import org.json.JSONException; import org.json.JSONObject; import nl.wildlands.wildlandseducation.GlobalSettings.DefaultApplication; import nl.wildlands.wildlandseducation.R; /** * Activity waarbij de docent de gegevens van de quiz kan invoeren * en deze vervolgens d.m.v. socekts wordt aangemaakt */ public class GenerateQuiz extends Activity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener { ImageButton backBtn; // ImageButton om terug te gaan Button generateQuiz; // Button om quiz te genereren Socket mSocket; // Socket voor de quizverbinding private SeekBar bar; // Seekbar om tijd dynamisch in te stellen private TextView textProgress, genereerQuiz,tijd; // TextView voor weergave huidige tijdsinput /** * Actie die voltrokken wordt, als de socket een bepaald bericht krijgt */ private Emitter.Listener onNewMessage = new Emitter.Listener() { @Override public void call(final Object... args) { GenerateQuiz.this.runOnUiThread(new Runnable() { @Override public void run() { JSONObject data = (JSONObject) args[0]; // Zet de data om in een JSONObject String success; // Succes van aanmaken int quizID; // ID van de gegenereerde quiz try { success = data.getString("success"); // Success message quizID = data.getInt("quizid"); // Quizid } catch (JSONException e) { return; } startNewActivity(success, quizID); // Roep startNewActivity aan met de waardes } }); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Zet layout setContentView(R.layout.activity_generate_quiz); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // Fullscreen WindowManager.LayoutParams.FLAG_FULLSCREEN); generateQuiz = (Button)findViewById(R.id.generateQuiz); // Button voor genereren quiz generateQuiz.setOnClickListener(this); // Activeer knopactie backBtn = (ImageButton)findViewById(R.id.quitbutton); // ImageButton om terug te gaan backBtn.setOnClickListener(this); // Activeer knopactie bar =(SeekBar)findViewById(R.id.seekBar1); // Seekbar om tijd in te stellen bar.setOnSeekBarChangeListener(this); // Actie bij het veranderen van de seekbar textProgress = (TextView)findViewById(R.id.textView3); // Tekst voor de actuele tijdsinstelling genereerQuiz = (TextView)findViewById(R.id.textView1); tijd = (TextView)findViewById(R.id.textView2); Typeface tf = DefaultApplication.tf2; // Verander de lettertypes genereerQuiz.setTypeface(tf); tijd.setTypeface(tf); Typeface tf2 = DefaultApplication.tf; // Verander de lettertypes generateQuiz.setTypeface(tf2); textProgress.setTypeface(tf2); mSocket = ((DefaultApplication)this.getApplicationContext()).getSocket(); // Vraag de centrale socket op mSocket.connect(); // Maak verbinding met de server } @Override public void onClick(View v) { switch(v.getId()) { case R.id.generateQuiz: // Genereer quiz ingedrukt mSocket.emit("createQuiz",""); // Verzend het verzoek om een quiz te maken startListening(); // Wacht op bevestiging break; case R.id.quitbutton: Intent i = new Intent(this, ChooseQuizGroup.class); // Backbutton gaat naar choose quiz group activity startActivity(i); this.finish(); // Beeindig deze activity break; } } public void startListening() { mSocket.on("quizCreated", onNewMessage); // Start de actie als de socket bevestiging krijgt } /** * Zet het quizid en de lengte van de quiz in de global variables * en start een nieuwe activity * @param success * @param quizID */ public void startNewActivity(String success, int quizID) { ((DefaultApplication)this.getApplication()).setSocketcode(quizID); // Zet de socketcode ((DefaultApplication)this.getApplication()).setDuration(bar.getProgress()); // Zet de quizduur in minuten Intent codeScreen = new Intent(this, QuizStart.class); // Intent met het wachtscherm startActivity(codeScreen); // Start het wachtscherm this.finish(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { textProgress.setText(progress+ " MIN"); // Bij verandering van de balk, zet de actuele tijdinstelling } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }
wildlands/wildlands-android
app/src/main/java/nl/wildlands/wildlandseducation/Activities/GenerateQuiz.java
1,678
// Actie bij het veranderen van de seekbar
line_comment
nl
package nl.wildlands.wildlandseducation.Activities; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; import com.github.nkzawa.emitter.Emitter; import com.github.nkzawa.socketio.client.Socket; import org.json.JSONException; import org.json.JSONObject; import nl.wildlands.wildlandseducation.GlobalSettings.DefaultApplication; import nl.wildlands.wildlandseducation.R; /** * Activity waarbij de docent de gegevens van de quiz kan invoeren * en deze vervolgens d.m.v. socekts wordt aangemaakt */ public class GenerateQuiz extends Activity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener { ImageButton backBtn; // ImageButton om terug te gaan Button generateQuiz; // Button om quiz te genereren Socket mSocket; // Socket voor de quizverbinding private SeekBar bar; // Seekbar om tijd dynamisch in te stellen private TextView textProgress, genereerQuiz,tijd; // TextView voor weergave huidige tijdsinput /** * Actie die voltrokken wordt, als de socket een bepaald bericht krijgt */ private Emitter.Listener onNewMessage = new Emitter.Listener() { @Override public void call(final Object... args) { GenerateQuiz.this.runOnUiThread(new Runnable() { @Override public void run() { JSONObject data = (JSONObject) args[0]; // Zet de data om in een JSONObject String success; // Succes van aanmaken int quizID; // ID van de gegenereerde quiz try { success = data.getString("success"); // Success message quizID = data.getInt("quizid"); // Quizid } catch (JSONException e) { return; } startNewActivity(success, quizID); // Roep startNewActivity aan met de waardes } }); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Zet layout setContentView(R.layout.activity_generate_quiz); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // Fullscreen WindowManager.LayoutParams.FLAG_FULLSCREEN); generateQuiz = (Button)findViewById(R.id.generateQuiz); // Button voor genereren quiz generateQuiz.setOnClickListener(this); // Activeer knopactie backBtn = (ImageButton)findViewById(R.id.quitbutton); // ImageButton om terug te gaan backBtn.setOnClickListener(this); // Activeer knopactie bar =(SeekBar)findViewById(R.id.seekBar1); // Seekbar om tijd in te stellen bar.setOnSeekBarChangeListener(this); // Actie bij<SUF> textProgress = (TextView)findViewById(R.id.textView3); // Tekst voor de actuele tijdsinstelling genereerQuiz = (TextView)findViewById(R.id.textView1); tijd = (TextView)findViewById(R.id.textView2); Typeface tf = DefaultApplication.tf2; // Verander de lettertypes genereerQuiz.setTypeface(tf); tijd.setTypeface(tf); Typeface tf2 = DefaultApplication.tf; // Verander de lettertypes generateQuiz.setTypeface(tf2); textProgress.setTypeface(tf2); mSocket = ((DefaultApplication)this.getApplicationContext()).getSocket(); // Vraag de centrale socket op mSocket.connect(); // Maak verbinding met de server } @Override public void onClick(View v) { switch(v.getId()) { case R.id.generateQuiz: // Genereer quiz ingedrukt mSocket.emit("createQuiz",""); // Verzend het verzoek om een quiz te maken startListening(); // Wacht op bevestiging break; case R.id.quitbutton: Intent i = new Intent(this, ChooseQuizGroup.class); // Backbutton gaat naar choose quiz group activity startActivity(i); this.finish(); // Beeindig deze activity break; } } public void startListening() { mSocket.on("quizCreated", onNewMessage); // Start de actie als de socket bevestiging krijgt } /** * Zet het quizid en de lengte van de quiz in de global variables * en start een nieuwe activity * @param success * @param quizID */ public void startNewActivity(String success, int quizID) { ((DefaultApplication)this.getApplication()).setSocketcode(quizID); // Zet de socketcode ((DefaultApplication)this.getApplication()).setDuration(bar.getProgress()); // Zet de quizduur in minuten Intent codeScreen = new Intent(this, QuizStart.class); // Intent met het wachtscherm startActivity(codeScreen); // Start het wachtscherm this.finish(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { textProgress.setText(progress+ " MIN"); // Bij verandering van de balk, zet de actuele tijdinstelling } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }
True
False
1,387
2,293
17465_3
package gretig.datastructuur; import gretig.datastructuur.Graaf; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; /** * Created by brent on 10/8/16. */ public class GraafDecoder { private InputStream is; private boolean done; private int bytesize; public GraafDecoder(InputStream is) throws IOException { this.is = is; done = false; } /** Decodeer de grafen één voor één. * @return gf lijst van alle grafen * @throws IOException fout bij het lezen */ public ArrayList<Graaf> decodeGrafen() throws IOException { ArrayList<Graaf> gf = new ArrayList<>(); while(!done){ this.bytesize = is.read(); int toppen = readNumber(); int bogen = readNumber(); if(bytesize==-1||toppen==-1||bogen==-1) break; gf.add(decodeGraaf(toppen, bogen)); } return gf; } /** * Lees het volgende getal in volgens de bytesize. * @return answer: ByteDecoded number * @throws IOException fout bij lezen */ public int readNumber() throws IOException { int answer = 0; for (int i=0; i<bytesize;i++){ int b=is.read(); if(b==-1){ return -1; } answer+=b<<(8*i); } return answer; } /** Verwerk 1 graaf. * @param toppen: aantal toppen * @param bogen: aantal bogen * @return g: de volledige graaf * @throws IOException */ public Graaf decodeGraaf(int toppen, int bogen) throws IOException { int b; int teller=0; Graaf g = new Graaf(toppen, bogen); g.init_next(); while((b=readNumber())!=-1){ if(b==0){ teller++; if(teller>=toppen) break; g.init_next(); } else { g.add_boog(b); } } if (b==-1) done=true; return g; } }
brent-vw/Greedy-Cycles
src/gretig/datastructuur/GraafDecoder.java
640
/** Verwerk 1 graaf. * @param toppen: aantal toppen * @param bogen: aantal bogen * @return g: de volledige graaf * @throws IOException */
block_comment
nl
package gretig.datastructuur; import gretig.datastructuur.Graaf; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; /** * Created by brent on 10/8/16. */ public class GraafDecoder { private InputStream is; private boolean done; private int bytesize; public GraafDecoder(InputStream is) throws IOException { this.is = is; done = false; } /** Decodeer de grafen één voor één. * @return gf lijst van alle grafen * @throws IOException fout bij het lezen */ public ArrayList<Graaf> decodeGrafen() throws IOException { ArrayList<Graaf> gf = new ArrayList<>(); while(!done){ this.bytesize = is.read(); int toppen = readNumber(); int bogen = readNumber(); if(bytesize==-1||toppen==-1||bogen==-1) break; gf.add(decodeGraaf(toppen, bogen)); } return gf; } /** * Lees het volgende getal in volgens de bytesize. * @return answer: ByteDecoded number * @throws IOException fout bij lezen */ public int readNumber() throws IOException { int answer = 0; for (int i=0; i<bytesize;i++){ int b=is.read(); if(b==-1){ return -1; } answer+=b<<(8*i); } return answer; } /** Verwerk 1 graaf.<SUF>*/ public Graaf decodeGraaf(int toppen, int bogen) throws IOException { int b; int teller=0; Graaf g = new Graaf(toppen, bogen); g.init_next(); while((b=readNumber())!=-1){ if(b==0){ teller++; if(teller>=toppen) break; g.init_next(); } else { g.add_boog(b); } } if (b==-1) done=true; return g; } }
True
False
1,393
705
10414_2
import lejos.nxt.Motor; import lejos.nxt.NXTRegulatedMotor; public class Dispenser extends Thread { public void geefGeld(int bedrag){ int a10 = 0; int a20 = 0; int a50 = 0; NXTRegulatedMotor m10 = Motor.A; NXTRegulatedMotor m20 = Motor.B; NXTRegulatedMotor m50 = Motor.C; while(bedrag > 0){ if(bedrag >= 50){ a50 += 1; bedrag -= 50; } else if (bedrag >= 20&& bedrag < 50){ a20 += 1; bedrag -= 20; } else{ a10 += 1; bedrag -= 10; } } dispense(m50,a50); dispense(m20,a20); dispense(m10,a10); } public static void dispense(NXTRegulatedMotor m, int aantal){ int tijd = 1100; m.backward(); // geld gaat voor uit try { sleep(tijd*aantal); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } m.stop(); m.forward(); //geld gaat terug in automaat } }
Horofic/ATM
client/Dispenser.java
403
//geld gaat terug in automaat
line_comment
nl
import lejos.nxt.Motor; import lejos.nxt.NXTRegulatedMotor; public class Dispenser extends Thread { public void geefGeld(int bedrag){ int a10 = 0; int a20 = 0; int a50 = 0; NXTRegulatedMotor m10 = Motor.A; NXTRegulatedMotor m20 = Motor.B; NXTRegulatedMotor m50 = Motor.C; while(bedrag > 0){ if(bedrag >= 50){ a50 += 1; bedrag -= 50; } else if (bedrag >= 20&& bedrag < 50){ a20 += 1; bedrag -= 20; } else{ a10 += 1; bedrag -= 10; } } dispense(m50,a50); dispense(m20,a20); dispense(m10,a10); } public static void dispense(NXTRegulatedMotor m, int aantal){ int tijd = 1100; m.backward(); // geld gaat voor uit try { sleep(tijd*aantal); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } m.stop(); m.forward(); //geld gaat<SUF> } }
True
False
1,396
4,391
96573_0
package org.janssen.scoreboard; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.Toast; import org.janssen.scoreboard.task.NewGameTask; import org.janssen.scoreboard.task.OnTaskListener; import static org.janssen.scoreboard.Constants.AUTH_TOKEN; import static org.janssen.scoreboard.Constants.COURT; import static org.janssen.scoreboard.Constants.GAME; import static org.janssen.scoreboard.Constants.MIRRORED; /** * Info voor nieuwe wedstrijd. * * Created by stephan on 16/06/13. */ public class NewGameActivity extends ImmersiveStickyActivity implements OnTaskListener { private static final int COURT_B = 1; private static final int SENIOREN = 0; private String authToken; /** * The tag used to log to adb console. */ private static final String TAG = "NewGameActivity"; private ProgressBar progressBar; private EditText teamAEdit; private EditText teamBEdit; private String teamA; private String teamB; private Integer selectedCourt; private int gameType; private int ageCategory; private boolean mirroring = false; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.activity_new_game); Bundle bundle = getIntent().getExtras(); if (bundle != null) { authToken = bundle.getString(AUTH_TOKEN); selectedCourt = (Integer) bundle.get(COURT); } else { Toast.makeText(getApplicationContext(), "No court selected, restart", Toast.LENGTH_LONG).show(); return; } teamAEdit = findViewById(R.id.teamA); teamAEdit.setText(R.string.oostkamp); teamBEdit = findViewById(R.id.teamB); teamBEdit.setText(R.string.bezoekers); progressBar = findViewById(R.id.progressBar3); // Game Type Spinner gameTypeSpinner = findViewById(R.id.gameType); ArrayAdapter<CharSequence> adapterGameTypeSpinner = ArrayAdapter.createFromResource(this, R.array.game_types, android.R.layout.simple_spinner_item); adapterGameTypeSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner gameTypeSpinner.setAdapter(adapterGameTypeSpinner); gameTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { gameType = pos; } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); // Age Category Spinner ageCategorySpinner = findViewById(R.id.ageCategory); ArrayAdapter<CharSequence> adapterAgeCategorySpinner = ArrayAdapter.createFromResource(this, R.array.age_category, android.R.layout.simple_spinner_item); adapterAgeCategorySpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner ageCategorySpinner.setAdapter(adapterAgeCategorySpinner); ageCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { ageCategory = pos; } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } public void createNewGame(View view) { Log.i(TAG, "create new game"); teamA = teamAEdit.getText().toString(); teamB = teamBEdit.getText().toString(); if (TextUtils.isEmpty(teamA) || TextUtils.isEmpty(teamB)) { Toast.makeText(getApplicationContext(), "Provide team names", Toast.LENGTH_LONG).show(); } else { if (ageCategory == SENIOREN && selectedCourt == COURT_B) { final AlertDialog dialog = new AlertDialog.Builder(this).create(); dialog.setTitle("Boodschap"); dialog.setMessage("Wens je 2 scoreborden te gebruiken?"); dialog.setCancelable(false); dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ja", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int buttonId) { startNewGame(true); } }); dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Nee", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int buttonId) { startNewGame(false); } }); dialog.setIcon(android.R.drawable.ic_dialog_alert); dialog.show(); } else { startNewGame(false); } } } private void startNewGame(final boolean isMirrored) { mirroring = isMirrored; // Show a progress dialog, and kick off a background task to perform the new game attempt showProgressBar(); new NewGameTask(this, teamA, teamB, gameType, ageCategory, selectedCourt, mirroring, authToken).execute(); } /** * Called when the new game creation process completes. */ @Override public void onTaskCompleted(final String result) { hideProgressBar(); if (result == null || result.contains("connect timed out")) { Toast.makeText(getApplicationContext(), "Geen connectie met scorebord", Toast.LENGTH_LONG).show(); } else { // Show count down Intent intent = new Intent(getApplicationContext(), CountDownActivity.class); intent.putExtra(MIRRORED, mirroring); intent.putExtra(GAME, result); intent.putExtra(AUTH_TOKEN, authToken); intent.putExtra(COURT, selectedCourt); startActivity(intent); } } @Override public void onTaskCancelled() { hideProgressBar(); } private void hideProgressBar() { progressBar.setVisibility(View.INVISIBLE); } private void showProgressBar() { progressBar.setVisibility(View.VISIBLE); } }
stephanj/AndroidRPIScoreboard
app/src/main/java/org/janssen/scoreboard/NewGameActivity.java
1,861
/** * Info voor nieuwe wedstrijd. * * Created by stephan on 16/06/13. */
block_comment
nl
package org.janssen.scoreboard; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.Toast; import org.janssen.scoreboard.task.NewGameTask; import org.janssen.scoreboard.task.OnTaskListener; import static org.janssen.scoreboard.Constants.AUTH_TOKEN; import static org.janssen.scoreboard.Constants.COURT; import static org.janssen.scoreboard.Constants.GAME; import static org.janssen.scoreboard.Constants.MIRRORED; /** * Info voor nieuwe<SUF>*/ public class NewGameActivity extends ImmersiveStickyActivity implements OnTaskListener { private static final int COURT_B = 1; private static final int SENIOREN = 0; private String authToken; /** * The tag used to log to adb console. */ private static final String TAG = "NewGameActivity"; private ProgressBar progressBar; private EditText teamAEdit; private EditText teamBEdit; private String teamA; private String teamB; private Integer selectedCourt; private int gameType; private int ageCategory; private boolean mirroring = false; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.activity_new_game); Bundle bundle = getIntent().getExtras(); if (bundle != null) { authToken = bundle.getString(AUTH_TOKEN); selectedCourt = (Integer) bundle.get(COURT); } else { Toast.makeText(getApplicationContext(), "No court selected, restart", Toast.LENGTH_LONG).show(); return; } teamAEdit = findViewById(R.id.teamA); teamAEdit.setText(R.string.oostkamp); teamBEdit = findViewById(R.id.teamB); teamBEdit.setText(R.string.bezoekers); progressBar = findViewById(R.id.progressBar3); // Game Type Spinner gameTypeSpinner = findViewById(R.id.gameType); ArrayAdapter<CharSequence> adapterGameTypeSpinner = ArrayAdapter.createFromResource(this, R.array.game_types, android.R.layout.simple_spinner_item); adapterGameTypeSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner gameTypeSpinner.setAdapter(adapterGameTypeSpinner); gameTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { gameType = pos; } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); // Age Category Spinner ageCategorySpinner = findViewById(R.id.ageCategory); ArrayAdapter<CharSequence> adapterAgeCategorySpinner = ArrayAdapter.createFromResource(this, R.array.age_category, android.R.layout.simple_spinner_item); adapterAgeCategorySpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner ageCategorySpinner.setAdapter(adapterAgeCategorySpinner); ageCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { ageCategory = pos; } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } public void createNewGame(View view) { Log.i(TAG, "create new game"); teamA = teamAEdit.getText().toString(); teamB = teamBEdit.getText().toString(); if (TextUtils.isEmpty(teamA) || TextUtils.isEmpty(teamB)) { Toast.makeText(getApplicationContext(), "Provide team names", Toast.LENGTH_LONG).show(); } else { if (ageCategory == SENIOREN && selectedCourt == COURT_B) { final AlertDialog dialog = new AlertDialog.Builder(this).create(); dialog.setTitle("Boodschap"); dialog.setMessage("Wens je 2 scoreborden te gebruiken?"); dialog.setCancelable(false); dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ja", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int buttonId) { startNewGame(true); } }); dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Nee", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int buttonId) { startNewGame(false); } }); dialog.setIcon(android.R.drawable.ic_dialog_alert); dialog.show(); } else { startNewGame(false); } } } private void startNewGame(final boolean isMirrored) { mirroring = isMirrored; // Show a progress dialog, and kick off a background task to perform the new game attempt showProgressBar(); new NewGameTask(this, teamA, teamB, gameType, ageCategory, selectedCourt, mirroring, authToken).execute(); } /** * Called when the new game creation process completes. */ @Override public void onTaskCompleted(final String result) { hideProgressBar(); if (result == null || result.contains("connect timed out")) { Toast.makeText(getApplicationContext(), "Geen connectie met scorebord", Toast.LENGTH_LONG).show(); } else { // Show count down Intent intent = new Intent(getApplicationContext(), CountDownActivity.class); intent.putExtra(MIRRORED, mirroring); intent.putExtra(GAME, result); intent.putExtra(AUTH_TOKEN, authToken); intent.putExtra(COURT, selectedCourt); startActivity(intent); } } @Override public void onTaskCancelled() { hideProgressBar(); } private void hideProgressBar() { progressBar.setVisibility(View.INVISIBLE); } private void showProgressBar() { progressBar.setVisibility(View.VISIBLE); } }
True
False
1,398
1,412
31192_9
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class DemoWorld extends World { // Declareren van CollisionEngine private CollisionEngine ce; // Declareren van TileEngine private TileEngine te; /** * Constructor for objects of class MyWorld. * */ public DemoWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},}; // initialiseren van de TileEngine klasse om de map aan de world toe te voegen te = new TileEngine(this, 60, 60); te.setTileFactory(new DemoTileFactory()); te.setMap(map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken DemoHero hero = new DemoHero(ce, te); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); addObject(new Enemy(150), 1170, 410); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); } @Override public void act() { ce.update(); } }
ROCMondriaanTIN/project-greenfoot-game-gijsdl
DemoWorld.java
3,196
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class DemoWorld extends World { // Declareren van CollisionEngine private CollisionEngine ce; // Declareren van TileEngine private TileEngine te; /** * Constructor for objects of class MyWorld. * */ public DemoWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},}; // initialiseren van de TileEngine klasse om de map aan de world toe te voegen te = new TileEngine(this, 60, 60); te.setTileFactory(new DemoTileFactory()); te.setMap(map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Initialiseren van<SUF> // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken DemoHero hero = new DemoHero(ce, te); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); addObject(new Enemy(150), 1170, 410); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); } @Override public void act() { ce.update(); } }
True
False
1,399
383
65066_6
package com.nhlstenden.amazonsimulatie.tests; import com.nhlstenden.amazonsimulatie.models.Model; import com.nhlstenden.amazonsimulatie.models.Object3D; import com.nhlstenden.amazonsimulatie.views.DefaultWebSocketView; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultWebSocketViewTests { /** * De code hieronder is een voorbeeld van een test in Java. Je schrijf per class die je wilt testen * een testclass zoals deze. Daarin zet je al je testfuncties. Vaak schrijf je per methode (of functie) * die je wilt testen een methode zoals deze hieronder. Kijk in de methode naar de genummerde comments. * Om de test het beste te begrijpen, begin je vanaf comment #1. */ @Test public void testUpdateSignal() throws Exception { /** * Comment #2 * Deze code hieronder hebben we nodig om de DefaultWebSocketView van comment 1 te kunnen maken. * Dat onderdeel van de software heeft een zogenaamde WebSocketSession nodig (een onderdeel waarmee * informatie via een websocket naar de webbrowser kan worden verstuurd). Een WebSocketSession is * normaal gesproken een onderdeel van het websocket systeem van onze server, en we kunnen niet * zomaar een WebSocketSession aanmaken wanneer er geen server draait, laat staan geen browser is. * Om dit toch te kunnen gebruiken, 'mocken' we de class WebSocketSession. Dit mocken betekent dat * we als het ware een 'nep' versie van het object maken. Deze 'mockSession'n (zie hieronder) is * een object dat wel alle methoden heeft van een echte WebSocketSession, maar de methoden doen * simpelweg niks. Hierdoor kun je code die een WebSocketSession nodig heeft, toch laten werken. * Ga nu naar comment #3. */ WebSocketSession mockSession = mock(WebSocketSession.class); /** * Comment #3 * De code hieronder is eigenlijk de invulling van een methode van WebSocketSession. Zoals je in * comment #2 las, is de het object mockSession een 'lege' WebSocketSession. De methoden bestaan dus * wel, maar doen in feite niks. Hieronder wordt een invulling gegeven. De when() functie is onderdeel * van het systeem om te mocken, en zegt hier wanneer de methode .isOpen() wordt aangeroepen op het object * mockSession, dan moet er iets gebeuren. Wat er moet gebeuren staat achter de when() methode, in de * vorm van .thenReturn(true). De hele regel code betekent nu dat wanneer .isOpen() wordt aangeroepen * op mockSession, dan moet deze methode altijd de waarde true teruggeven. Dit onderdeel is nodig omdat * de view in de update methode gebruikmaakt van de .isOpen() methode. Ga nu naar comment #4. */ when(mockSession.isOpen()).thenReturn(true); /** * Comment 4 * De code hieronder is misschien wat onduidelijk. Wat we hier doen, is het injecteren van testcode binnen * het mockSession object. Dit doen we omdat mockSession gebruikt wordt om het JSON pakketje te versturen. * Dit object krijgt dus sowieso de JSON tekst te zien. Dit gebeurd in de methode .sendMessage(). Hier wordt * een tekstbericht verstuurd naar de browser. In dit bericht zit de JSON code. Hier kunnen we dus een test * injecteren om de validiteit van de JSON de controleren. Dit is ook wat hieronder gebeurd. De methode * doAnwser hieronder zorgt ervoor dat de code die daarin wordt gegeven wordt uitgevoerd wanneer de * methode .sendMessage wordt aangeroepen. Het onderdeel daarna met 'new TextMessage(anyString())' * betekent dat die nieuwe code moet worden uitgevoerd voor de methode .sendMessage(), wanneer er * aan .sendMessage() een object TextMessage wordt meegegeven waar elke bedenkbare string in mag * zitten (vandaar de anyString()). Ga nu naar comment #5. */ doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); /** * Comment #5 * Deze code hieronder is de daadwerkelijke testcode. De methode assertThat() controleert of iets dat je opgeeft * dat waar moet zijn, daadwerkelijk ook zo is. In dit geval wordt gecontroleerd of het binnengekomen object * TextMessage (zit op index 0 van args) een JSON string in zich heeft die gelijk is aan de opgegeven string * daar rechts van. Via de is() methode wordt aangegeven dat beide strings gelijk moeten zijn. De JSON wordt * gemaakt van een Object3D dat geupdate wordt (zie update methode in de DefaultWebSocketView class). In de * JSON code hieronder zie je dat voor elke parameter in de JSON een standaardwaarde is ingevoerd. Ga nu naar * comment #6 om te zien hoe we ervoor zorgen dat de update() methode ook gebruiktmaakt van die standaardwaarden. */ assertThat(((TextMessage)args[0]).getPayload(), is("{\"command\": \"object_update\",\"parameters\": {\"uuid\":\"unique_string\",\"type\":\"type_here\",\"x\":0.0,\"y\":0.0,\"z\":0.0,\"rotationX\":0.0,\"rotationY\":0.0,\"rotationZ\":0.0,\"status\":\"status_here\"}}")); return null; } }).when(mockSession).sendMessage(new TextMessage(anyString())); /** * Comment #1 * De testfunctie waar we nu inzitten heet testUpdateSignal. Dit updatesignal slaat op het updaten van een * view binnen de simulatie. Wanneer dat gebeurd, wordt er een JSON pakketje naar de webbrowser van die * view gestuurd. We gaan dit systeem simuleren om zo de validiteit van de JSON te kunnen testen. Daarvoor * hebben we eerst een nieuwe view nodig. Die wordt hieronder aangemaakt. Om een DefaultWebSocketView aan te * maken, hebben we iets van een websocket nodig (in dit geval een sessie, zie de projectcode). Zie comment #2. */ DefaultWebSocketView view = new DefaultWebSocketView(mockSession); /** * Commeent #6 * Hieronder wordt een Object3D aangemaakt. Dit doen we omdat de view.update() methode een Object3D nodig heeft. * Voor een Object3D geldt ook dat een simulatie nodig is om een Object3D object te kunnen krijgen. Omdat we de * simulatie niet draaien, mocken we een Object3D. We maken er dus als het ware eentje na. Hier voeren we de * standaardwaarden in die de JSON code bij comment #5 gebruikt om te controleren of de .update() methode van * view werkt. Ga nu naar comment #7 om te zien welke code de test in zijn werk zet. */ Object3D mockObj3D = mock(Object3D.class); when(mockObj3D.getUUID()).thenReturn("unique_string"); when(mockObj3D.getType()).thenReturn("type_here"); when(mockObj3D.getX()).thenReturn(0.0); when(mockObj3D.getY()).thenReturn(0.0); when(mockObj3D.getZ()).thenReturn(0.0); when(mockObj3D.getRotationX()).thenReturn(0.0); when(mockObj3D.getRotationY()).thenReturn(0.0); when(mockObj3D.getRotationZ()).thenReturn(0.0); when(mockObj3D.getStatus()).thenReturn("status_here"); /** * Comment #7 * De code hieronder activeert de .update() methode van view. Deze methode maakt van een Object3D (hier mockObj3D) * een JSON pakket en verstuurd deze via een websocket connectie. In de websocket connectie hebben we onze testcode * geïnjecteerd, en dit betekent dat dan de test ook zal worden uitgoerd. */ view.update(Model.UPDATE_COMMAND, mockObj3D); } }
Damiaen/AmazonSimulatie
src/test/java/com/nhlstenden/amazonsimulatie/tests/DefaultWebSocketViewTests.java
2,315
/** * Commeent #6 * Hieronder wordt een Object3D aangemaakt. Dit doen we omdat de view.update() methode een Object3D nodig heeft. * Voor een Object3D geldt ook dat een simulatie nodig is om een Object3D object te kunnen krijgen. Omdat we de * simulatie niet draaien, mocken we een Object3D. We maken er dus als het ware eentje na. Hier voeren we de * standaardwaarden in die de JSON code bij comment #5 gebruikt om te controleren of de .update() methode van * view werkt. Ga nu naar comment #7 om te zien welke code de test in zijn werk zet. */
block_comment
nl
package com.nhlstenden.amazonsimulatie.tests; import com.nhlstenden.amazonsimulatie.models.Model; import com.nhlstenden.amazonsimulatie.models.Object3D; import com.nhlstenden.amazonsimulatie.views.DefaultWebSocketView; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultWebSocketViewTests { /** * De code hieronder is een voorbeeld van een test in Java. Je schrijf per class die je wilt testen * een testclass zoals deze. Daarin zet je al je testfuncties. Vaak schrijf je per methode (of functie) * die je wilt testen een methode zoals deze hieronder. Kijk in de methode naar de genummerde comments. * Om de test het beste te begrijpen, begin je vanaf comment #1. */ @Test public void testUpdateSignal() throws Exception { /** * Comment #2 * Deze code hieronder hebben we nodig om de DefaultWebSocketView van comment 1 te kunnen maken. * Dat onderdeel van de software heeft een zogenaamde WebSocketSession nodig (een onderdeel waarmee * informatie via een websocket naar de webbrowser kan worden verstuurd). Een WebSocketSession is * normaal gesproken een onderdeel van het websocket systeem van onze server, en we kunnen niet * zomaar een WebSocketSession aanmaken wanneer er geen server draait, laat staan geen browser is. * Om dit toch te kunnen gebruiken, 'mocken' we de class WebSocketSession. Dit mocken betekent dat * we als het ware een 'nep' versie van het object maken. Deze 'mockSession'n (zie hieronder) is * een object dat wel alle methoden heeft van een echte WebSocketSession, maar de methoden doen * simpelweg niks. Hierdoor kun je code die een WebSocketSession nodig heeft, toch laten werken. * Ga nu naar comment #3. */ WebSocketSession mockSession = mock(WebSocketSession.class); /** * Comment #3 * De code hieronder is eigenlijk de invulling van een methode van WebSocketSession. Zoals je in * comment #2 las, is de het object mockSession een 'lege' WebSocketSession. De methoden bestaan dus * wel, maar doen in feite niks. Hieronder wordt een invulling gegeven. De when() functie is onderdeel * van het systeem om te mocken, en zegt hier wanneer de methode .isOpen() wordt aangeroepen op het object * mockSession, dan moet er iets gebeuren. Wat er moet gebeuren staat achter de when() methode, in de * vorm van .thenReturn(true). De hele regel code betekent nu dat wanneer .isOpen() wordt aangeroepen * op mockSession, dan moet deze methode altijd de waarde true teruggeven. Dit onderdeel is nodig omdat * de view in de update methode gebruikmaakt van de .isOpen() methode. Ga nu naar comment #4. */ when(mockSession.isOpen()).thenReturn(true); /** * Comment 4 * De code hieronder is misschien wat onduidelijk. Wat we hier doen, is het injecteren van testcode binnen * het mockSession object. Dit doen we omdat mockSession gebruikt wordt om het JSON pakketje te versturen. * Dit object krijgt dus sowieso de JSON tekst te zien. Dit gebeurd in de methode .sendMessage(). Hier wordt * een tekstbericht verstuurd naar de browser. In dit bericht zit de JSON code. Hier kunnen we dus een test * injecteren om de validiteit van de JSON de controleren. Dit is ook wat hieronder gebeurd. De methode * doAnwser hieronder zorgt ervoor dat de code die daarin wordt gegeven wordt uitgevoerd wanneer de * methode .sendMessage wordt aangeroepen. Het onderdeel daarna met 'new TextMessage(anyString())' * betekent dat die nieuwe code moet worden uitgevoerd voor de methode .sendMessage(), wanneer er * aan .sendMessage() een object TextMessage wordt meegegeven waar elke bedenkbare string in mag * zitten (vandaar de anyString()). Ga nu naar comment #5. */ doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); /** * Comment #5 * Deze code hieronder is de daadwerkelijke testcode. De methode assertThat() controleert of iets dat je opgeeft * dat waar moet zijn, daadwerkelijk ook zo is. In dit geval wordt gecontroleerd of het binnengekomen object * TextMessage (zit op index 0 van args) een JSON string in zich heeft die gelijk is aan de opgegeven string * daar rechts van. Via de is() methode wordt aangegeven dat beide strings gelijk moeten zijn. De JSON wordt * gemaakt van een Object3D dat geupdate wordt (zie update methode in de DefaultWebSocketView class). In de * JSON code hieronder zie je dat voor elke parameter in de JSON een standaardwaarde is ingevoerd. Ga nu naar * comment #6 om te zien hoe we ervoor zorgen dat de update() methode ook gebruiktmaakt van die standaardwaarden. */ assertThat(((TextMessage)args[0]).getPayload(), is("{\"command\": \"object_update\",\"parameters\": {\"uuid\":\"unique_string\",\"type\":\"type_here\",\"x\":0.0,\"y\":0.0,\"z\":0.0,\"rotationX\":0.0,\"rotationY\":0.0,\"rotationZ\":0.0,\"status\":\"status_here\"}}")); return null; } }).when(mockSession).sendMessage(new TextMessage(anyString())); /** * Comment #1 * De testfunctie waar we nu inzitten heet testUpdateSignal. Dit updatesignal slaat op het updaten van een * view binnen de simulatie. Wanneer dat gebeurd, wordt er een JSON pakketje naar de webbrowser van die * view gestuurd. We gaan dit systeem simuleren om zo de validiteit van de JSON te kunnen testen. Daarvoor * hebben we eerst een nieuwe view nodig. Die wordt hieronder aangemaakt. Om een DefaultWebSocketView aan te * maken, hebben we iets van een websocket nodig (in dit geval een sessie, zie de projectcode). Zie comment #2. */ DefaultWebSocketView view = new DefaultWebSocketView(mockSession); /** * Commeent #6 <SUF>*/ Object3D mockObj3D = mock(Object3D.class); when(mockObj3D.getUUID()).thenReturn("unique_string"); when(mockObj3D.getType()).thenReturn("type_here"); when(mockObj3D.getX()).thenReturn(0.0); when(mockObj3D.getY()).thenReturn(0.0); when(mockObj3D.getZ()).thenReturn(0.0); when(mockObj3D.getRotationX()).thenReturn(0.0); when(mockObj3D.getRotationY()).thenReturn(0.0); when(mockObj3D.getRotationZ()).thenReturn(0.0); when(mockObj3D.getStatus()).thenReturn("status_here"); /** * Comment #7 * De code hieronder activeert de .update() methode van view. Deze methode maakt van een Object3D (hier mockObj3D) * een JSON pakket en verstuurd deze via een websocket connectie. In de websocket connectie hebben we onze testcode * geïnjecteerd, en dit betekent dat dan de test ook zal worden uitgoerd. */ view.update(Model.UPDATE_COMMAND, mockObj3D); } }
True
False
1,403
3,658
31698_0
package Symbols; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.io.StringReader; public class Tokenizer { public Tokenizer(Reader inStream) { numOfErrors = 0; currentChar = '\0'; currentLine = 1; inputStream = new PushbackReader(inStream); } private static final int SLASH_SLASH = 0; private static final int SLASH_STAR = 1; private static final char NEW_LINE = '\n'; private PushbackReader inputStream; private char currentChar; private int currentLine; private int numOfErrors; public int getLineNumber() { return currentLine; } public int getErrorCount() { return numOfErrors; } public char getNextOpenClose() { while (nextChar()) { if (currentChar == '/') { processSlash(); } else if (currentChar == '\'' || currentChar == '"') { skipQuote(currentChar); } else if (currentChar == '(' || currentChar == '[' || currentChar == '{' || currentChar == ')' || currentChar == ']' || currentChar == '}') { return currentChar; } } return '\0'; } @Override public String toString() { StringBuilder result = new StringBuilder(); while (nextChar()) { result.append(currentChar); } inputStream = new PushbackReader(new StringReader(result.toString())); // Niet de mooiste manier, werkt voor nu. return result.toString(); } //public char getNextID() { /* Figure 12.29 */ //} private boolean nextChar() { try { int currentCharValue = inputStream.read(); if (currentCharValue == -1) { return false; } currentChar = (char) currentCharValue; if (currentChar == NEW_LINE) { currentLine++; } return true; } catch (IOException e) { return false; } } private void putBackChar() { if (currentChar == NEW_LINE) { currentLine--; } try { inputStream.unread((int) currentChar); } catch (IOException e) { // Swallow } } private void skipComment(int start) { if (start == SLASH_SLASH) { while (nextChar() && (currentChar != '\n')) ; return; } boolean state = false; while (nextChar()) { if (state && currentChar == '/') { return; } state = currentChar == '*'; } numOfErrors++; System.out.println("Unterminated comment!"); } private void skipQuote(char quoteType) { while (nextChar()) { if (currentChar == quoteType) { return; } if (currentChar == NEW_LINE) { numOfErrors++; System.out.println(String.format( "Missing closed quote at line %s", currentLine)); } else if (currentChar == '\\') { nextChar(); } } } private void processSlash() { if (nextChar()) { if (currentChar == '*') { if (nextChar() && currentChar != '*') { putBackChar(); } skipComment(SLASH_STAR); } else if (currentChar == '/') { skipComment(SLASH_SLASH); } else if (currentChar != NEW_LINE) { putBackChar(); } } } //private static final boolean isIdChar(char ch) { /* Figure 12.27 */ //} //private String getRemainingString() { /* Figure 12.28 */ //} }
mikederksen/Algorithms
src/main/java/Symbols/Tokenizer.java
1,050
// Niet de mooiste manier, werkt voor nu.
line_comment
nl
package Symbols; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.io.StringReader; public class Tokenizer { public Tokenizer(Reader inStream) { numOfErrors = 0; currentChar = '\0'; currentLine = 1; inputStream = new PushbackReader(inStream); } private static final int SLASH_SLASH = 0; private static final int SLASH_STAR = 1; private static final char NEW_LINE = '\n'; private PushbackReader inputStream; private char currentChar; private int currentLine; private int numOfErrors; public int getLineNumber() { return currentLine; } public int getErrorCount() { return numOfErrors; } public char getNextOpenClose() { while (nextChar()) { if (currentChar == '/') { processSlash(); } else if (currentChar == '\'' || currentChar == '"') { skipQuote(currentChar); } else if (currentChar == '(' || currentChar == '[' || currentChar == '{' || currentChar == ')' || currentChar == ']' || currentChar == '}') { return currentChar; } } return '\0'; } @Override public String toString() { StringBuilder result = new StringBuilder(); while (nextChar()) { result.append(currentChar); } inputStream = new PushbackReader(new StringReader(result.toString())); // Niet de<SUF> return result.toString(); } //public char getNextID() { /* Figure 12.29 */ //} private boolean nextChar() { try { int currentCharValue = inputStream.read(); if (currentCharValue == -1) { return false; } currentChar = (char) currentCharValue; if (currentChar == NEW_LINE) { currentLine++; } return true; } catch (IOException e) { return false; } } private void putBackChar() { if (currentChar == NEW_LINE) { currentLine--; } try { inputStream.unread((int) currentChar); } catch (IOException e) { // Swallow } } private void skipComment(int start) { if (start == SLASH_SLASH) { while (nextChar() && (currentChar != '\n')) ; return; } boolean state = false; while (nextChar()) { if (state && currentChar == '/') { return; } state = currentChar == '*'; } numOfErrors++; System.out.println("Unterminated comment!"); } private void skipQuote(char quoteType) { while (nextChar()) { if (currentChar == quoteType) { return; } if (currentChar == NEW_LINE) { numOfErrors++; System.out.println(String.format( "Missing closed quote at line %s", currentLine)); } else if (currentChar == '\\') { nextChar(); } } } private void processSlash() { if (nextChar()) { if (currentChar == '*') { if (nextChar() && currentChar != '*') { putBackChar(); } skipComment(SLASH_STAR); } else if (currentChar == '/') { skipComment(SLASH_SLASH); } else if (currentChar != NEW_LINE) { putBackChar(); } } } //private static final boolean isIdChar(char ch) { /* Figure 12.27 */ //} //private String getRemainingString() { /* Figure 12.28 */ //} }
True
False
1,404
1,463
151744_8
package nl.han.ica.icss.checker; import nl.han.ica.datastructures.HANLinkedList; import nl.han.ica.datastructures.IHANLinkedList; import nl.han.ica.icss.ast.*; import nl.han.ica.icss.ast.literals.*; import nl.han.ica.icss.ast.operations.AddOperation; import nl.han.ica.icss.ast.operations.MultiplyOperation; import nl.han.ica.icss.ast.operations.SubtractOperation; import nl.han.ica.icss.ast.types.ExpressionType; import java.util.HashMap; import java.util.Stack; public class Checker { private IHANLinkedList<HashMap<String, ExpressionType>> variableTypes; private Stack<HashMap<String, ExpressionType>> variableScopeStack; public void check(AST ast) { variableTypes = new HANLinkedList<>(); variableScopeStack = new Stack<>(); variableTypes.addFirst(new HashMap<>()); for (int i = 0; i < variableTypes.getSize(); i++){ HashMap<String, ExpressionType> scope = variableTypes.get(i); variableScopeStack.push(scope); } findAllVariables(ast.root); checkAST(ast.root); } private void checkAST(ASTNode node){ checkVariables(node, variableScopeStack); checkOperationTypes(node); checkNoColorsInOperation(node); checkIfDeclarationValueMatchesProperty(node); checkIfConditionIsBoolean(node); node.getChildren().forEach(this::checkAST); } /** * Function for CH01 & CH06: * CH01: "Controleer of er geen variabelen worden gebruikt die niet gedefinieerd zijn." * CH06: "Controleer of variabelen niet buiten hun scope worden gebruikt." * Checks if the variable is defined in the current scope. * If the variable is not defined in the current scope, it checks if the variable is defined in a higher scope. * If the variable is not defined in a higher scope, it sets an error. * * @param toBeChecked: The node that needs to be checked * @param variableScopeStack: The stack that contains all the scopes * */ private void checkVariables(ASTNode toBeChecked, Stack<HashMap<String, ExpressionType>> variableScopeStack) { if (toBeChecked instanceof VariableReference) { String name = ((VariableReference) toBeChecked).name; if (!isWithinScope(variableScopeStack, name)) { if (isWithinScope(variableScopeStack, name)) { toBeChecked.setError("The variable " + name + " is used outside its scope!"); } else { toBeChecked.setError("Variable " + name + " is not defined (within this scope) and can't be used"); } } } else { for (ASTNode child : toBeChecked.getChildren()) { checkVariables(child, variableScopeStack); } } } /** * This helper function checks if a variable is within the scope of the current scope. * If the variable is defined in the current scope or in a higher scope, it returns true. * * @param variableScopeStack: The stack that contains all the scopes * (the current scope is the last element in the stack) * (the highest scope is the first element in the stack) * @param variableName: The name of the variable that needs to be checked */ private boolean isWithinScope(Stack<HashMap<String, ExpressionType>> variableScopeStack, String variableName) { for (HashMap<String, ExpressionType> scope : variableScopeStack) { if (scope.containsKey(variableName)) { return true; } } return false; } /** * Function for CH02: * "Controleer of de operanden van de operaties plus en min van gelijke type zijn. * Je mag geen pixels bij percentages optellen bijvoorbeeld. * Controleer dat bij vermenigvuldigen minimaal een operand een scalaire waarde is." * Checks if the operands of the operations plus and minus are of the same type. * Checks if the operands of the operation multiply are of type scalar and pixel or percentage. * Else sets an error. * * @param toBeChecked: The node that needs to be checked * */ private void checkOperationTypes(ASTNode toBeChecked) { if(toBeChecked.getChildren().size() != 1){ if(toBeChecked instanceof AddOperation || toBeChecked instanceof SubtractOperation){ if (((Operation) toBeChecked).lhs instanceof VariableReference){ if (variableTypes.getFirst().containsKey(((VariableReference) ((Operation) toBeChecked).lhs).name)) { if (variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).lhs).name) != resolveExpressionType(((Operation) toBeChecked).rhs)) { toBeChecked.setError("The operand types must be of the same type!"); } } } else if (((Operation) toBeChecked).rhs instanceof VariableReference) { if (variableTypes.getFirst().containsKey(((VariableReference) ((Operation) toBeChecked).rhs).name)) { if (variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).rhs).name) != resolveExpressionType(((Operation) toBeChecked).lhs)) { toBeChecked.setError("The operand types must be of the same type!"); } } } else if (((Operation) toBeChecked).lhs instanceof VariableReference && ((Operation) toBeChecked).rhs instanceof VariableReference) { if (variableTypes.getFirst().containsKey(((VariableReference) ((Operation) toBeChecked).lhs).name) && variableTypes.getFirst().containsKey(((VariableReference) ((Operation) toBeChecked).rhs).name)) { if (variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).lhs).name) != variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).rhs).name)) { toBeChecked.setError("The operand types must be of the same type!"); } } } else if (resolveExpressionType(((Operation) toBeChecked).lhs) != resolveExpressionType(((Operation) toBeChecked).rhs)) { toBeChecked.setError("The operand types must be of the same type!"); } } else if (toBeChecked instanceof MultiplyOperation) { if ((resolveExpressionType(((MultiplyOperation) toBeChecked).lhs) != ExpressionType.SCALAR && resolveExpressionType(((MultiplyOperation) toBeChecked).rhs) != ExpressionType.SCALAR) || (resolveExpressionType(((MultiplyOperation) toBeChecked).lhs) == ExpressionType.SCALAR && resolveExpressionType(((MultiplyOperation) toBeChecked).rhs) == ExpressionType.SCALAR)) { toBeChecked.setError("One of the operands must be of type scalar!"); } } } } /** * Function for CH03: * "Controleer of er geen kleuren worden gebruikt in operaties (plus, min of keer)." * Checks if either the left or right side of an operation is a Colorliteral * or VariableReference with ExpressionType color, else sets an error. * * @param toBeChecked: The node that needs to be checked * */ private void checkNoColorsInOperation(ASTNode toBeChecked){ if (toBeChecked.getChildren().size() != 1){ if (toBeChecked instanceof Operation){ if (((Operation) toBeChecked).lhs instanceof VariableReference) { if (variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).lhs).name) == ExpressionType.COLOR) { toBeChecked.setError("Colors can't be used in operations!"); } } if (((Operation) toBeChecked).rhs instanceof VariableReference) { if (variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).rhs).name) == ExpressionType.COLOR) { toBeChecked.setError("Colors can't be used in operations!"); } } if (((Operation) toBeChecked).lhs instanceof ColorLiteral || ((Operation) toBeChecked).rhs instanceof ColorLiteral) { toBeChecked.setError("Colors can't be used in operations!"); } } } } /** * Function for CH04: * "Controleer of bij declaraties het type van de value klopt met de property. * Declaraties zoals width: #ff0000 of color: 12px zijn natuurlijk onzin." * Checks for the properties color and background-color if the value is of type color. * Checks for the properties width and height if the value is of type pixel or percentage. * Checks if the value is a VariableReference if the variable is of type color, pixel or percentage. * If the value is an Operation, checks if the result of the operation is of type color, pixel or percentage. * Else sets an error. * * @param toBeChecked: The node that needs to be checked * */ private void checkIfDeclarationValueMatchesProperty(ASTNode toBeChecked) { if (toBeChecked.getChildren().size() != 1) { if (toBeChecked instanceof Declaration) { PropertyName propertyName = ((Declaration) toBeChecked).property; Expression expressionOfProperty = ((Declaration) toBeChecked).expression; if ((propertyName.name.equals("color") || propertyName.name.equals("background-color"))) { if (expressionOfProperty instanceof Operation) { toBeChecked.setError("Operations are not allowed in color declarations!"); } if (expressionOfProperty instanceof VariableReference) { if (variableTypes.getFirst().containsKey(((VariableReference) expressionOfProperty).name)) { if (variableTypes.getFirst().get(((VariableReference) expressionOfProperty).name) != ExpressionType.COLOR) { toBeChecked.setError("The variable in the declaration must be of type color!"); } } } else if (resolveExpressionType(expressionOfProperty) != ExpressionType.COLOR) { toBeChecked.setError("The declaration must be of type color!"); } } if ((propertyName.name.equals("width")|| propertyName.name.equals("height"))) { if (expressionOfProperty instanceof Operation) { if (checkOperationResultType((Operation) expressionOfProperty) != ExpressionType.PIXEL && checkOperationResultType((Operation) expressionOfProperty) != ExpressionType.PERCENTAGE) { toBeChecked.setError("Operations in width and height declarations must be of type pixel or percentage!"); } } if (expressionOfProperty instanceof VariableReference) { if (variableTypes.getFirst().containsKey(((VariableReference) expressionOfProperty).name)) { if (variableTypes.getFirst().get(((VariableReference) expressionOfProperty).name) != ExpressionType.PIXEL && variableTypes.getFirst().get(((VariableReference) expressionOfProperty).name) != ExpressionType.PERCENTAGE) { toBeChecked.setError("Variables in width and height declarations must be of type pixel or percentage!"); } } } else if (resolveExpressionType(expressionOfProperty) != ExpressionType.PIXEL && resolveExpressionType(expressionOfProperty) != ExpressionType.PERCENTAGE) { toBeChecked.setError("The declaration must be of type pixel or percentage!"); } } } } } /** * Function for CH05: * "Controleer of de conditie bij een if-statement van het type boolean is" * Checks if the condition of an if-statement is of type boolean. * If the condition is a VariableReference, checks if the variable is of type boolean. * Else sets an error. * * @param toBeChecked: The node that needs to be checked * */ private void checkIfConditionIsBoolean(ASTNode toBeChecked){ if (toBeChecked.getChildren().size() != 1 ){ if (toBeChecked instanceof IfClause){ if (((IfClause) toBeChecked).getConditionalExpression() instanceof VariableReference) { if (variableTypes.getFirst().containsKey(((VariableReference) ((IfClause) toBeChecked).getConditionalExpression()).name)) { if (variableTypes.getFirst().get(((VariableReference) ((IfClause) toBeChecked).getConditionalExpression()).name) != ExpressionType.BOOL) { toBeChecked.setError("The variable in the if-statement must be of type boolean!"); } } } else if (!(((IfClause) toBeChecked).getConditionalExpression() instanceof BoolLiteral)) { toBeChecked.setError("The if-statement must be of type boolean!"); } } } } /** * This method finds all the variables in the AST and adds them to the variableScopeStack. * It checks if the variable is already defined in the current scope, if so it sets an error. * * @param toBeFound: The node that needs to be checked * @param variableScopeStack: The stack that contains all the scopes */ private void findAllVariables(ASTNode toBeFound, Stack<HashMap<String, ExpressionType>> variableScopeStack){ if(toBeFound instanceof VariableAssignment){ String name = ((VariableAssignment) toBeFound).name.name; ExpressionType expressionType = resolveExpressionType(((VariableAssignment) toBeFound).expression); variableScopeStack.peek().put(name, expressionType); } else if (toBeFound instanceof Stylerule) { //Betreden nieuwe scope, voegt een nieuwe map toe aan de stack variableScopeStack.push(new HashMap<>()); } for(ASTNode child : toBeFound.getChildren()){ findAllVariables(child, variableScopeStack); } if(toBeFound instanceof Stylerule){ //Verlaat scope, verwijdert de map van de stack variableScopeStack.pop(); } } /** * overloaded method for findAllVariables * This method finds all the variables in the AST and adds them to the variableScopeStack. * * @param toBeFound: The node that needs to be checked */ private void findAllVariables(ASTNode toBeFound){ findAllVariables(toBeFound, variableScopeStack); } /** * This method resolves the ExpressionType of the given Expression. * If the Expression is a VariableReference, it checks if the variable is defined and returns the ExpressionType of the variable. * Else it returns the ExpressionType of the Expression. * * @param expression: The expression that needs to be checked * @return ExpressionType: The ExpressionType of the given Expression */ private ExpressionType resolveExpressionType(Expression expression){ if(expression instanceof BoolLiteral){ return ExpressionType.BOOL; } else if (expression instanceof ColorLiteral){ return ExpressionType.COLOR; } else if (expression instanceof PercentageLiteral){ return ExpressionType.PERCENTAGE; } else if (expression instanceof PixelLiteral){ return ExpressionType.PIXEL; } else if (expression instanceof ScalarLiteral){ return ExpressionType.SCALAR; } else if (expression instanceof Operation){ return checkOperationResultType((Operation) expression); } else if (expression instanceof VariableReference){ if(variableTypes.getFirst().containsKey(((VariableReference) expression).name)){ return variableTypes.getFirst().get(((VariableReference) expression).name); } } return ExpressionType.UNDEFINED; } /** * This recursive method gets the left and right side of an ExpressionType, it then checks which type of operation it is * and returns the ExpressionType of the result of the operation. * If the operation is not valid, it returns ExpressionType.UNDEFINED. * * @param operation: The operation that needs to be checked (AddOperation, SubtractOperation or MultiplyOperation) * @return ExpressionType or Undefined: The ExpressionType of the result of the operation */ private ExpressionType checkOperationResultType(Operation operation){ ExpressionType left = resolveExpressionType(operation.lhs); ExpressionType right = resolveExpressionType(operation.rhs); if(operation instanceof MultiplyOperation) { if (left == ExpressionType.SCALAR) { if (right == ExpressionType.PIXEL) { return ExpressionType.PIXEL; } if (right == ExpressionType.PERCENTAGE){ return ExpressionType.PERCENTAGE; } } else if (right == ExpressionType.SCALAR) { if (left == ExpressionType.PIXEL) { return ExpressionType.PIXEL; } if (left == ExpressionType.PERCENTAGE){ return ExpressionType.PERCENTAGE; } } } if (operation instanceof AddOperation || operation instanceof SubtractOperation){ if (left == ExpressionType.PIXEL) { if (left == right) { return ExpressionType.PIXEL; } } if (right == ExpressionType.PERCENTAGE) { if (left == right) { return ExpressionType.PERCENTAGE; } } } return ExpressionType.UNDEFINED; } }
RichieRamz18/APP-Compiler-Beroepsproduct
icss2022-sep-main/icss2022-sep-main/startcode/src/main/java/nl/han/ica/icss/checker/Checker.java
4,634
//Verlaat scope, verwijdert de map van de stack
line_comment
nl
package nl.han.ica.icss.checker; import nl.han.ica.datastructures.HANLinkedList; import nl.han.ica.datastructures.IHANLinkedList; import nl.han.ica.icss.ast.*; import nl.han.ica.icss.ast.literals.*; import nl.han.ica.icss.ast.operations.AddOperation; import nl.han.ica.icss.ast.operations.MultiplyOperation; import nl.han.ica.icss.ast.operations.SubtractOperation; import nl.han.ica.icss.ast.types.ExpressionType; import java.util.HashMap; import java.util.Stack; public class Checker { private IHANLinkedList<HashMap<String, ExpressionType>> variableTypes; private Stack<HashMap<String, ExpressionType>> variableScopeStack; public void check(AST ast) { variableTypes = new HANLinkedList<>(); variableScopeStack = new Stack<>(); variableTypes.addFirst(new HashMap<>()); for (int i = 0; i < variableTypes.getSize(); i++){ HashMap<String, ExpressionType> scope = variableTypes.get(i); variableScopeStack.push(scope); } findAllVariables(ast.root); checkAST(ast.root); } private void checkAST(ASTNode node){ checkVariables(node, variableScopeStack); checkOperationTypes(node); checkNoColorsInOperation(node); checkIfDeclarationValueMatchesProperty(node); checkIfConditionIsBoolean(node); node.getChildren().forEach(this::checkAST); } /** * Function for CH01 & CH06: * CH01: "Controleer of er geen variabelen worden gebruikt die niet gedefinieerd zijn." * CH06: "Controleer of variabelen niet buiten hun scope worden gebruikt." * Checks if the variable is defined in the current scope. * If the variable is not defined in the current scope, it checks if the variable is defined in a higher scope. * If the variable is not defined in a higher scope, it sets an error. * * @param toBeChecked: The node that needs to be checked * @param variableScopeStack: The stack that contains all the scopes * */ private void checkVariables(ASTNode toBeChecked, Stack<HashMap<String, ExpressionType>> variableScopeStack) { if (toBeChecked instanceof VariableReference) { String name = ((VariableReference) toBeChecked).name; if (!isWithinScope(variableScopeStack, name)) { if (isWithinScope(variableScopeStack, name)) { toBeChecked.setError("The variable " + name + " is used outside its scope!"); } else { toBeChecked.setError("Variable " + name + " is not defined (within this scope) and can't be used"); } } } else { for (ASTNode child : toBeChecked.getChildren()) { checkVariables(child, variableScopeStack); } } } /** * This helper function checks if a variable is within the scope of the current scope. * If the variable is defined in the current scope or in a higher scope, it returns true. * * @param variableScopeStack: The stack that contains all the scopes * (the current scope is the last element in the stack) * (the highest scope is the first element in the stack) * @param variableName: The name of the variable that needs to be checked */ private boolean isWithinScope(Stack<HashMap<String, ExpressionType>> variableScopeStack, String variableName) { for (HashMap<String, ExpressionType> scope : variableScopeStack) { if (scope.containsKey(variableName)) { return true; } } return false; } /** * Function for CH02: * "Controleer of de operanden van de operaties plus en min van gelijke type zijn. * Je mag geen pixels bij percentages optellen bijvoorbeeld. * Controleer dat bij vermenigvuldigen minimaal een operand een scalaire waarde is." * Checks if the operands of the operations plus and minus are of the same type. * Checks if the operands of the operation multiply are of type scalar and pixel or percentage. * Else sets an error. * * @param toBeChecked: The node that needs to be checked * */ private void checkOperationTypes(ASTNode toBeChecked) { if(toBeChecked.getChildren().size() != 1){ if(toBeChecked instanceof AddOperation || toBeChecked instanceof SubtractOperation){ if (((Operation) toBeChecked).lhs instanceof VariableReference){ if (variableTypes.getFirst().containsKey(((VariableReference) ((Operation) toBeChecked).lhs).name)) { if (variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).lhs).name) != resolveExpressionType(((Operation) toBeChecked).rhs)) { toBeChecked.setError("The operand types must be of the same type!"); } } } else if (((Operation) toBeChecked).rhs instanceof VariableReference) { if (variableTypes.getFirst().containsKey(((VariableReference) ((Operation) toBeChecked).rhs).name)) { if (variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).rhs).name) != resolveExpressionType(((Operation) toBeChecked).lhs)) { toBeChecked.setError("The operand types must be of the same type!"); } } } else if (((Operation) toBeChecked).lhs instanceof VariableReference && ((Operation) toBeChecked).rhs instanceof VariableReference) { if (variableTypes.getFirst().containsKey(((VariableReference) ((Operation) toBeChecked).lhs).name) && variableTypes.getFirst().containsKey(((VariableReference) ((Operation) toBeChecked).rhs).name)) { if (variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).lhs).name) != variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).rhs).name)) { toBeChecked.setError("The operand types must be of the same type!"); } } } else if (resolveExpressionType(((Operation) toBeChecked).lhs) != resolveExpressionType(((Operation) toBeChecked).rhs)) { toBeChecked.setError("The operand types must be of the same type!"); } } else if (toBeChecked instanceof MultiplyOperation) { if ((resolveExpressionType(((MultiplyOperation) toBeChecked).lhs) != ExpressionType.SCALAR && resolveExpressionType(((MultiplyOperation) toBeChecked).rhs) != ExpressionType.SCALAR) || (resolveExpressionType(((MultiplyOperation) toBeChecked).lhs) == ExpressionType.SCALAR && resolveExpressionType(((MultiplyOperation) toBeChecked).rhs) == ExpressionType.SCALAR)) { toBeChecked.setError("One of the operands must be of type scalar!"); } } } } /** * Function for CH03: * "Controleer of er geen kleuren worden gebruikt in operaties (plus, min of keer)." * Checks if either the left or right side of an operation is a Colorliteral * or VariableReference with ExpressionType color, else sets an error. * * @param toBeChecked: The node that needs to be checked * */ private void checkNoColorsInOperation(ASTNode toBeChecked){ if (toBeChecked.getChildren().size() != 1){ if (toBeChecked instanceof Operation){ if (((Operation) toBeChecked).lhs instanceof VariableReference) { if (variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).lhs).name) == ExpressionType.COLOR) { toBeChecked.setError("Colors can't be used in operations!"); } } if (((Operation) toBeChecked).rhs instanceof VariableReference) { if (variableTypes.getFirst().get(((VariableReference) ((Operation) toBeChecked).rhs).name) == ExpressionType.COLOR) { toBeChecked.setError("Colors can't be used in operations!"); } } if (((Operation) toBeChecked).lhs instanceof ColorLiteral || ((Operation) toBeChecked).rhs instanceof ColorLiteral) { toBeChecked.setError("Colors can't be used in operations!"); } } } } /** * Function for CH04: * "Controleer of bij declaraties het type van de value klopt met de property. * Declaraties zoals width: #ff0000 of color: 12px zijn natuurlijk onzin." * Checks for the properties color and background-color if the value is of type color. * Checks for the properties width and height if the value is of type pixel or percentage. * Checks if the value is a VariableReference if the variable is of type color, pixel or percentage. * If the value is an Operation, checks if the result of the operation is of type color, pixel or percentage. * Else sets an error. * * @param toBeChecked: The node that needs to be checked * */ private void checkIfDeclarationValueMatchesProperty(ASTNode toBeChecked) { if (toBeChecked.getChildren().size() != 1) { if (toBeChecked instanceof Declaration) { PropertyName propertyName = ((Declaration) toBeChecked).property; Expression expressionOfProperty = ((Declaration) toBeChecked).expression; if ((propertyName.name.equals("color") || propertyName.name.equals("background-color"))) { if (expressionOfProperty instanceof Operation) { toBeChecked.setError("Operations are not allowed in color declarations!"); } if (expressionOfProperty instanceof VariableReference) { if (variableTypes.getFirst().containsKey(((VariableReference) expressionOfProperty).name)) { if (variableTypes.getFirst().get(((VariableReference) expressionOfProperty).name) != ExpressionType.COLOR) { toBeChecked.setError("The variable in the declaration must be of type color!"); } } } else if (resolveExpressionType(expressionOfProperty) != ExpressionType.COLOR) { toBeChecked.setError("The declaration must be of type color!"); } } if ((propertyName.name.equals("width")|| propertyName.name.equals("height"))) { if (expressionOfProperty instanceof Operation) { if (checkOperationResultType((Operation) expressionOfProperty) != ExpressionType.PIXEL && checkOperationResultType((Operation) expressionOfProperty) != ExpressionType.PERCENTAGE) { toBeChecked.setError("Operations in width and height declarations must be of type pixel or percentage!"); } } if (expressionOfProperty instanceof VariableReference) { if (variableTypes.getFirst().containsKey(((VariableReference) expressionOfProperty).name)) { if (variableTypes.getFirst().get(((VariableReference) expressionOfProperty).name) != ExpressionType.PIXEL && variableTypes.getFirst().get(((VariableReference) expressionOfProperty).name) != ExpressionType.PERCENTAGE) { toBeChecked.setError("Variables in width and height declarations must be of type pixel or percentage!"); } } } else if (resolveExpressionType(expressionOfProperty) != ExpressionType.PIXEL && resolveExpressionType(expressionOfProperty) != ExpressionType.PERCENTAGE) { toBeChecked.setError("The declaration must be of type pixel or percentage!"); } } } } } /** * Function for CH05: * "Controleer of de conditie bij een if-statement van het type boolean is" * Checks if the condition of an if-statement is of type boolean. * If the condition is a VariableReference, checks if the variable is of type boolean. * Else sets an error. * * @param toBeChecked: The node that needs to be checked * */ private void checkIfConditionIsBoolean(ASTNode toBeChecked){ if (toBeChecked.getChildren().size() != 1 ){ if (toBeChecked instanceof IfClause){ if (((IfClause) toBeChecked).getConditionalExpression() instanceof VariableReference) { if (variableTypes.getFirst().containsKey(((VariableReference) ((IfClause) toBeChecked).getConditionalExpression()).name)) { if (variableTypes.getFirst().get(((VariableReference) ((IfClause) toBeChecked).getConditionalExpression()).name) != ExpressionType.BOOL) { toBeChecked.setError("The variable in the if-statement must be of type boolean!"); } } } else if (!(((IfClause) toBeChecked).getConditionalExpression() instanceof BoolLiteral)) { toBeChecked.setError("The if-statement must be of type boolean!"); } } } } /** * This method finds all the variables in the AST and adds them to the variableScopeStack. * It checks if the variable is already defined in the current scope, if so it sets an error. * * @param toBeFound: The node that needs to be checked * @param variableScopeStack: The stack that contains all the scopes */ private void findAllVariables(ASTNode toBeFound, Stack<HashMap<String, ExpressionType>> variableScopeStack){ if(toBeFound instanceof VariableAssignment){ String name = ((VariableAssignment) toBeFound).name.name; ExpressionType expressionType = resolveExpressionType(((VariableAssignment) toBeFound).expression); variableScopeStack.peek().put(name, expressionType); } else if (toBeFound instanceof Stylerule) { //Betreden nieuwe scope, voegt een nieuwe map toe aan de stack variableScopeStack.push(new HashMap<>()); } for(ASTNode child : toBeFound.getChildren()){ findAllVariables(child, variableScopeStack); } if(toBeFound instanceof Stylerule){ //Verlaat scope,<SUF> variableScopeStack.pop(); } } /** * overloaded method for findAllVariables * This method finds all the variables in the AST and adds them to the variableScopeStack. * * @param toBeFound: The node that needs to be checked */ private void findAllVariables(ASTNode toBeFound){ findAllVariables(toBeFound, variableScopeStack); } /** * This method resolves the ExpressionType of the given Expression. * If the Expression is a VariableReference, it checks if the variable is defined and returns the ExpressionType of the variable. * Else it returns the ExpressionType of the Expression. * * @param expression: The expression that needs to be checked * @return ExpressionType: The ExpressionType of the given Expression */ private ExpressionType resolveExpressionType(Expression expression){ if(expression instanceof BoolLiteral){ return ExpressionType.BOOL; } else if (expression instanceof ColorLiteral){ return ExpressionType.COLOR; } else if (expression instanceof PercentageLiteral){ return ExpressionType.PERCENTAGE; } else if (expression instanceof PixelLiteral){ return ExpressionType.PIXEL; } else if (expression instanceof ScalarLiteral){ return ExpressionType.SCALAR; } else if (expression instanceof Operation){ return checkOperationResultType((Operation) expression); } else if (expression instanceof VariableReference){ if(variableTypes.getFirst().containsKey(((VariableReference) expression).name)){ return variableTypes.getFirst().get(((VariableReference) expression).name); } } return ExpressionType.UNDEFINED; } /** * This recursive method gets the left and right side of an ExpressionType, it then checks which type of operation it is * and returns the ExpressionType of the result of the operation. * If the operation is not valid, it returns ExpressionType.UNDEFINED. * * @param operation: The operation that needs to be checked (AddOperation, SubtractOperation or MultiplyOperation) * @return ExpressionType or Undefined: The ExpressionType of the result of the operation */ private ExpressionType checkOperationResultType(Operation operation){ ExpressionType left = resolveExpressionType(operation.lhs); ExpressionType right = resolveExpressionType(operation.rhs); if(operation instanceof MultiplyOperation) { if (left == ExpressionType.SCALAR) { if (right == ExpressionType.PIXEL) { return ExpressionType.PIXEL; } if (right == ExpressionType.PERCENTAGE){ return ExpressionType.PERCENTAGE; } } else if (right == ExpressionType.SCALAR) { if (left == ExpressionType.PIXEL) { return ExpressionType.PIXEL; } if (left == ExpressionType.PERCENTAGE){ return ExpressionType.PERCENTAGE; } } } if (operation instanceof AddOperation || operation instanceof SubtractOperation){ if (left == ExpressionType.PIXEL) { if (left == right) { return ExpressionType.PIXEL; } } if (right == ExpressionType.PERCENTAGE) { if (left == right) { return ExpressionType.PERCENTAGE; } } } return ExpressionType.UNDEFINED; } }
True
False
1,407
2,655
151816_1
/* * 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 annotatieviewer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * de hoofdclass met opslag en verwerking van gegevens * @author emilvanamerongen, (Tjeerd van der Veen) */ public class Data_opslag_en_verwerking { /** * hoofdopslag van de huidige DNA sequentie */ public static String sequence = "empty"; /** * opslag van substrings van de huidige DNA sequentie */ public static HashMap<Integer, String> substrings = new HashMap<>(); /** * opslag van de forward substrings van de huidige aminozuur sequentie */ public static HashMap<Integer, String> aminosubstrings = new HashMap<>(); /** * opslag van de reverse substrings van de huidige aminozuur sequentie */ public static HashMap<Integer, String> aminosubstringsreverse = new HashMap<>(); /** * opslag van annotatie in een arraylist met gene objecten (gekozen voor arraylist omdat hashmaps bugs veroorzaakte) */ public static List<Gene> genes = new ArrayList<Gene>(); /** * hoofdopslag van de huidige aminozuur sequentie */ public static String AminoSequence; /** * oplag van de reverse aminozuur sequentie */ public static String AminoSequencereverse; /** * keuze tussen DNA sequentie weergave of aminozuursequentie weergave, opgeslagen als boolean */ public static Boolean dnaorprotein = false; /** * * initiates the project * @param args the command line arguments */ public static void main(String[] args) { init(); } /** * initiates the GUI */ public static void init(){ new Annotation_viewer_GUI().setVisible(true); } /** * sla een nieuwe sequentie op en verwerk deze naar verschillende type opslag objecten * @param newsequence die nieuwe DNA sequentie */ public static void setsequence(String newsequence){ // filter alle nextline en spaties uit de DNA sequentie sequence = newsequence.replace("\n", "").replace(" ", "").replace("\r",""); // maak substrings van de DNA sequentie substrings = Sequencetools.createsubstrings(sequence); // vertaal de sequentie naar aminozuren AminoSequence = Sequencetools.TranslateSequence(sequence); // vertaal de complementaire sequentie naar aminozuren AminoSequencereverse = Sequencetools.TranslateSequence(Sequencetools.complement(sequence)); // maak substrings van de aminozuursequentie aminosubstrings = Sequencetools.createsubstrings(AminoSequence); // maak substrings van de complementaire aminozuursequentie aminosubstringsreverse = Sequencetools.createsubstrings(AminoSequencereverse); // visualiseer de nieuwe data Annotation_viewer_GUI.visualise(); } /** * sla nieuwe annotatie gene objecten op in de Arraylist met genen * @param newgenes nieuwe list met genen die opgeslagen moeten worden */ public static void setgenes(List<Gene> newgenes){ genes.addAll(newgenes); // visualiseer de nieuwe data Annotation_viewer_GUI.visualise(); } }
emilvanamerongen/annotatieviewer
src/annotatieviewer/Data_opslag_en_verwerking.java
1,003
/** * de hoofdclass met opslag en verwerking van gegevens * @author emilvanamerongen, (Tjeerd van der Veen) */
block_comment
nl
/* * 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 annotatieviewer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * de hoofdclass met<SUF>*/ public class Data_opslag_en_verwerking { /** * hoofdopslag van de huidige DNA sequentie */ public static String sequence = "empty"; /** * opslag van substrings van de huidige DNA sequentie */ public static HashMap<Integer, String> substrings = new HashMap<>(); /** * opslag van de forward substrings van de huidige aminozuur sequentie */ public static HashMap<Integer, String> aminosubstrings = new HashMap<>(); /** * opslag van de reverse substrings van de huidige aminozuur sequentie */ public static HashMap<Integer, String> aminosubstringsreverse = new HashMap<>(); /** * opslag van annotatie in een arraylist met gene objecten (gekozen voor arraylist omdat hashmaps bugs veroorzaakte) */ public static List<Gene> genes = new ArrayList<Gene>(); /** * hoofdopslag van de huidige aminozuur sequentie */ public static String AminoSequence; /** * oplag van de reverse aminozuur sequentie */ public static String AminoSequencereverse; /** * keuze tussen DNA sequentie weergave of aminozuursequentie weergave, opgeslagen als boolean */ public static Boolean dnaorprotein = false; /** * * initiates the project * @param args the command line arguments */ public static void main(String[] args) { init(); } /** * initiates the GUI */ public static void init(){ new Annotation_viewer_GUI().setVisible(true); } /** * sla een nieuwe sequentie op en verwerk deze naar verschillende type opslag objecten * @param newsequence die nieuwe DNA sequentie */ public static void setsequence(String newsequence){ // filter alle nextline en spaties uit de DNA sequentie sequence = newsequence.replace("\n", "").replace(" ", "").replace("\r",""); // maak substrings van de DNA sequentie substrings = Sequencetools.createsubstrings(sequence); // vertaal de sequentie naar aminozuren AminoSequence = Sequencetools.TranslateSequence(sequence); // vertaal de complementaire sequentie naar aminozuren AminoSequencereverse = Sequencetools.TranslateSequence(Sequencetools.complement(sequence)); // maak substrings van de aminozuursequentie aminosubstrings = Sequencetools.createsubstrings(AminoSequence); // maak substrings van de complementaire aminozuursequentie aminosubstringsreverse = Sequencetools.createsubstrings(AminoSequencereverse); // visualiseer de nieuwe data Annotation_viewer_GUI.visualise(); } /** * sla nieuwe annotatie gene objecten op in de Arraylist met genen * @param newgenes nieuwe list met genen die opgeslagen moeten worden */ public static void setgenes(List<Gene> newgenes){ genes.addAll(newgenes); // visualiseer de nieuwe data Annotation_viewer_GUI.visualise(); } }
True
False
1,408
739
6351_25
package org.ivdnt.fcs.results; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * This class is used to store FCS keywords in context (kwic) as part of the * ResultSet (which is part of a FcsSearchResultSet = main result object) * * @author jesse * */ public class Kwic { // A Kwic (keyword in context) is a list of words in which a match was found // so it consists of [a left context], [a match], and [a right context] // // The tokens of those 3 parts are stored together in lists, each of which // represents one property. // So, for a given token at position X, we can retrieve the value of a given // property // by accessing the corresponding list at the same position X // // (t.i. we have one sorted list for each single property, so there are as many // lists // as properties) // // To be able to recognize each part, the Kwic object has // hitStart and hitEnd, which indicate the borders of the [match part] // = start and end position of a keyword, within its context private int hitStart; private int hitEnd; // default property private String defaultProperty = "word"; // the list contains the names of all the properties contained in our Kwic // object private List<String> tokenPropertyNames = new ArrayList<>(); // this maps a property name to a sorted list of token properties // (sorted, as the list represents the tokens on the result string) private Map<String, List<String>> tokenProperties = new ConcurrentHashMap<>(); // metadata private Map<String, String> metadata = new ConcurrentHashMap<>(); // considering the size of opensonar metadata, // probably better to introduce separate // document objects // private Document document = null; // ----------------------------------------------------------------------------------- // add a new property name to all tokens public void addTokenProperty(String propertyName) { // register the property name // and // add the property to all tokens if (!this.tokenPropertyNames.contains(propertyName)) { this.addTokenPropertyName(propertyName); List<String> propertyValues = new ArrayList<>(this.size()); for (int i = 0; i < this.size(); i++) { propertyValues.add(null); } this.setTokenProperties(propertyName, propertyValues); } } // ----------------------------------------------------------------------------------- // getters public void addTokenPropertyName(String pname) { this.tokenPropertyNames.add(pname); } public void addTokenPropertyNames(Set<String> pnames) { this.tokenPropertyNames.addAll(pnames); } public String get(String pname, int i) { return getLayer(pname).get(i); } public String getDefaultProperty() { return this.defaultProperty; } public int getHitEnd() { return this.hitEnd; } public int getHitStart() { return this.hitStart; } public List<String> getLayer(String propertyName) { return this.tokenProperties.get(propertyName); } public URI getLayerURL(String pname) { try { return new URI("http://www.ivdnt.org/annotation-layers/" + pname); } catch (Exception e) { throw new NullPointerException("Unable to get layer URL for " + pname + ". " + e); } } public Map<String, String> getMetadata() { return this.metadata; } // synonym of getLayer public List<String> getPropertyValues(String propertyName) { return getLayer(propertyName); } public List<String> getTokenPropertyNames() { return this.tokenPropertyNames; } public String getWord(int i) { return this.tokenProperties.get(defaultProperty).get(i); } // ----------------------------------------------------------------------------------- // setters public void setHitEnd(int hitEnd) { this.hitEnd = hitEnd; } public void setHitStart(int hitStart) { this.hitStart = hitStart; } public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } // set one property for all tokens at once // eg. the pos-tag of all tokens of a sentence public void setTokenProperties(String pname, List<String> properties) { this.tokenProperties.put(pname, properties); } // modify the value of a property for token at position X public void setTokenPropertyAt(String propertyName, String property, int index) { List<String> propertyValues = this.getLayer(propertyName); if (propertyValues.size() == 0) propertyValues = new ArrayList<>(this.getTokenPropertyNames().size()); propertyValues.set(index, property); this.setTokenProperties(propertyName, propertyValues); } public int size() { return words().size(); } public String toString() { List<String> tokens = new ArrayList<String>(); List<String> words = words(); for (int i = 0; i < words.size(); i++) { String p = (this.hitStart <= i && i <= this.hitEnd) ? ">>" : ""; tokens.add(p + words.get(i)); } String s = String.format("Kwic(%d,%d):", this.hitStart, this.hitEnd); return s + tokens.toString(); } public Kwic translatePrefixes(Map<String, String> map) { map.forEach((k, v) -> { this.tokenProperties.put(v, this.tokenProperties.get(k)); this.tokenProperties.remove(k); }); this.tokenPropertyNames = this.tokenPropertyNames.stream().map(p -> map.containsKey(p) ? map.get(p) : p) .collect(Collectors.toList()); return this; } // ----------------------------------------------------------------------------------- public List<String> words() { return this.tokenProperties.get(defaultProperty); } // ----------------------------------------------------------------------------------- } /** * Wat gaan we met metadata doen? In een CMDI profiel stoppen? Hoe halen we dat * op bij nederlab? Voor blacklab server zelf maken uit de aanwezige metadata. * https://www.clarin.eu/sites/default/files/CE-2014-0317-CLARIN_FCS_Specification_DataViews_1_0.pdf: * * <!-- potential @pid and @ref attributes omitted --> * <fcs:DataView type="application/x-cmdi+xml"> * <cmdi:CMD xmlns:cmdi="http://www.clarin.eu/cmd/" CMDVersion="1.1"> <!-- * content omitted --> </cmdi:CMD> </fcs:DataView> <!-- potential @pid attribute * omitted --> <fcs:DataView type="application/x-cmdi+xml" ref= * "http://repos.example.org/resources/4711/0815.cmdi" /> */
INL/clariah-fcs-endpoints
src/main/java/org/ivdnt/fcs/results/Kwic.java
1,899
/** * Wat gaan we met metadata doen? In een CMDI profiel stoppen? Hoe halen we dat * op bij nederlab? Voor blacklab server zelf maken uit de aanwezige metadata. * https://www.clarin.eu/sites/default/files/CE-2014-0317-CLARIN_FCS_Specification_DataViews_1_0.pdf: * * <!-- potential @pid and @ref attributes omitted --> * <fcs:DataView type="application/x-cmdi+xml"> * <cmdi:CMD xmlns:cmdi="http://www.clarin.eu/cmd/" CMDVersion="1.1"> <!-- * content omitted --> </cmdi:CMD> </fcs:DataView> <!-- potential @pid attribute * omitted --> <fcs:DataView type="application/x-cmdi+xml" ref= * "http://repos.example.org/resources/4711/0815.cmdi" /> */
block_comment
nl
package org.ivdnt.fcs.results; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * This class is used to store FCS keywords in context (kwic) as part of the * ResultSet (which is part of a FcsSearchResultSet = main result object) * * @author jesse * */ public class Kwic { // A Kwic (keyword in context) is a list of words in which a match was found // so it consists of [a left context], [a match], and [a right context] // // The tokens of those 3 parts are stored together in lists, each of which // represents one property. // So, for a given token at position X, we can retrieve the value of a given // property // by accessing the corresponding list at the same position X // // (t.i. we have one sorted list for each single property, so there are as many // lists // as properties) // // To be able to recognize each part, the Kwic object has // hitStart and hitEnd, which indicate the borders of the [match part] // = start and end position of a keyword, within its context private int hitStart; private int hitEnd; // default property private String defaultProperty = "word"; // the list contains the names of all the properties contained in our Kwic // object private List<String> tokenPropertyNames = new ArrayList<>(); // this maps a property name to a sorted list of token properties // (sorted, as the list represents the tokens on the result string) private Map<String, List<String>> tokenProperties = new ConcurrentHashMap<>(); // metadata private Map<String, String> metadata = new ConcurrentHashMap<>(); // considering the size of opensonar metadata, // probably better to introduce separate // document objects // private Document document = null; // ----------------------------------------------------------------------------------- // add a new property name to all tokens public void addTokenProperty(String propertyName) { // register the property name // and // add the property to all tokens if (!this.tokenPropertyNames.contains(propertyName)) { this.addTokenPropertyName(propertyName); List<String> propertyValues = new ArrayList<>(this.size()); for (int i = 0; i < this.size(); i++) { propertyValues.add(null); } this.setTokenProperties(propertyName, propertyValues); } } // ----------------------------------------------------------------------------------- // getters public void addTokenPropertyName(String pname) { this.tokenPropertyNames.add(pname); } public void addTokenPropertyNames(Set<String> pnames) { this.tokenPropertyNames.addAll(pnames); } public String get(String pname, int i) { return getLayer(pname).get(i); } public String getDefaultProperty() { return this.defaultProperty; } public int getHitEnd() { return this.hitEnd; } public int getHitStart() { return this.hitStart; } public List<String> getLayer(String propertyName) { return this.tokenProperties.get(propertyName); } public URI getLayerURL(String pname) { try { return new URI("http://www.ivdnt.org/annotation-layers/" + pname); } catch (Exception e) { throw new NullPointerException("Unable to get layer URL for " + pname + ". " + e); } } public Map<String, String> getMetadata() { return this.metadata; } // synonym of getLayer public List<String> getPropertyValues(String propertyName) { return getLayer(propertyName); } public List<String> getTokenPropertyNames() { return this.tokenPropertyNames; } public String getWord(int i) { return this.tokenProperties.get(defaultProperty).get(i); } // ----------------------------------------------------------------------------------- // setters public void setHitEnd(int hitEnd) { this.hitEnd = hitEnd; } public void setHitStart(int hitStart) { this.hitStart = hitStart; } public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } // set one property for all tokens at once // eg. the pos-tag of all tokens of a sentence public void setTokenProperties(String pname, List<String> properties) { this.tokenProperties.put(pname, properties); } // modify the value of a property for token at position X public void setTokenPropertyAt(String propertyName, String property, int index) { List<String> propertyValues = this.getLayer(propertyName); if (propertyValues.size() == 0) propertyValues = new ArrayList<>(this.getTokenPropertyNames().size()); propertyValues.set(index, property); this.setTokenProperties(propertyName, propertyValues); } public int size() { return words().size(); } public String toString() { List<String> tokens = new ArrayList<String>(); List<String> words = words(); for (int i = 0; i < words.size(); i++) { String p = (this.hitStart <= i && i <= this.hitEnd) ? ">>" : ""; tokens.add(p + words.get(i)); } String s = String.format("Kwic(%d,%d):", this.hitStart, this.hitEnd); return s + tokens.toString(); } public Kwic translatePrefixes(Map<String, String> map) { map.forEach((k, v) -> { this.tokenProperties.put(v, this.tokenProperties.get(k)); this.tokenProperties.remove(k); }); this.tokenPropertyNames = this.tokenPropertyNames.stream().map(p -> map.containsKey(p) ? map.get(p) : p) .collect(Collectors.toList()); return this; } // ----------------------------------------------------------------------------------- public List<String> words() { return this.tokenProperties.get(defaultProperty); } // ----------------------------------------------------------------------------------- } /** * Wat gaan we<SUF>*/
True
False
1,410
4,698
69092_4
import data.AdresDAOHibernate; import data.OVChipkaartDAOHibernate; import data.ProductDAOHibernate; import data.ReizigerDAOHibernate; import data.interfaces.AdresDAO; import data.interfaces.OVChipkaartDAO; import data.interfaces.ProductDAO; import data.interfaces.ReizigerDAO; import domain.Adres; import domain.OVChipkaart; import domain.Product; import domain.Reiziger; import jakarta.persistence.metamodel.EntityType; import jakarta.persistence.metamodel.Metamodel; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import java.sql.Date; import java.sql.SQLException; import java.util.List; /** * Testklasse - deze klasse test alle andere klassen in deze package. * * System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions). * * @author [email protected] */ public class Main { // Creëer een factory voor Hibernate sessions. private static final SessionFactory factory; static { try { // Create a Hibernate session factory factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } /** * Retouneer een Hibernate session. * * @return Hibernate session * @throws HibernateException */ private static Session getSession() throws HibernateException { return factory.openSession(); } public static void main(String[] args) throws SQLException { //testFetchAll(); testDAO(); } /** * P6. Haal alle (geannoteerde) entiteiten uit de database. */ private static void testFetchAll() { Session session = getSession(); try { Metamodel metamodel = session.getSessionFactory().getMetamodel(); for (EntityType<?> entityType : metamodel.getEntities()) { Query query = session.createQuery("from " + entityType.getName()); System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:"); for (Object o : query.list()) { System.out.println(" " + o); } System.out.println(); } } finally { session.close(); } } private static void testDAO() { Session session = getSession(); Transaction transaction = session.getTransaction(); try { // make DAO OVChipkaartDAO ovChipkaartDAO = new OVChipkaartDAOHibernate(session); AdresDAO adresDAO = new AdresDAOHibernate(session); ReizigerDAO reizigerDAO = new ReizigerDAOHibernate(session); ProductDAO productDAO = new ProductDAOHibernate(session); // test DAO testReizigerDAO(reizigerDAO); testAdresDAO(adresDAO, reizigerDAO); testOVChipDAO(ovChipkaartDAO, reizigerDAO); testProductDAO(productDAO, reizigerDAO); } catch (Exception e){ e.printStackTrace(); System.out.println("ROLLBACK!!!"); transaction.rollback(); } finally { session.close(); } } private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testReizigerDAO----------"); Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17")); List<Reiziger> reizigers= rdao.findAll(); System.out.println("findAll gives:"); for (Reiziger r : reizigers) { System.out.println(r); } System.out.println("\nfindByGbdatum gives:"); for (Reiziger r : rdao.findByGbdatum("2002-12-03")) { System.out.println(r); } // test save System.out.println("\nsave before: " + reizigers.size()); rdao.save(reiziger); reizigers = rdao.findAll(); System.out.println("after: " + reizigers.size()); System.out.println("\nupdate before: " + rdao.findById(100)); reiziger.setVoorletters("jag"); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + reizigers.size()); rdao.delete(reiziger); reizigers = rdao.findAll(); System.out.println("after: " + reizigers.size()); } private static void testAdresDAO(AdresDAO adao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testAdresDAO----------"); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17"), adres); adres.setReiziger(reiziger); List<Adres> adresList = adao.findAll(); System.out.println("\nfindAll gives:"); for (Adres a : adresList) { System.out.println(a); } // test save System.out.println("\nsave before: " + adresList.size()); rdao.save(reiziger); adresList = adao.findAll(); System.out.println("after: " + adresList.size()); System.out.println("\nfindById gives: " + adao.findById(reiziger.getId())); System.out.println("\nfindByReiziger gives: " + adao.findByReiziger(reiziger)); // test update System.out.println("\nupdate before: " + rdao.findById(100)); adres.setHuisnummer("3B"); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + adresList.size()); rdao.delete(reiziger); adresList = adao.findAll(); System.out.println("delete after: " + adresList.size()); } private static void testOVChipDAO(OVChipkaartDAO odao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testOVChipkaartDAO----------"); OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100); OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres); adres.setReiziger(reiziger); ovChipkaart.setReiziger(reiziger); reiziger.addOVChipkaart(ovChipkaart); List<OVChipkaart> kaartList = odao.findAll(); System.out.println("\nfindAll gives:"); for (OVChipkaart o : kaartList) { System.out.println(o); } // test save System.out.println("\nsave before: " + kaartList.size()); rdao.save(reiziger); kaartList = odao.findAll(); System.out.println("after: " + kaartList.size()); System.out.println("\nfindById gives: " + odao.findById(reiziger.getId())); System.out.println("\nfindByReiziger gives: " + odao.findByReiziger(reiziger)); // test update System.out.println("\nupdate before: " + rdao.findById(100)); ovChipkaart.setSaldo(69); reiziger.addOVChipkaart(ovChipkaart2); ovChipkaart2.setReiziger(reiziger); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + kaartList.size()); rdao.delete(reiziger); kaartList = odao.findAll(); System.out.println("delete after: " + kaartList.size()); } private static void testProductDAO(ProductDAO pdao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testProductDAO----------"); OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100); OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres); Product product = new Product(100,"test","test",100); adres.setReiziger(reiziger); ovChipkaart.setReiziger(reiziger); ovChipkaart2.setReiziger(reiziger); product.addOvChip(ovChipkaart); rdao.save(reiziger); List<Product> productList = pdao.findAll(); System.out.println("\nfindAll gives:"); for (Product p : productList) { System.out.println(p); } // test save System.out.println("\nsave before: " + productList.size()); pdao.save(product); productList = pdao.findAll(); System.out.println("after: " + productList.size()); System.out.println("\nfindById gives: " + pdao.findById(product.getProductNummer())); System.out.println("\nfindByOVChipkaart gives: " + pdao.findByOvChipkaart(ovChipkaart)); // test update System.out.println("\nupdate before: " + pdao.findById(product.getProductNummer())); product.addOvChip(ovChipkaart2); product.setBeschrijving("tset"); pdao.update(product); System.out.println("update after: " + pdao.findById(product.getProductNummer())); // test delete System.out.println("\ndelete before: " + productList.size()); pdao.delete(product); productList = pdao.findAll(); System.out.println("delete after: " + productList.size()); rdao.delete(reiziger); } }
wiemanboy/DataPersistency-Hibernate
src/main/java/Main.java
3,208
/** * P6. Haal alle (geannoteerde) entiteiten uit de database. */
block_comment
nl
import data.AdresDAOHibernate; import data.OVChipkaartDAOHibernate; import data.ProductDAOHibernate; import data.ReizigerDAOHibernate; import data.interfaces.AdresDAO; import data.interfaces.OVChipkaartDAO; import data.interfaces.ProductDAO; import data.interfaces.ReizigerDAO; import domain.Adres; import domain.OVChipkaart; import domain.Product; import domain.Reiziger; import jakarta.persistence.metamodel.EntityType; import jakarta.persistence.metamodel.Metamodel; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import java.sql.Date; import java.sql.SQLException; import java.util.List; /** * Testklasse - deze klasse test alle andere klassen in deze package. * * System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions). * * @author [email protected] */ public class Main { // Creëer een factory voor Hibernate sessions. private static final SessionFactory factory; static { try { // Create a Hibernate session factory factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } /** * Retouneer een Hibernate session. * * @return Hibernate session * @throws HibernateException */ private static Session getSession() throws HibernateException { return factory.openSession(); } public static void main(String[] args) throws SQLException { //testFetchAll(); testDAO(); } /** * P6. Haal alle<SUF>*/ private static void testFetchAll() { Session session = getSession(); try { Metamodel metamodel = session.getSessionFactory().getMetamodel(); for (EntityType<?> entityType : metamodel.getEntities()) { Query query = session.createQuery("from " + entityType.getName()); System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:"); for (Object o : query.list()) { System.out.println(" " + o); } System.out.println(); } } finally { session.close(); } } private static void testDAO() { Session session = getSession(); Transaction transaction = session.getTransaction(); try { // make DAO OVChipkaartDAO ovChipkaartDAO = new OVChipkaartDAOHibernate(session); AdresDAO adresDAO = new AdresDAOHibernate(session); ReizigerDAO reizigerDAO = new ReizigerDAOHibernate(session); ProductDAO productDAO = new ProductDAOHibernate(session); // test DAO testReizigerDAO(reizigerDAO); testAdresDAO(adresDAO, reizigerDAO); testOVChipDAO(ovChipkaartDAO, reizigerDAO); testProductDAO(productDAO, reizigerDAO); } catch (Exception e){ e.printStackTrace(); System.out.println("ROLLBACK!!!"); transaction.rollback(); } finally { session.close(); } } private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testReizigerDAO----------"); Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17")); List<Reiziger> reizigers= rdao.findAll(); System.out.println("findAll gives:"); for (Reiziger r : reizigers) { System.out.println(r); } System.out.println("\nfindByGbdatum gives:"); for (Reiziger r : rdao.findByGbdatum("2002-12-03")) { System.out.println(r); } // test save System.out.println("\nsave before: " + reizigers.size()); rdao.save(reiziger); reizigers = rdao.findAll(); System.out.println("after: " + reizigers.size()); System.out.println("\nupdate before: " + rdao.findById(100)); reiziger.setVoorletters("jag"); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + reizigers.size()); rdao.delete(reiziger); reizigers = rdao.findAll(); System.out.println("after: " + reizigers.size()); } private static void testAdresDAO(AdresDAO adao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testAdresDAO----------"); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17"), adres); adres.setReiziger(reiziger); List<Adres> adresList = adao.findAll(); System.out.println("\nfindAll gives:"); for (Adres a : adresList) { System.out.println(a); } // test save System.out.println("\nsave before: " + adresList.size()); rdao.save(reiziger); adresList = adao.findAll(); System.out.println("after: " + adresList.size()); System.out.println("\nfindById gives: " + adao.findById(reiziger.getId())); System.out.println("\nfindByReiziger gives: " + adao.findByReiziger(reiziger)); // test update System.out.println("\nupdate before: " + rdao.findById(100)); adres.setHuisnummer("3B"); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + adresList.size()); rdao.delete(reiziger); adresList = adao.findAll(); System.out.println("delete after: " + adresList.size()); } private static void testOVChipDAO(OVChipkaartDAO odao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testOVChipkaartDAO----------"); OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100); OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres); adres.setReiziger(reiziger); ovChipkaart.setReiziger(reiziger); reiziger.addOVChipkaart(ovChipkaart); List<OVChipkaart> kaartList = odao.findAll(); System.out.println("\nfindAll gives:"); for (OVChipkaart o : kaartList) { System.out.println(o); } // test save System.out.println("\nsave before: " + kaartList.size()); rdao.save(reiziger); kaartList = odao.findAll(); System.out.println("after: " + kaartList.size()); System.out.println("\nfindById gives: " + odao.findById(reiziger.getId())); System.out.println("\nfindByReiziger gives: " + odao.findByReiziger(reiziger)); // test update System.out.println("\nupdate before: " + rdao.findById(100)); ovChipkaart.setSaldo(69); reiziger.addOVChipkaart(ovChipkaart2); ovChipkaart2.setReiziger(reiziger); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + kaartList.size()); rdao.delete(reiziger); kaartList = odao.findAll(); System.out.println("delete after: " + kaartList.size()); } private static void testProductDAO(ProductDAO pdao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testProductDAO----------"); OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100); OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres); Product product = new Product(100,"test","test",100); adres.setReiziger(reiziger); ovChipkaart.setReiziger(reiziger); ovChipkaart2.setReiziger(reiziger); product.addOvChip(ovChipkaart); rdao.save(reiziger); List<Product> productList = pdao.findAll(); System.out.println("\nfindAll gives:"); for (Product p : productList) { System.out.println(p); } // test save System.out.println("\nsave before: " + productList.size()); pdao.save(product); productList = pdao.findAll(); System.out.println("after: " + productList.size()); System.out.println("\nfindById gives: " + pdao.findById(product.getProductNummer())); System.out.println("\nfindByOVChipkaart gives: " + pdao.findByOvChipkaart(ovChipkaart)); // test update System.out.println("\nupdate before: " + pdao.findById(product.getProductNummer())); product.addOvChip(ovChipkaart2); product.setBeschrijving("tset"); pdao.update(product); System.out.println("update after: " + pdao.findById(product.getProductNummer())); // test delete System.out.println("\ndelete before: " + productList.size()); pdao.delete(product); productList = pdao.findAll(); System.out.println("delete after: " + productList.size()); rdao.delete(reiziger); } }
True
False
1,412
3,240
52711_8
/* Copyright 2013 Nationale-Nederlanden, 2020, 2022 WeAreFrank! 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 nl.nn.adapterframework.jms; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.NamingException; import org.apache.commons.lang3.StringUtils; import nl.nn.adapterframework.core.HasSender; import nl.nn.adapterframework.core.ICorrelatedPullingListener; import nl.nn.adapterframework.core.IListenerConnector; import nl.nn.adapterframework.core.IPostboxListener; import nl.nn.adapterframework.core.IPullingListener; import nl.nn.adapterframework.core.ISender; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.core.PipeLine.ExitState; import nl.nn.adapterframework.core.PipeLineResult; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.core.TimeoutException; import nl.nn.adapterframework.util.RunState; import nl.nn.adapterframework.util.RunStateEnquirer; import nl.nn.adapterframework.util.RunStateEnquiring; /** * A true multi-threaded {@link IPullingListener Listener}-class. * <br/> * * Since version 4.1, Ibis supports distributed transactions using the XA-protocol. This feature is controlled by the * {@link #setTransacted(boolean) transacted} attribute. If this is set to <code>true</code>, received messages are * committed or rolled back, possibly together with other actions, by the receiver or the pipeline. * In case of a failure, all actions within the transaction are rolled back. * * <p><b>Using jmsTransacted and acknowledgement</b><br/> * If jmsTransacted is set <code>true</code>: it should ensure that a message is received and processed on a both or nothing basis. * IBIS will commit the the message, otherwise perform rollback. However using jmsTransacted, IBIS does not bring transactions within * the adapters under transaction control, compromising the idea of atomic transactions. In the roll-back situation messages sent to * other destinations within the Pipeline are NOT rolled back if jmsTransacted is set <code>true</code>! In the failure situation the * message is therefore completely processed, and the roll back does not mean that the processing is rolled back! To obtain the correct * (transactional) behaviour, {@link #setTransacted(boolean) transacted} should be used instead of {@link #setJmsTransacted(boolean) * listener.transacted}. *<p> * Setting {@link #setAcknowledgeMode(String) listener.acknowledgeMode} to "auto" means that messages are allways acknowledged (removed from * the queue, regardless of what the status of the Adapter is. "client" means that the message will only be removed from the queue * when the state of the Adapter equals the success state. * The "dups" mode instructs the session to lazily acknowledge the delivery of the messages. This is likely to result in the * delivery of duplicate messages if JMS fails. It should be used by consumers who are tolerant in processing duplicate messages. * In cases where the client is tolerant of duplicate messages, some enhancement in performance can be achieved using this mode, * since a session has lower overhead in trying to prevent duplicate messages. * </p> * <p>The setting for {@link #setAcknowledgeMode(String) listener.acknowledgeMode} will only be processed if * the setting for {@link #setTransacted(boolean) listener.transacted} as well as for * {@link #setJmsTransacted(boolean) listener.jmsTransacted} is false.</p> * * <p>If {@link #setUseReplyTo(boolean) useReplyTo} is set and a replyTo-destination is * specified in the message, the JmsListener sends the result of the processing * in the pipeline to this destination. Otherwise the result is sent using the (optionally) * specified {@link #setSender(ISender) Sender}, that in turn sends the message to * whatever it is configured to.</p> * </p> * <p><b>Notice:</b> the JmsListener is ONLY capable of processing * <code>javax.jms.TextMessage</code>s <br/><br/> * </p> * @author Gerrit van Brakel * @since 4.0.1 */ public class PullingJmsListener extends JmsListenerBase implements IPostboxListener<javax.jms.Message>, ICorrelatedPullingListener<javax.jms.Message>, HasSender, RunStateEnquiring { private static final String THREAD_CONTEXT_MESSAGECONSUMER_KEY="messageConsumer"; private RunStateEnquirer runStateEnquirer=null; public PullingJmsListener() { setTimeout(20000); } protected Session getSession(Map<String,Object> threadContext) throws ListenerException { if (isSessionsArePooled()) { try { return createSession(); } catch (JmsException e) { throw new ListenerException("exception creating QueueSession", e); } } return (Session) threadContext.get(IListenerConnector.THREAD_CONTEXT_SESSION_KEY); } protected void releaseSession(Session session) throws ListenerException { if (isSessionsArePooled()) { closeSession(session); } } protected MessageConsumer getReceiver(Map<String,Object> threadContext, Session session, String correlationId) throws ListenerException { try { if (StringUtils.isNotEmpty(correlationId)) { return getMessageConsumerForCorrelationId(session, getDestination(), correlationId); } if (isSessionsArePooled()) { return getMessageConsumer(session, getDestination()); } return (MessageConsumer) threadContext.get(THREAD_CONTEXT_MESSAGECONSUMER_KEY); } catch (Exception e) { throw new ListenerException(getLogPrefix()+"exception creating QueueReceiver for "+getPhysicalDestinationName(), e); } } protected void releaseReceiver(MessageConsumer receiver, String correlationId) throws ListenerException { if ((isSessionsArePooled() || StringUtils.isNotEmpty(correlationId)) && receiver != null) { try { receiver.close(); // do not write to log, this occurs too often } catch (Exception e) { throw new ListenerException(getLogPrefix()+"exception closing QueueReceiver", e); } } } @Override public Map<String,Object> openThread() throws ListenerException { Map<String,Object> threadContext = new HashMap<String,Object>(); try { if (!isSessionsArePooled()) { Session session = createSession(); threadContext.put(IListenerConnector.THREAD_CONTEXT_SESSION_KEY, session); MessageConsumer mc = getMessageConsumer(session, getDestination()); threadContext.put(THREAD_CONTEXT_MESSAGECONSUMER_KEY, mc); } return threadContext; } catch (Exception e) { throw new ListenerException("exception in ["+getName()+"]", e); } } @Override public void closeThread(Map<String,Object> threadContext) throws ListenerException { try { if (!isSessionsArePooled()) { MessageConsumer mc = (MessageConsumer) threadContext.remove(THREAD_CONTEXT_MESSAGECONSUMER_KEY); releaseReceiver(mc,null); Session session = (Session) threadContext.remove(IListenerConnector.THREAD_CONTEXT_SESSION_KEY); closeSession(session); } } catch (Exception e) { throw new ListenerException("exception in [" + getName() + "]", e); } } @Override public void afterMessageProcessed(PipeLineResult plr, Object rawMessageOrWrapper, Map<String, Object> threadContext) throws ListenerException { super.afterMessageProcessed(plr, rawMessageOrWrapper, threadContext); try { // TODO Do we still need this? Should we rollback too? See // PushingJmsListener.afterMessageProcessed() too (which does a // rollback, but no commit). if (!isTransacted()) { if (isJmsTransacted()) { // the following if transacted using transacted sessions, instead of XA-enabled sessions. Session session = (Session)threadContext.get(IListenerConnector.THREAD_CONTEXT_SESSION_KEY); if (session == null) { log.warn("Listener ["+getName()+"] message ["+ (String)threadContext.get(PipeLineSession.messageIdKey) +"] has no session to commit or rollback"); } else { if (plr.getState()==ExitState.SUCCESS) { session.commit(); } else { log.warn("Listener ["+getName()+"] message ["+ (String)threadContext.get(PipeLineSession.messageIdKey) +"] not committed nor rolled back either"); //TODO: enable rollback, or remove support for JmsTransacted altogether (XA-transactions should do it all) // session.rollback(); } if (isSessionsArePooled()) { threadContext.remove(IListenerConnector.THREAD_CONTEXT_SESSION_KEY); releaseSession(session); } } } else { // TODO: dit weghalen. Het hoort hier niet, en zit ook al in getIdFromRawMessage. Daar hoort het ook niet, overigens... if (getAcknowledgeModeEnum() == AcknowledgeMode.CLIENT_ACKNOWLEDGE) { log.debug("["+getName()+"] acknowledges message with id ["+threadContext.get(PipeLineSession.messageIdKey)+"]"); ((TextMessage)rawMessageOrWrapper).acknowledge(); } } } } catch (JMSException e) { throw new ListenerException(e); } } protected void sendReply(PipeLineResult plr, Destination replyTo, String replyCid, long timeToLive, boolean ignoreInvalidDestinationException, Map<String, Object> threadContext, Map<String, Object> properties) throws SenderException, ListenerException, NamingException, JMSException, IOException { Session session = (Session)threadContext.get(IListenerConnector.THREAD_CONTEXT_SESSION_KEY); if (session==null) { try { session=getSession(threadContext); send(session, replyTo, replyCid, prepareReply(plr.getResult(),threadContext), getReplyMessageType(), timeToLive, getReplyDeliveryMode().getDeliveryMode(), getReplyPriority(), ignoreInvalidDestinationException, properties); } finally { releaseSession(session); } } else { send(session, replyTo, replyCid, plr.getResult(), getReplyMessageType(), timeToLive, getReplyDeliveryMode().getDeliveryMode(), getReplyPriority(), ignoreInvalidDestinationException, properties); } } /** * Retrieves messages from queue or other channel, but does no processing on it. */ @Override public javax.jms.Message getRawMessage(Map<String,Object> threadContext) throws ListenerException { return getRawMessageFromDestination(null, threadContext); } @Override public javax.jms.Message getRawMessage(String correlationId, Map<String,Object> threadContext) throws ListenerException, TimeoutException { javax.jms.Message msg = getRawMessageFromDestination(correlationId, threadContext); if (msg==null) { throw new TimeoutException(getLogPrefix()+" timed out waiting for message with correlationId ["+correlationId+"]"); } if (log.isDebugEnabled()) { log.debug("JmsListener ["+getName()+"] received for correlationId ["+correlationId+"] replymessage ["+msg+"]"); } return msg; } private boolean sessionNeedsToBeSavedForAfterProcessMessage(Object result) { return isJmsTransacted() && !isTransacted() && isSessionsArePooled()&& result != null; } /** * Retrieves messages from queue or other channel under transaction control, but does no processing on it. */ private javax.jms.Message getRawMessageFromDestination(String correlationId, Map<String,Object> threadContext) throws ListenerException { Session session=null; javax.jms.Message msg = null; try { session = getSession(threadContext); MessageConsumer mc=null; try { mc = getReceiver(threadContext,session,correlationId); msg = mc.receive(getTimeOut()); while (msg==null && correlationId==null && canGoOn() && !isTransacted()) { msg = mc.receive(getTimeOut()); } } catch (JMSException e) { throw new ListenerException(getLogPrefix()+"exception retrieving message",e); } finally { releaseReceiver(mc,correlationId); } } finally { if (sessionNeedsToBeSavedForAfterProcessMessage(msg)) { threadContext.put(IListenerConnector.THREAD_CONTEXT_SESSION_KEY, session); } else { releaseSession(session); } } return msg; } /** * @see IPostboxListener#retrieveRawMessage(String, Map) */ @Override public javax.jms.Message retrieveRawMessage(String messageSelector, Map<String,Object> threadContext) throws ListenerException { Session session=null; try { session = getSession(threadContext); MessageConsumer mc=null; try { mc = getMessageConsumer(session, getDestination(), messageSelector); javax.jms.Message result = (getTimeOut()<0) ? mc.receiveNoWait() : mc.receive(getTimeOut()); return result; } finally { if (mc != null) { try { mc.close(); } catch(JMSException e) { log.warn(getLogPrefix()+"exception closing messageConsumer",e); } } } } catch (Exception e) { throw new ListenerException(getLogPrefix()+"exception preparing to retrieve message", e); } finally { releaseSession(session); } } protected boolean canGoOn() { return runStateEnquirer!=null && runStateEnquirer.getRunState()==RunState.STARTED; } @Override public void SetRunStateEnquirer(RunStateEnquirer enquirer) { runStateEnquirer=enquirer; } }
jjansenvr/iaf
core/src/main/java/nl/nn/adapterframework/jms/PullingJmsListener.java
4,051
// TODO: dit weghalen. Het hoort hier niet, en zit ook al in getIdFromRawMessage. Daar hoort het ook niet, overigens...
line_comment
nl
/* Copyright 2013 Nationale-Nederlanden, 2020, 2022 WeAreFrank! 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 nl.nn.adapterframework.jms; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.NamingException; import org.apache.commons.lang3.StringUtils; import nl.nn.adapterframework.core.HasSender; import nl.nn.adapterframework.core.ICorrelatedPullingListener; import nl.nn.adapterframework.core.IListenerConnector; import nl.nn.adapterframework.core.IPostboxListener; import nl.nn.adapterframework.core.IPullingListener; import nl.nn.adapterframework.core.ISender; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.core.PipeLine.ExitState; import nl.nn.adapterframework.core.PipeLineResult; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.core.TimeoutException; import nl.nn.adapterframework.util.RunState; import nl.nn.adapterframework.util.RunStateEnquirer; import nl.nn.adapterframework.util.RunStateEnquiring; /** * A true multi-threaded {@link IPullingListener Listener}-class. * <br/> * * Since version 4.1, Ibis supports distributed transactions using the XA-protocol. This feature is controlled by the * {@link #setTransacted(boolean) transacted} attribute. If this is set to <code>true</code>, received messages are * committed or rolled back, possibly together with other actions, by the receiver or the pipeline. * In case of a failure, all actions within the transaction are rolled back. * * <p><b>Using jmsTransacted and acknowledgement</b><br/> * If jmsTransacted is set <code>true</code>: it should ensure that a message is received and processed on a both or nothing basis. * IBIS will commit the the message, otherwise perform rollback. However using jmsTransacted, IBIS does not bring transactions within * the adapters under transaction control, compromising the idea of atomic transactions. In the roll-back situation messages sent to * other destinations within the Pipeline are NOT rolled back if jmsTransacted is set <code>true</code>! In the failure situation the * message is therefore completely processed, and the roll back does not mean that the processing is rolled back! To obtain the correct * (transactional) behaviour, {@link #setTransacted(boolean) transacted} should be used instead of {@link #setJmsTransacted(boolean) * listener.transacted}. *<p> * Setting {@link #setAcknowledgeMode(String) listener.acknowledgeMode} to "auto" means that messages are allways acknowledged (removed from * the queue, regardless of what the status of the Adapter is. "client" means that the message will only be removed from the queue * when the state of the Adapter equals the success state. * The "dups" mode instructs the session to lazily acknowledge the delivery of the messages. This is likely to result in the * delivery of duplicate messages if JMS fails. It should be used by consumers who are tolerant in processing duplicate messages. * In cases where the client is tolerant of duplicate messages, some enhancement in performance can be achieved using this mode, * since a session has lower overhead in trying to prevent duplicate messages. * </p> * <p>The setting for {@link #setAcknowledgeMode(String) listener.acknowledgeMode} will only be processed if * the setting for {@link #setTransacted(boolean) listener.transacted} as well as for * {@link #setJmsTransacted(boolean) listener.jmsTransacted} is false.</p> * * <p>If {@link #setUseReplyTo(boolean) useReplyTo} is set and a replyTo-destination is * specified in the message, the JmsListener sends the result of the processing * in the pipeline to this destination. Otherwise the result is sent using the (optionally) * specified {@link #setSender(ISender) Sender}, that in turn sends the message to * whatever it is configured to.</p> * </p> * <p><b>Notice:</b> the JmsListener is ONLY capable of processing * <code>javax.jms.TextMessage</code>s <br/><br/> * </p> * @author Gerrit van Brakel * @since 4.0.1 */ public class PullingJmsListener extends JmsListenerBase implements IPostboxListener<javax.jms.Message>, ICorrelatedPullingListener<javax.jms.Message>, HasSender, RunStateEnquiring { private static final String THREAD_CONTEXT_MESSAGECONSUMER_KEY="messageConsumer"; private RunStateEnquirer runStateEnquirer=null; public PullingJmsListener() { setTimeout(20000); } protected Session getSession(Map<String,Object> threadContext) throws ListenerException { if (isSessionsArePooled()) { try { return createSession(); } catch (JmsException e) { throw new ListenerException("exception creating QueueSession", e); } } return (Session) threadContext.get(IListenerConnector.THREAD_CONTEXT_SESSION_KEY); } protected void releaseSession(Session session) throws ListenerException { if (isSessionsArePooled()) { closeSession(session); } } protected MessageConsumer getReceiver(Map<String,Object> threadContext, Session session, String correlationId) throws ListenerException { try { if (StringUtils.isNotEmpty(correlationId)) { return getMessageConsumerForCorrelationId(session, getDestination(), correlationId); } if (isSessionsArePooled()) { return getMessageConsumer(session, getDestination()); } return (MessageConsumer) threadContext.get(THREAD_CONTEXT_MESSAGECONSUMER_KEY); } catch (Exception e) { throw new ListenerException(getLogPrefix()+"exception creating QueueReceiver for "+getPhysicalDestinationName(), e); } } protected void releaseReceiver(MessageConsumer receiver, String correlationId) throws ListenerException { if ((isSessionsArePooled() || StringUtils.isNotEmpty(correlationId)) && receiver != null) { try { receiver.close(); // do not write to log, this occurs too often } catch (Exception e) { throw new ListenerException(getLogPrefix()+"exception closing QueueReceiver", e); } } } @Override public Map<String,Object> openThread() throws ListenerException { Map<String,Object> threadContext = new HashMap<String,Object>(); try { if (!isSessionsArePooled()) { Session session = createSession(); threadContext.put(IListenerConnector.THREAD_CONTEXT_SESSION_KEY, session); MessageConsumer mc = getMessageConsumer(session, getDestination()); threadContext.put(THREAD_CONTEXT_MESSAGECONSUMER_KEY, mc); } return threadContext; } catch (Exception e) { throw new ListenerException("exception in ["+getName()+"]", e); } } @Override public void closeThread(Map<String,Object> threadContext) throws ListenerException { try { if (!isSessionsArePooled()) { MessageConsumer mc = (MessageConsumer) threadContext.remove(THREAD_CONTEXT_MESSAGECONSUMER_KEY); releaseReceiver(mc,null); Session session = (Session) threadContext.remove(IListenerConnector.THREAD_CONTEXT_SESSION_KEY); closeSession(session); } } catch (Exception e) { throw new ListenerException("exception in [" + getName() + "]", e); } } @Override public void afterMessageProcessed(PipeLineResult plr, Object rawMessageOrWrapper, Map<String, Object> threadContext) throws ListenerException { super.afterMessageProcessed(plr, rawMessageOrWrapper, threadContext); try { // TODO Do we still need this? Should we rollback too? See // PushingJmsListener.afterMessageProcessed() too (which does a // rollback, but no commit). if (!isTransacted()) { if (isJmsTransacted()) { // the following if transacted using transacted sessions, instead of XA-enabled sessions. Session session = (Session)threadContext.get(IListenerConnector.THREAD_CONTEXT_SESSION_KEY); if (session == null) { log.warn("Listener ["+getName()+"] message ["+ (String)threadContext.get(PipeLineSession.messageIdKey) +"] has no session to commit or rollback"); } else { if (plr.getState()==ExitState.SUCCESS) { session.commit(); } else { log.warn("Listener ["+getName()+"] message ["+ (String)threadContext.get(PipeLineSession.messageIdKey) +"] not committed nor rolled back either"); //TODO: enable rollback, or remove support for JmsTransacted altogether (XA-transactions should do it all) // session.rollback(); } if (isSessionsArePooled()) { threadContext.remove(IListenerConnector.THREAD_CONTEXT_SESSION_KEY); releaseSession(session); } } } else { // TODO: dit<SUF> if (getAcknowledgeModeEnum() == AcknowledgeMode.CLIENT_ACKNOWLEDGE) { log.debug("["+getName()+"] acknowledges message with id ["+threadContext.get(PipeLineSession.messageIdKey)+"]"); ((TextMessage)rawMessageOrWrapper).acknowledge(); } } } } catch (JMSException e) { throw new ListenerException(e); } } protected void sendReply(PipeLineResult plr, Destination replyTo, String replyCid, long timeToLive, boolean ignoreInvalidDestinationException, Map<String, Object> threadContext, Map<String, Object> properties) throws SenderException, ListenerException, NamingException, JMSException, IOException { Session session = (Session)threadContext.get(IListenerConnector.THREAD_CONTEXT_SESSION_KEY); if (session==null) { try { session=getSession(threadContext); send(session, replyTo, replyCid, prepareReply(plr.getResult(),threadContext), getReplyMessageType(), timeToLive, getReplyDeliveryMode().getDeliveryMode(), getReplyPriority(), ignoreInvalidDestinationException, properties); } finally { releaseSession(session); } } else { send(session, replyTo, replyCid, plr.getResult(), getReplyMessageType(), timeToLive, getReplyDeliveryMode().getDeliveryMode(), getReplyPriority(), ignoreInvalidDestinationException, properties); } } /** * Retrieves messages from queue or other channel, but does no processing on it. */ @Override public javax.jms.Message getRawMessage(Map<String,Object> threadContext) throws ListenerException { return getRawMessageFromDestination(null, threadContext); } @Override public javax.jms.Message getRawMessage(String correlationId, Map<String,Object> threadContext) throws ListenerException, TimeoutException { javax.jms.Message msg = getRawMessageFromDestination(correlationId, threadContext); if (msg==null) { throw new TimeoutException(getLogPrefix()+" timed out waiting for message with correlationId ["+correlationId+"]"); } if (log.isDebugEnabled()) { log.debug("JmsListener ["+getName()+"] received for correlationId ["+correlationId+"] replymessage ["+msg+"]"); } return msg; } private boolean sessionNeedsToBeSavedForAfterProcessMessage(Object result) { return isJmsTransacted() && !isTransacted() && isSessionsArePooled()&& result != null; } /** * Retrieves messages from queue or other channel under transaction control, but does no processing on it. */ private javax.jms.Message getRawMessageFromDestination(String correlationId, Map<String,Object> threadContext) throws ListenerException { Session session=null; javax.jms.Message msg = null; try { session = getSession(threadContext); MessageConsumer mc=null; try { mc = getReceiver(threadContext,session,correlationId); msg = mc.receive(getTimeOut()); while (msg==null && correlationId==null && canGoOn() && !isTransacted()) { msg = mc.receive(getTimeOut()); } } catch (JMSException e) { throw new ListenerException(getLogPrefix()+"exception retrieving message",e); } finally { releaseReceiver(mc,correlationId); } } finally { if (sessionNeedsToBeSavedForAfterProcessMessage(msg)) { threadContext.put(IListenerConnector.THREAD_CONTEXT_SESSION_KEY, session); } else { releaseSession(session); } } return msg; } /** * @see IPostboxListener#retrieveRawMessage(String, Map) */ @Override public javax.jms.Message retrieveRawMessage(String messageSelector, Map<String,Object> threadContext) throws ListenerException { Session session=null; try { session = getSession(threadContext); MessageConsumer mc=null; try { mc = getMessageConsumer(session, getDestination(), messageSelector); javax.jms.Message result = (getTimeOut()<0) ? mc.receiveNoWait() : mc.receive(getTimeOut()); return result; } finally { if (mc != null) { try { mc.close(); } catch(JMSException e) { log.warn(getLogPrefix()+"exception closing messageConsumer",e); } } } } catch (Exception e) { throw new ListenerException(getLogPrefix()+"exception preparing to retrieve message", e); } finally { releaseSession(session); } } protected boolean canGoOn() { return runStateEnquirer!=null && runStateEnquirer.getRunState()==RunState.STARTED; } @Override public void SetRunStateEnquirer(RunStateEnquirer enquirer) { runStateEnquirer=enquirer; } }
True
False
1,414
50
21118_0
package com.example.midasvg.pilgrim; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends AppCompatActivity { private DrawerLayout nDrawerLayout; private NavigationView navigationView; private ActionBarDrawerToggle nToggle; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Pilgrim </font>")); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646"))); //De button wordt ge-enabled op de Action Bar nDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); navigationView = (NavigationView) findViewById(R.id.navView); nToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close); nDrawerLayout.addDrawerListener(nToggle); nToggle.syncState(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { UserMenuSelector(item); return false; } }); mAuth = FirebaseAuth.getInstance(); //Button staat nu aan & kan gebruikt worden. //Het is de bedoeling dat de button disabled wordt, tot de speler bij het startpunt komt. final Button startButton = (Button) findViewById(R.id.bttnStart); startButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ Intent intent = new Intent(MainActivity.this, GameActivity.class); startActivity(intent); } }); final Button accButton = (Button) findViewById(R.id.imageAcc); accButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ProfileActivity.class); startActivity(intent); } }); } //Nu kan er op de button gedrukt worden @Override public boolean onOptionsItemSelected(MenuItem item){ if (nToggle.onOptionsItemSelected(item)){ return true; } return super.onOptionsItemSelected(item); } private void UserMenuSelector(MenuItem item){ switch (item.getItemId()){ case R.id.nav_collections: Intent intentCollection = new Intent(MainActivity.this, CollectionActivity.class); startActivity(intentCollection); break; case R.id.nav_game: Intent intentGame = new Intent(MainActivity.this, MainActivity.class); startActivity(intentGame); break; case R.id.nav_leaderboard: Intent intentLeaderboard = new Intent(MainActivity.this, LeaderboardActivity.class); startActivity(intentLeaderboard); break; case R.id.nav_profile: Intent intentProfile = new Intent(MainActivity.this, ProfileActivity.class); startActivity(intentProfile); break; case R.id.nav_guide: Intent intentGuide = new Intent(MainActivity.this, GuideActivity.class); startActivity(intentGuide); break; case R.id.nav_about: Intent intentAbout = new Intent(MainActivity.this, AboutActivity.class); startActivity(intentAbout); break; case R.id.nav_logout: mAuth.signOut(); Toast.makeText(MainActivity.this, "Logging out...", Toast.LENGTH_SHORT).show(); Intent logOut = new Intent(MainActivity.this, LoginActivity.class); startActivity(logOut); break; } } }
AP-IT-GH/CA1819-Pilgrim
src/AndroidApp/app/src/main/java/com/example/midasvg/pilgrim/MainActivity.java
1,268
//De button wordt ge-enabled op de Action Bar
line_comment
nl
package com.example.midasvg.pilgrim; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends AppCompatActivity { private DrawerLayout nDrawerLayout; private NavigationView navigationView; private ActionBarDrawerToggle nToggle; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Pilgrim </font>")); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646"))); //De button<SUF> nDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); navigationView = (NavigationView) findViewById(R.id.navView); nToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close); nDrawerLayout.addDrawerListener(nToggle); nToggle.syncState(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { UserMenuSelector(item); return false; } }); mAuth = FirebaseAuth.getInstance(); //Button staat nu aan & kan gebruikt worden. //Het is de bedoeling dat de button disabled wordt, tot de speler bij het startpunt komt. final Button startButton = (Button) findViewById(R.id.bttnStart); startButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ Intent intent = new Intent(MainActivity.this, GameActivity.class); startActivity(intent); } }); final Button accButton = (Button) findViewById(R.id.imageAcc); accButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ProfileActivity.class); startActivity(intent); } }); } //Nu kan er op de button gedrukt worden @Override public boolean onOptionsItemSelected(MenuItem item){ if (nToggle.onOptionsItemSelected(item)){ return true; } return super.onOptionsItemSelected(item); } private void UserMenuSelector(MenuItem item){ switch (item.getItemId()){ case R.id.nav_collections: Intent intentCollection = new Intent(MainActivity.this, CollectionActivity.class); startActivity(intentCollection); break; case R.id.nav_game: Intent intentGame = new Intent(MainActivity.this, MainActivity.class); startActivity(intentGame); break; case R.id.nav_leaderboard: Intent intentLeaderboard = new Intent(MainActivity.this, LeaderboardActivity.class); startActivity(intentLeaderboard); break; case R.id.nav_profile: Intent intentProfile = new Intent(MainActivity.this, ProfileActivity.class); startActivity(intentProfile); break; case R.id.nav_guide: Intent intentGuide = new Intent(MainActivity.this, GuideActivity.class); startActivity(intentGuide); break; case R.id.nav_about: Intent intentAbout = new Intent(MainActivity.this, AboutActivity.class); startActivity(intentAbout); break; case R.id.nav_logout: mAuth.signOut(); Toast.makeText(MainActivity.this, "Logging out...", Toast.LENGTH_SHORT).show(); Intent logOut = new Intent(MainActivity.this, LoginActivity.class); startActivity(logOut); break; } } }
True
False
1,426
558
11601_0
package agent; import lejos.nxt.NXTRegulatedMotor; import robotica.SimState; import standard.Agent; public class Customer extends Agent { private long previousTime; private long currentTime; private long timeToWait = 0; private CustomerBehavior behavior; private boolean rotating = false; private NXTRegulatedMotor motor; public Customer(NXTRegulatedMotor motor, String name) { super(name, new SimState("IDLE")); this.behavior = new CustomerBehavior(4); resetTime(); this.motor = motor; motor.resetTachoCount(); } public void reset() { resetTime(); resetRotation(); this.setState(new SimState("IDLE")); this.setChanged(); } @Override public void update() { switch (currentState().name()) { case "IDLE": idle(); break; case "WBESTELLEN": wBestellen(); break; case "WETEN": wEten(); break; case "ETEN": eten(); break; case "WBETALEN": wBetalen(); break; } this.updateState(); notifyObservers(); } private long timePast() { currentTime = System.currentTimeMillis(); long timePast = currentTime - previousTime; previousTime = currentTime; return timePast; } private boolean resetTimeToWait() { if (timeToWait <= 0) { timeToWait = 0; return true; } else return false; } private void resetTime() { currentTime = System.currentTimeMillis(); previousTime = currentTime; timeToWait = 0; } private void idle() { resetRotation(); if (resetTimeToWait()) timeToWait = behavior.idle(); timeToWait -= timePast(); System.out.println("IDLE"); motor.setSpeed(720); motor.rotateTo(0); if (timeToWait < 0) { this.setState(new SimState("WBESTELLEN")); setChanged(); resetTime(); } } private void wBestellen() { resetRotation(); motor.setSpeed(720); motor.rotateTo(90); resetTime(); } private void wEten() { resetRotation(); motor.setSpeed(720); motor.rotateTo(180); resetTime(); } private void eten() { if (resetTimeToWait()) timeToWait = behavior.eten(); timeToWait -= timePast(); System.out.println("ETEN"); if (timeToWait < 0) { this.setState(new SimState("WBETALEN")); setChanged(); resetTime(); } rotating = true; motor.setSpeed(300); motor.forward(); } private void wBetalen() { resetRotation(); motor.setSpeed(720); motor.setSpeed(720); motor.rotateTo(270); } private void resetRotation() { if (rotating) { int lol = motor.getTachoCount() / 360; motor.rotateTo(lol * 360); motor.resetTachoCount(); rotating = false; } } public void processCompletedTask(String task) { System.out.println(task); switch (task) { case "BESTELLING_OPGENOMEN": if (this.currentState().name().equals("WBESTELLEN")) { this.setState(new SimState("WETEN")); this.setChanged(); } break; case "ETEN_BEZORGD": if (this.currentState().name().equals("WETEN")) { this.setState(new SimState("ETEN")); this.setChanged(); } break; case "BETALING_AFGEROND": if (this.currentState().name().equals("WBETALEN")) { motor.rotateTo(0); this.setState(new SimState("STOP")); this.setChanged(); } break; } } } /* * 5 states: * * -idle"IDLE" Niks boven. -Wachten op bestellen: "WBESTELLEN" Rood boven. * -Wachten op eten: "WETEN" Blauw boven. -Eten: "ETEN" Motor draait rond. * -Betalen: "WBETALEN" Zwart boven. */
GSamuel/Robotica-2-2013
Robotica 2 NXT/src/agent/Customer.java
1,308
/* * 5 states: * * -idle"IDLE" Niks boven. -Wachten op bestellen: "WBESTELLEN" Rood boven. * -Wachten op eten: "WETEN" Blauw boven. -Eten: "ETEN" Motor draait rond. * -Betalen: "WBETALEN" Zwart boven. */
block_comment
nl
package agent; import lejos.nxt.NXTRegulatedMotor; import robotica.SimState; import standard.Agent; public class Customer extends Agent { private long previousTime; private long currentTime; private long timeToWait = 0; private CustomerBehavior behavior; private boolean rotating = false; private NXTRegulatedMotor motor; public Customer(NXTRegulatedMotor motor, String name) { super(name, new SimState("IDLE")); this.behavior = new CustomerBehavior(4); resetTime(); this.motor = motor; motor.resetTachoCount(); } public void reset() { resetTime(); resetRotation(); this.setState(new SimState("IDLE")); this.setChanged(); } @Override public void update() { switch (currentState().name()) { case "IDLE": idle(); break; case "WBESTELLEN": wBestellen(); break; case "WETEN": wEten(); break; case "ETEN": eten(); break; case "WBETALEN": wBetalen(); break; } this.updateState(); notifyObservers(); } private long timePast() { currentTime = System.currentTimeMillis(); long timePast = currentTime - previousTime; previousTime = currentTime; return timePast; } private boolean resetTimeToWait() { if (timeToWait <= 0) { timeToWait = 0; return true; } else return false; } private void resetTime() { currentTime = System.currentTimeMillis(); previousTime = currentTime; timeToWait = 0; } private void idle() { resetRotation(); if (resetTimeToWait()) timeToWait = behavior.idle(); timeToWait -= timePast(); System.out.println("IDLE"); motor.setSpeed(720); motor.rotateTo(0); if (timeToWait < 0) { this.setState(new SimState("WBESTELLEN")); setChanged(); resetTime(); } } private void wBestellen() { resetRotation(); motor.setSpeed(720); motor.rotateTo(90); resetTime(); } private void wEten() { resetRotation(); motor.setSpeed(720); motor.rotateTo(180); resetTime(); } private void eten() { if (resetTimeToWait()) timeToWait = behavior.eten(); timeToWait -= timePast(); System.out.println("ETEN"); if (timeToWait < 0) { this.setState(new SimState("WBETALEN")); setChanged(); resetTime(); } rotating = true; motor.setSpeed(300); motor.forward(); } private void wBetalen() { resetRotation(); motor.setSpeed(720); motor.setSpeed(720); motor.rotateTo(270); } private void resetRotation() { if (rotating) { int lol = motor.getTachoCount() / 360; motor.rotateTo(lol * 360); motor.resetTachoCount(); rotating = false; } } public void processCompletedTask(String task) { System.out.println(task); switch (task) { case "BESTELLING_OPGENOMEN": if (this.currentState().name().equals("WBESTELLEN")) { this.setState(new SimState("WETEN")); this.setChanged(); } break; case "ETEN_BEZORGD": if (this.currentState().name().equals("WETEN")) { this.setState(new SimState("ETEN")); this.setChanged(); } break; case "BETALING_AFGEROND": if (this.currentState().name().equals("WBETALEN")) { motor.rotateTo(0); this.setState(new SimState("STOP")); this.setChanged(); } break; } } } /* * 5 states: <SUF>*/
True
False
1,430
3,743
52485_8
/** * TINPRO04-3 Les 7-HW // Circular Doubly Linked List, non-generic * 20240217 // [email protected] * */ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class AppCircular { public static void main(String[] args) { // Lees ./input in zoals behandeld in Les 6: File I/O String input = ""; try { input = Files.readString(Paths.get("./input")); } catch ( IOException e ) { e.printStackTrace(); } // Split het bestand op in een array van woorden (String) String splitString[] = input.split(" "); // Stop alle woorden in de LinkedList, achter elkaar. LinkedList list = new LinkedList(); for (String str : splitString) { list.push(str); } // Tests list.print(); list.pop("actually"); list.print(); list.pop(2); list.print(); } } /** * Grote verschil is de toevoeging van de nieuwe field: private Node previous (en bijbehorende get/set-methods). * Dat vergt ingrijpende aanpassingen aan je LinkedList methods. * */ class Node { // Fields: private Node previous; private Node next; private String value; // Constructor(s): public Node(String value) { this.value = value; } // Get/set methods: public Node getNext() { return this.next; } public void setNext(Node next) { this.next = next; } public Node getPrevious() { return this.previous; } public void setPrevious(Node previous) { this.previous = previous; } public String getValue() { return this.value; } // Other methods (n/a) } /** * Merk op dat de enige aanpassing ten opzichte van de "gewone" Doubly Linked List * is dat in alle while-loops de conditie: * (current.getNext() != null) * is vervangen door: * (!current.getNext().equals(this.head)) * */ class LinkedList { // Fields: (Belangrijk: Nieuwe field `Node tail` // Helpt bij het circulair maken van je lijst) private Node head; private Node tail; // Constructors (n/a) // Get/set methods (n/a) // Other methods: public void push(String value) { Node newNode = new Node(value); if (this.head == null && this.tail == null) { this.head = newNode; this.tail = newNode; } else { Node current = this.head; while (!current.getNext().equals(this.head)) { current = current.getNext(); } current.setNext(newNode); current.getNext().setPrevious(current); // Staar hier even naar. this.tail = current.getNext(); // Of: this.tail = newNode } // BONUS: Maak de lijst circulair! // Dit kun je buiten de if/else laten, omdat je dit in beide gevallen hetzelfde zou doen this.tail.setNext(this.head); this.head.setPrevious(this.tail); } public String pop(String value) { Node current = this.head; while (!current.getNext().equals(this.head)) { if (current.getNext().getValue().equals(value)) { Node returnNode = current.getNext(); // Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node // VERGEET NIET de verbinding in beide richtingen goed te leggen, anders kan de GC z'n werk niet doen current.setNext(current.getNext().getNext()); current.getNext().setPrevious(current); // Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken returnNode.setPrevious(null); returnNode.setNext(null); return returnNode.getValue(); } current = current.getNext(); } return "Not found"; } public String pop(int index) { int currentindex = 0; Node current = head; while (currentindex != index && !current.getNext().equals(this.head)) { if (currentindex == index-1) { Node returnNode = current.getNext(); // Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node // VERGEET NIET de verbinding in beide richtingen goed te leggen current.setNext(current.getNext().getNext()); current.getNext().setPrevious(current); // Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken returnNode.setPrevious(null); returnNode.setNext(null); return returnNode.getValue(); } currentindex++; current = current.getNext(); } return "Not found"; } public String peek(String value) { Node current = head; while (!current.getNext().equals(this.head)) { if (current.getNext().getValue().equals(value)) { return current.getNext().getValue(); } current = current.getNext(); } return "Not found"; } public void print() { Node current = this.head; do { System.out.print(current.getValue()+" "); current = current.getNext(); } while (!current.equals(this.head)); System.out.println(); } }
mskelo/progdemocode
java3/7-huiswerk/Circular Doubly LL/AppCircular.java
1,562
// Helpt bij het circulair maken van je lijst)
line_comment
nl
/** * TINPRO04-3 Les 7-HW // Circular Doubly Linked List, non-generic * 20240217 // [email protected] * */ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class AppCircular { public static void main(String[] args) { // Lees ./input in zoals behandeld in Les 6: File I/O String input = ""; try { input = Files.readString(Paths.get("./input")); } catch ( IOException e ) { e.printStackTrace(); } // Split het bestand op in een array van woorden (String) String splitString[] = input.split(" "); // Stop alle woorden in de LinkedList, achter elkaar. LinkedList list = new LinkedList(); for (String str : splitString) { list.push(str); } // Tests list.print(); list.pop("actually"); list.print(); list.pop(2); list.print(); } } /** * Grote verschil is de toevoeging van de nieuwe field: private Node previous (en bijbehorende get/set-methods). * Dat vergt ingrijpende aanpassingen aan je LinkedList methods. * */ class Node { // Fields: private Node previous; private Node next; private String value; // Constructor(s): public Node(String value) { this.value = value; } // Get/set methods: public Node getNext() { return this.next; } public void setNext(Node next) { this.next = next; } public Node getPrevious() { return this.previous; } public void setPrevious(Node previous) { this.previous = previous; } public String getValue() { return this.value; } // Other methods (n/a) } /** * Merk op dat de enige aanpassing ten opzichte van de "gewone" Doubly Linked List * is dat in alle while-loops de conditie: * (current.getNext() != null) * is vervangen door: * (!current.getNext().equals(this.head)) * */ class LinkedList { // Fields: (Belangrijk: Nieuwe field `Node tail` // Helpt bij<SUF> private Node head; private Node tail; // Constructors (n/a) // Get/set methods (n/a) // Other methods: public void push(String value) { Node newNode = new Node(value); if (this.head == null && this.tail == null) { this.head = newNode; this.tail = newNode; } else { Node current = this.head; while (!current.getNext().equals(this.head)) { current = current.getNext(); } current.setNext(newNode); current.getNext().setPrevious(current); // Staar hier even naar. this.tail = current.getNext(); // Of: this.tail = newNode } // BONUS: Maak de lijst circulair! // Dit kun je buiten de if/else laten, omdat je dit in beide gevallen hetzelfde zou doen this.tail.setNext(this.head); this.head.setPrevious(this.tail); } public String pop(String value) { Node current = this.head; while (!current.getNext().equals(this.head)) { if (current.getNext().getValue().equals(value)) { Node returnNode = current.getNext(); // Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node // VERGEET NIET de verbinding in beide richtingen goed te leggen, anders kan de GC z'n werk niet doen current.setNext(current.getNext().getNext()); current.getNext().setPrevious(current); // Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken returnNode.setPrevious(null); returnNode.setNext(null); return returnNode.getValue(); } current = current.getNext(); } return "Not found"; } public String pop(int index) { int currentindex = 0; Node current = head; while (currentindex != index && !current.getNext().equals(this.head)) { if (currentindex == index-1) { Node returnNode = current.getNext(); // Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node // VERGEET NIET de verbinding in beide richtingen goed te leggen current.setNext(current.getNext().getNext()); current.getNext().setPrevious(current); // Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken returnNode.setPrevious(null); returnNode.setNext(null); return returnNode.getValue(); } currentindex++; current = current.getNext(); } return "Not found"; } public String peek(String value) { Node current = head; while (!current.getNext().equals(this.head)) { if (current.getNext().getValue().equals(value)) { return current.getNext().getValue(); } current = current.getNext(); } return "Not found"; } public void print() { Node current = this.head; do { System.out.print(current.getValue()+" "); current = current.getNext(); } while (!current.equals(this.head)); System.out.println(); } }
True
False
1,432
1,703
32735_0
import java.io.*; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.json.simple.*; import org.json.simple.parser.JSONParser; public class JSONHandler { public static String getJSON(String filename) { String jsonText = ""; try { BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); String line; while ((line = bufferedReader.readLine()) != null) { jsonText += line + "\n"; } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } return jsonText; } public static void updateJson(HashMap<String, Game> gameMap) { JSONArray gamesList = new JSONArray(); for (Map.Entry<String, Game> entry : gameMap.entrySet()) { Game game = entry.getValue(); // Voor elke game, creëer een nieuw JSONObject en vul het met de game details JSONObject gameDetails = new JSONObject(); gameDetails.put("name", game.getName()); gameDetails.put("genre", game.getGenre()); gameDetails.put("platform", game.getPlatform()); gameDetails.put("price", String.format("%.2f", game.getBasePrice())); gameDetails.put("sale", Integer.toString(game.korting)); gamesList.add(gameDetails); } // Creëer een hoofd JSONObject dat de games lijst bevat JSONObject root = new JSONObject(); root.put("games", gamesList); try (FileWriter file = new FileWriter("GamesDB.json")) { String content = root.toJSONString(); file.write(content); } catch (IOException e) { System.out.println("Er is een fout opgetreden bij het schrijven naar het JSON-bestand."); e.printStackTrace(); } } //create a method that reads a JSON file and prints the contents to the console public static HashMap<String, Game> readJSON(String filename, HashMap<String, Game> gameMap) { JSONParser parser = new JSONParser(); JSONArray games = null; try { Object obj = parser.parse(new FileReader(filename)); if (obj instanceof JSONObject jsonObject) { games = (JSONArray) jsonObject.get("games"); // process games array } else if (obj instanceof JSONArray) { games = (JSONArray) obj; // process games array } else { throw new Exception("Invalid JSON file"); } gameMap = new HashMap<>(); for (Object game : games) { JSONObject gameObj = (JSONObject) game; String name = (String) gameObj.get("name"); String genre = (String) gameObj.get("genre"); String platform = (String) gameObj.get("platform"); double price = Double.parseDouble(((String) gameObj.get("price")).replace(",", ".")); int korting = Integer.parseInt((String) gameObj.get("sale")); Game tempGame = new Game(name, genre, platform, price, korting); gameMap.put(name, tempGame); } } catch (Exception e) { e.printStackTrace(); } return gameMap; } }
Techmaster3000/RetroReviewer
src/JSONHandler.java
873
// Voor elke game, creëer een nieuw JSONObject en vul het met de game details
line_comment
nl
import java.io.*; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.json.simple.*; import org.json.simple.parser.JSONParser; public class JSONHandler { public static String getJSON(String filename) { String jsonText = ""; try { BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); String line; while ((line = bufferedReader.readLine()) != null) { jsonText += line + "\n"; } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } return jsonText; } public static void updateJson(HashMap<String, Game> gameMap) { JSONArray gamesList = new JSONArray(); for (Map.Entry<String, Game> entry : gameMap.entrySet()) { Game game = entry.getValue(); // Voor elke<SUF> JSONObject gameDetails = new JSONObject(); gameDetails.put("name", game.getName()); gameDetails.put("genre", game.getGenre()); gameDetails.put("platform", game.getPlatform()); gameDetails.put("price", String.format("%.2f", game.getBasePrice())); gameDetails.put("sale", Integer.toString(game.korting)); gamesList.add(gameDetails); } // Creëer een hoofd JSONObject dat de games lijst bevat JSONObject root = new JSONObject(); root.put("games", gamesList); try (FileWriter file = new FileWriter("GamesDB.json")) { String content = root.toJSONString(); file.write(content); } catch (IOException e) { System.out.println("Er is een fout opgetreden bij het schrijven naar het JSON-bestand."); e.printStackTrace(); } } //create a method that reads a JSON file and prints the contents to the console public static HashMap<String, Game> readJSON(String filename, HashMap<String, Game> gameMap) { JSONParser parser = new JSONParser(); JSONArray games = null; try { Object obj = parser.parse(new FileReader(filename)); if (obj instanceof JSONObject jsonObject) { games = (JSONArray) jsonObject.get("games"); // process games array } else if (obj instanceof JSONArray) { games = (JSONArray) obj; // process games array } else { throw new Exception("Invalid JSON file"); } gameMap = new HashMap<>(); for (Object game : games) { JSONObject gameObj = (JSONObject) game; String name = (String) gameObj.get("name"); String genre = (String) gameObj.get("genre"); String platform = (String) gameObj.get("platform"); double price = Double.parseDouble(((String) gameObj.get("price")).replace(",", ".")); int korting = Integer.parseInt((String) gameObj.get("sale")); Game tempGame = new Game(name, genre, platform, price, korting); gameMap.put(name, tempGame); } } catch (Exception e) { e.printStackTrace(); } return gameMap; } }
True
False
1,433
1,498
111117_2
package nl.hu.bep.setup.game.webservices; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import nl.hu.bep.setup.game.domain.BattleSnake; import nl.hu.bep.setup.game.domain.Game; import nl.hu.bep.setup.game.domain.Snake; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; import java.util.Map; @Path("snake") public class SnakeResource { private String lastMove; //haalt snake op @GET @Produces(MediaType.APPLICATION_JSON) public Response getSnake() { return Response.ok(BattleSnake.getMy_BattleSnake().getSnake()).build(); } //Veranderd snake values @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed("user") public Response changeSnake(SnakeDTO snakeDTO) { Snake snake = BattleSnake.getMy_BattleSnake().getSnake(); snake.updateSnake(snakeDTO.color, snakeDTO.head, snakeDTO.tail); return Response.ok(snake).build(); } private static class SnakeDTO{ public String color; public String tail; public String head; } //Methode slaat data van game op bij start @POST @Path("start") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response startGame(GameDataDtos gameDataDtos) { Game game = new Game(gameDataDtos.gameDTO.id, gameDataDtos.youDTO.name); BattleSnake.getMy_BattleSnake().addGame(game); return Response.ok().build(); } //move method geeft de move terug die de snake moet doen @POST @Path("move") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response move(GameDataDtos gameDataDtos) { Snake snake = BattleSnake.getMy_BattleSnake().getSnake(); Game game = BattleSnake.getMy_BattleSnake().getGameById(gameDataDtos.gameDTO.id); Map<String, String> move = snake.getNextMove(gameDataDtos); game.addMove(move.get("move")); return Response.ok().entity(move).build(); } //Slaat alle data op bij einde game @POST @Path("end") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response endGame(GameDataDtos gameDataDtos) { Game game = BattleSnake.getMy_BattleSnake().getGameById(gameDataDtos.gameDTO.id); if (game == null) { return Response.status(Response.Status.NOT_FOUND).build(); } game.setAmountOfMoves(gameDataDtos.turn); game.setEndingSnakeLength(gameDataDtos.youDTO.length); return Response.ok().build(); } @JsonIgnoreProperties(ignoreUnknown = true) public static class GameDataDtos { @JsonProperty("game") public GameDTO gameDTO; @JsonProperty("turn") public int turn; @JsonProperty("board") public BoardDTO boardDTO; @JsonProperty("you") public YouDTO youDTO; } @JsonIgnoreProperties(ignoreUnknown = true) public static class GameDTO { public String id; } @JsonIgnoreProperties(ignoreUnknown = true) public static class BoardDTO { public int height; public int width; public List<Map<String, Integer>> food; } @JsonIgnoreProperties(ignoreUnknown = true) public static class YouDTO { public String name; public int length; public List<Map<String, Integer>> body; public Map<String, Integer> head; } }
Rubens880/BattleSnake
src/main/java/nl/hu/bep/setup/game/webservices/SnakeResource.java
1,169
//Methode slaat data van game op bij start
line_comment
nl
package nl.hu.bep.setup.game.webservices; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import nl.hu.bep.setup.game.domain.BattleSnake; import nl.hu.bep.setup.game.domain.Game; import nl.hu.bep.setup.game.domain.Snake; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; import java.util.Map; @Path("snake") public class SnakeResource { private String lastMove; //haalt snake op @GET @Produces(MediaType.APPLICATION_JSON) public Response getSnake() { return Response.ok(BattleSnake.getMy_BattleSnake().getSnake()).build(); } //Veranderd snake values @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed("user") public Response changeSnake(SnakeDTO snakeDTO) { Snake snake = BattleSnake.getMy_BattleSnake().getSnake(); snake.updateSnake(snakeDTO.color, snakeDTO.head, snakeDTO.tail); return Response.ok(snake).build(); } private static class SnakeDTO{ public String color; public String tail; public String head; } //Methode slaat<SUF> @POST @Path("start") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response startGame(GameDataDtos gameDataDtos) { Game game = new Game(gameDataDtos.gameDTO.id, gameDataDtos.youDTO.name); BattleSnake.getMy_BattleSnake().addGame(game); return Response.ok().build(); } //move method geeft de move terug die de snake moet doen @POST @Path("move") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response move(GameDataDtos gameDataDtos) { Snake snake = BattleSnake.getMy_BattleSnake().getSnake(); Game game = BattleSnake.getMy_BattleSnake().getGameById(gameDataDtos.gameDTO.id); Map<String, String> move = snake.getNextMove(gameDataDtos); game.addMove(move.get("move")); return Response.ok().entity(move).build(); } //Slaat alle data op bij einde game @POST @Path("end") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response endGame(GameDataDtos gameDataDtos) { Game game = BattleSnake.getMy_BattleSnake().getGameById(gameDataDtos.gameDTO.id); if (game == null) { return Response.status(Response.Status.NOT_FOUND).build(); } game.setAmountOfMoves(gameDataDtos.turn); game.setEndingSnakeLength(gameDataDtos.youDTO.length); return Response.ok().build(); } @JsonIgnoreProperties(ignoreUnknown = true) public static class GameDataDtos { @JsonProperty("game") public GameDTO gameDTO; @JsonProperty("turn") public int turn; @JsonProperty("board") public BoardDTO boardDTO; @JsonProperty("you") public YouDTO youDTO; } @JsonIgnoreProperties(ignoreUnknown = true) public static class GameDTO { public String id; } @JsonIgnoreProperties(ignoreUnknown = true) public static class BoardDTO { public int height; public int width; public List<Map<String, Integer>> food; } @JsonIgnoreProperties(ignoreUnknown = true) public static class YouDTO { public String name; public int length; public List<Map<String, Integer>> body; public Map<String, Integer> head; } }
True
False
1,436
1,071
109965_9
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.dtos.user.UserDto; import nl.novi.techiteasy.dtos.user.UserResponseDto; import nl.novi.techiteasy.exceptions.BadRequestException; import nl.novi.techiteasy.dtos.authority.AuthorityDto; import nl.novi.techiteasy.services.UserService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.util.List; @CrossOrigin @RestController @RequestMapping(value = "/users") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @GetMapping(value = "") public ResponseEntity<List<UserDto>> getUsers() { List<UserDto> userDtos = userService.getUsers(); return ResponseEntity.ok().body(userDtos); } @GetMapping(value = "/{username}") public ResponseEntity<UserDto> getUser(@PathVariable("username") String username) { UserDto optionalUser = userService.getUser(username); return ResponseEntity.ok().body(optionalUser); } @PostMapping(value = "") public ResponseEntity<UserDto> createKlant(@RequestBody UserDto dto) {; String newUsername = userService.createUser(dto); userService.addAuthority(newUsername, "ROLE_USER"); URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{username}") .buildAndExpand(newUsername).toUri(); return ResponseEntity.created(location).build(); } @PutMapping(value = "/{username}") public ResponseEntity<UserDto> updateKlant(@PathVariable("username") String username, @RequestBody UserDto dto) { userService.updateUser(username, dto); return ResponseEntity.noContent().build(); } @DeleteMapping(value = "/{username}") public ResponseEntity<Object> deleteKlant(@PathVariable("username") String username) { userService.deleteUser(username); return ResponseEntity.noContent().build(); } @GetMapping(value = "/{username}/authorities") public ResponseEntity<Object> getUserAuthorities(@PathVariable("username") String username) { return ResponseEntity.ok().body(userService.getAuthorities(username)); } // Vraag in to do: Als Requestbody wordt hier een Map<String, Object> gebruikt om de "authorityName" binnen te halen, dat werkt, maar kun je een betere oplossing bedenken? // Antwoord: Ja, met een DTO. Ik heb deze class AuthorityDto genoemd en ondergebracht in het mapje dtos/authority, @PostMapping(value = "/{username}/authorities") public ResponseEntity<Object> addUserAuthority( @PathVariable("username") String username, @RequestBody AuthorityDto authorityDto) { try { String authorityName = authorityDto.authority; userService.addAuthority(username, authorityName); return ResponseEntity.noContent().build(); } catch (Exception ex) { throw new BadRequestException(); } } // Oude versie: // @PostMapping(value = "/{username}/authorities") // public ResponseEntity<Object> addUserAuthority(@PathVariable("username") String username, @RequestBody Map<String, Object> fields) { // try { // String authorityName = (String) fields.get("authority"); // userService.addAuthority(username, authorityName); // return ResponseEntity.noContent().build(); // } // catch (Exception ex) { // throw new BadRequestException(); // } // } @DeleteMapping(value = "/{username}/authorities/{authority}") public ResponseEntity<Object> deleteUserAuthority(@PathVariable("username") String username, @PathVariable("authority") String authority) { userService.removeAuthority(username, authority); return ResponseEntity.noContent().build(); } // Bonusopdracht // Toepassen van SecurityContextHolder en Authentication classes (zie imports), en methode getUserById toegevoegd. // Ik heb een aparte ResponseDto gemaakt, die een beperkt aantal velden teruggeeft aan de gebruiker. // Ben er niet meer aan toegekomen om dit uit te testen in Postman voor de deadline, maar dit wil ik nog wel gaan doen. Ben wel benieuwd of ik op de goede weg zit. @GetMapping("/{id}") public ResponseEntity<Object> getUserById(@PathVariable("id") String id) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String username = authentication.getName(); if (username.equals(id)) { UserDto userDto = userService.getUser(id); UserResponseDto responseDto = new UserResponseDto(userDto.getUsername(), userDto.getEmail(), userDto.getAuthorities()); return ResponseEntity.ok(userDto); } else { return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Access denied"); } } }
MarjetBosma/NOVI-backend-springboot-techiteasy
src/main/java/nl/novi/techiteasy/controllers/UserController.java
1,422
// Ben er niet meer aan toegekomen om dit uit te testen in Postman voor de deadline, maar dit wil ik nog wel gaan doen. Ben wel benieuwd of ik op de goede weg zit.
line_comment
nl
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.dtos.user.UserDto; import nl.novi.techiteasy.dtos.user.UserResponseDto; import nl.novi.techiteasy.exceptions.BadRequestException; import nl.novi.techiteasy.dtos.authority.AuthorityDto; import nl.novi.techiteasy.services.UserService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.util.List; @CrossOrigin @RestController @RequestMapping(value = "/users") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @GetMapping(value = "") public ResponseEntity<List<UserDto>> getUsers() { List<UserDto> userDtos = userService.getUsers(); return ResponseEntity.ok().body(userDtos); } @GetMapping(value = "/{username}") public ResponseEntity<UserDto> getUser(@PathVariable("username") String username) { UserDto optionalUser = userService.getUser(username); return ResponseEntity.ok().body(optionalUser); } @PostMapping(value = "") public ResponseEntity<UserDto> createKlant(@RequestBody UserDto dto) {; String newUsername = userService.createUser(dto); userService.addAuthority(newUsername, "ROLE_USER"); URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{username}") .buildAndExpand(newUsername).toUri(); return ResponseEntity.created(location).build(); } @PutMapping(value = "/{username}") public ResponseEntity<UserDto> updateKlant(@PathVariable("username") String username, @RequestBody UserDto dto) { userService.updateUser(username, dto); return ResponseEntity.noContent().build(); } @DeleteMapping(value = "/{username}") public ResponseEntity<Object> deleteKlant(@PathVariable("username") String username) { userService.deleteUser(username); return ResponseEntity.noContent().build(); } @GetMapping(value = "/{username}/authorities") public ResponseEntity<Object> getUserAuthorities(@PathVariable("username") String username) { return ResponseEntity.ok().body(userService.getAuthorities(username)); } // Vraag in to do: Als Requestbody wordt hier een Map<String, Object> gebruikt om de "authorityName" binnen te halen, dat werkt, maar kun je een betere oplossing bedenken? // Antwoord: Ja, met een DTO. Ik heb deze class AuthorityDto genoemd en ondergebracht in het mapje dtos/authority, @PostMapping(value = "/{username}/authorities") public ResponseEntity<Object> addUserAuthority( @PathVariable("username") String username, @RequestBody AuthorityDto authorityDto) { try { String authorityName = authorityDto.authority; userService.addAuthority(username, authorityName); return ResponseEntity.noContent().build(); } catch (Exception ex) { throw new BadRequestException(); } } // Oude versie: // @PostMapping(value = "/{username}/authorities") // public ResponseEntity<Object> addUserAuthority(@PathVariable("username") String username, @RequestBody Map<String, Object> fields) { // try { // String authorityName = (String) fields.get("authority"); // userService.addAuthority(username, authorityName); // return ResponseEntity.noContent().build(); // } // catch (Exception ex) { // throw new BadRequestException(); // } // } @DeleteMapping(value = "/{username}/authorities/{authority}") public ResponseEntity<Object> deleteUserAuthority(@PathVariable("username") String username, @PathVariable("authority") String authority) { userService.removeAuthority(username, authority); return ResponseEntity.noContent().build(); } // Bonusopdracht // Toepassen van SecurityContextHolder en Authentication classes (zie imports), en methode getUserById toegevoegd. // Ik heb een aparte ResponseDto gemaakt, die een beperkt aantal velden teruggeeft aan de gebruiker. // Ben er<SUF> @GetMapping("/{id}") public ResponseEntity<Object> getUserById(@PathVariable("id") String id) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String username = authentication.getName(); if (username.equals(id)) { UserDto userDto = userService.getUser(id); UserResponseDto responseDto = new UserResponseDto(userDto.getUsername(), userDto.getEmail(), userDto.getAuthorities()); return ResponseEntity.ok(userDto); } else { return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Access denied"); } } }
True
False
1,440
716
30152_0
package com.hyxogen.authenticator; import org.apache.commons.codec.digest.DigestUtils; import org.bukkit.entity.Player; import com.hyxogen.authenticator.challenge.ChallengeHandler; import com.hyxogen.authenticator.user.User; import com.hyxogen.authenticator.user.UserHandler; import com.hyxogen.authenticator.user.UserLogin; import com.hyxogen.authenticator.util.CryptoUtils; import com.hyxogen.authenticator.util.Permissions; public class AuthenticationHandler { public static final int COOLDOWN = 30 * 60; public final ChallengeHandler challengeHandler; public AuthenticationHandler(ChallengeHandler challengeHandler) { this.challengeHandler = challengeHandler; } public boolean needsAuthentication(Player player) { if(!player.hasPermission(Permissions.PERM_AUTH_REQUIRED) && !player.hasPermission(Permissions.PERM_AUTH_ALLOWED)) return false; if(!isReady(player)) return true; long current = System.currentTimeMillis(); User user = UserHandler.getUser(player.getUniqueId()); UserLogin lastLogin = user.lastLogin; //TODO cache result zodat dit niet iedere movement gechecked moet worden. //We zouden ook slowness 100000 kunnen geven zodat ze niet kunnen bewegen //Dit werkt niet voor commands en chat berichten if(player.getAddress().getAddress().getAddress() != lastLogin.address) return true; if(((lastLogin.time - current) / 1000L) > COOLDOWN) return true; return false; } public boolean handleAuth(Player player, String code) { // if(!needsAuthentication(player)) // return true; User user = UserHandler.getUser(player.getUniqueId()); long current = System.currentTimeMillis(); if(CryptoUtils.checkTOTP(user.key, current / 1000L, 1, 6, code)) { challengeHandler.finishAll(user); user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis()); return true; } else if (CryptoUtils.containsKey(DigestUtils.sha1(code), user.backupCodes)) { challengeHandler.finishAll(user); user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis()); return true; } else { return false; } } public boolean isReady(Player player) { User user = UserHandler.getUser(player.getUniqueId()); if(user.lastLogin == null) return false; else return true; } }
Hyxogen/AuthenticatorPlugin
src/com/hyxogen/authenticator/AuthenticationHandler.java
762
//TODO cache result zodat dit niet iedere movement gechecked moet worden.
line_comment
nl
package com.hyxogen.authenticator; import org.apache.commons.codec.digest.DigestUtils; import org.bukkit.entity.Player; import com.hyxogen.authenticator.challenge.ChallengeHandler; import com.hyxogen.authenticator.user.User; import com.hyxogen.authenticator.user.UserHandler; import com.hyxogen.authenticator.user.UserLogin; import com.hyxogen.authenticator.util.CryptoUtils; import com.hyxogen.authenticator.util.Permissions; public class AuthenticationHandler { public static final int COOLDOWN = 30 * 60; public final ChallengeHandler challengeHandler; public AuthenticationHandler(ChallengeHandler challengeHandler) { this.challengeHandler = challengeHandler; } public boolean needsAuthentication(Player player) { if(!player.hasPermission(Permissions.PERM_AUTH_REQUIRED) && !player.hasPermission(Permissions.PERM_AUTH_ALLOWED)) return false; if(!isReady(player)) return true; long current = System.currentTimeMillis(); User user = UserHandler.getUser(player.getUniqueId()); UserLogin lastLogin = user.lastLogin; //TODO cache<SUF> //We zouden ook slowness 100000 kunnen geven zodat ze niet kunnen bewegen //Dit werkt niet voor commands en chat berichten if(player.getAddress().getAddress().getAddress() != lastLogin.address) return true; if(((lastLogin.time - current) / 1000L) > COOLDOWN) return true; return false; } public boolean handleAuth(Player player, String code) { // if(!needsAuthentication(player)) // return true; User user = UserHandler.getUser(player.getUniqueId()); long current = System.currentTimeMillis(); if(CryptoUtils.checkTOTP(user.key, current / 1000L, 1, 6, code)) { challengeHandler.finishAll(user); user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis()); return true; } else if (CryptoUtils.containsKey(DigestUtils.sha1(code), user.backupCodes)) { challengeHandler.finishAll(user); user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis()); return true; } else { return false; } } public boolean isReady(Player player) { User user = UserHandler.getUser(player.getUniqueId()); if(user.lastLogin == null) return false; else return true; } }
True
False
1,441
1,396
15324_6
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class DemoWorld extends World { // Declareren van CollisionEngine private CollisionEngine ce; // Declareren van TileEngine private TileEngine te; /** * Constructor for objects of class MyWorld. * */ public DemoWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg_gras.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, 17, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},}; // initialiseren van de TileEngine klasse om de map aan de world toe te voegen te = new TileEngine(this, 60, 60); te.setTileFactory(new DemoTileFactory()); te.setMap(map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken DemoHero hero = new DemoHero(ce, te); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); addObject(new Enemy(), 1170, 410); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); if (BeginLevel.daarIsDeT == true) { addObject (new THUD(), 300, 50); } if (BeginLevel.daarIsDeO == true) { addObject (new OHUD(), 350, 50); } if (BeginLevel.daarIsDeP == true) { addObject (new PHUD(), 400, 50); } if (BeginLevel.daarIsDeJ == true) { addObject (new JHUD(), 450, 50); } if (BeginLevel.daarIsDeE == true) { addObject (new EHUD(), 500, 50); } } @Override public void act() { if (LevelSelector1.heeftT == true && BeginLevel.tIsEr == false){addObject (new THUD(), 300,50); BeginLevel.tIsEr = true; BeginLevel.daarIsDeT = true;} if (LevelSelector1.heeftO == true && BeginLevel.oIsEr == false) {addObject (new OHUD(), 350,50); BeginLevel.oIsEr = true; BeginLevel.daarIsDeO = true;} if (LevelSelector1.heeftP == true &&BeginLevel. pIsEr == false){addObject (new PHUD(), 400,50); BeginLevel.pIsEr = true; BeginLevel.daarIsDeP = true;} if (LevelSelector1.heeftJ == true && BeginLevel.jIsEr == false){addObject (new JHUD(), 450,50); BeginLevel.jIsEr = true; BeginLevel.daarIsDeJ = true;} if (LevelSelector1.heeftE == true && BeginLevel.eIsEr == false){addObject (new EHUD(), 500,50); BeginLevel.eIsEr = true; BeginLevel.daarIsDeE = true; }}}
ROCMondriaanTIN/project-greenfoot-game-TScollin
DemoWorld.java
3,659
// initialiseren van de TileEngine klasse om de map aan de world toe te voegen
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class DemoWorld extends World { // Declareren van CollisionEngine private CollisionEngine ce; // Declareren van TileEngine private TileEngine te; /** * Constructor for objects of class MyWorld. * */ public DemoWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg_gras.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, 17, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},}; // initialiseren van<SUF> te = new TileEngine(this, 60, 60); te.setTileFactory(new DemoTileFactory()); te.setMap(map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken DemoHero hero = new DemoHero(ce, te); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); addObject(new Enemy(), 1170, 410); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); if (BeginLevel.daarIsDeT == true) { addObject (new THUD(), 300, 50); } if (BeginLevel.daarIsDeO == true) { addObject (new OHUD(), 350, 50); } if (BeginLevel.daarIsDeP == true) { addObject (new PHUD(), 400, 50); } if (BeginLevel.daarIsDeJ == true) { addObject (new JHUD(), 450, 50); } if (BeginLevel.daarIsDeE == true) { addObject (new EHUD(), 500, 50); } } @Override public void act() { if (LevelSelector1.heeftT == true && BeginLevel.tIsEr == false){addObject (new THUD(), 300,50); BeginLevel.tIsEr = true; BeginLevel.daarIsDeT = true;} if (LevelSelector1.heeftO == true && BeginLevel.oIsEr == false) {addObject (new OHUD(), 350,50); BeginLevel.oIsEr = true; BeginLevel.daarIsDeO = true;} if (LevelSelector1.heeftP == true &&BeginLevel. pIsEr == false){addObject (new PHUD(), 400,50); BeginLevel.pIsEr = true; BeginLevel.daarIsDeP = true;} if (LevelSelector1.heeftJ == true && BeginLevel.jIsEr == false){addObject (new JHUD(), 450,50); BeginLevel.jIsEr = true; BeginLevel.daarIsDeJ = true;} if (LevelSelector1.heeftE == true && BeginLevel.eIsEr == false){addObject (new EHUD(), 500,50); BeginLevel.eIsEr = true; BeginLevel.daarIsDeE = true; }}}
True
False
1,444
2,037
25160_8
package heap.pairing; import heap.Element; import heap.EmptyHeapException; import heap.Heap; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; public class PairingHeap<T extends Comparable<T>> implements Heap<T> { PairingHeapElement<T> root; public PairingHeap() { root = null; } /** * @param value * De waarde die aan de heap moet toegevoegd worden * @return * Het toegevoegde element */ @Override public PairingHeapElement<T> insert(T value) { PairingHeapElement<T> l = new PairingHeapElement<>(value, this); if (root != null) { // Als de heap al elementen bevat: maak een nieuwe heap met het element en merge root = merge(root, l); } else { // Maak anders l het eerste element van de heap root = l; } // Geef het aangemaakte element terug return l; } /** * @return * Het kleinste element van de heap * @throws EmptyHeapException * Wanneer de heap leeg is */ @Override public PairingHeapElement<T> findMin() throws EmptyHeapException { if (root != null) { return root; } else { throw new EmptyHeapException(); } } /** * @return * De waarde van het kleinste element van de heap * @throws EmptyHeapException * Wanneer de heap leeg is */ @Override public T removeMin() throws EmptyHeapException { PairingHeapElement<T> min = findMin(); root = removeSubTree(min); return min.value(); } /** * Verwijderd de wortel van de deelboom met wortel root en geeft de nieuwe * deelboom na deze verwijderbewerking terug * @param root * De wortel van de deelboom * @return * Het resultaat van de verwijderbewerking */ PairingHeapElement<T> removeSubTree(PairingHeapElement<T> root) { // Nieuwe heap PairingHeapElement<T> result; if (root.child != null) { LinkedList<PairingHeapElement<T>> stack = new LinkedList<>(); // Van links naar rechts over kinderen verwijderd el gaan en deze 2 aan 2 mergen, daarna op stack pushen PairingHeapElement<T> curr = root.child; while (curr != null && curr.next != null) { curr.previous = null; curr.next.previous = null; PairingHeapElement<T> volg = curr.next.next; stack.push(merge(curr, curr.next)); curr = volg; } // Als het aantal kinderen oneven is, maak dit het tijdelijk resultaat if (curr != null) { result = curr; result.previous = null; } else { // Maak anders het tijdelijk resultaat het eerste element van de stack result = stack.pop(); } // Zolang stack niet leeg is pop element van stack en merge dit met resultaat while(stack.size() != 0) { PairingHeapElement<T> el1 = stack.pop(); result = merge(el1, result); } } else { result = null; } return result; } /** * Merged heap 1 met heap 2 * @param t1 * Heap 1 * @param t2 * Heap 2 * @return * De top van de nieuwe heap */ PairingHeapElement<T> merge(PairingHeapElement<T> t1, PairingHeapElement<T> t2) { if (t1 == null) { return t2; } else if(t2 == null) { return t1; } // Als t1 kleiner is dan t2 wordt t2 het linkerkind van t1 if (t1.value.compareTo(t2.value) < 0) { t2.previous = t1; t2.next = t1.child; if (t2.next != null) { t2.next.previous = t2; } t1.child = t2; return t1; } else { t1.previous = t2; t1.next = t2.child; if (t1.next != null) { t1.next.previous = t1; } t2.child = t1; return t2; } } }
amohoste/Project-Algorithms-and-Data-Structures-2
heap/pairing/PairingHeap.java
1,300
// Als het aantal kinderen oneven is, maak dit het tijdelijk resultaat
line_comment
nl
package heap.pairing; import heap.Element; import heap.EmptyHeapException; import heap.Heap; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; public class PairingHeap<T extends Comparable<T>> implements Heap<T> { PairingHeapElement<T> root; public PairingHeap() { root = null; } /** * @param value * De waarde die aan de heap moet toegevoegd worden * @return * Het toegevoegde element */ @Override public PairingHeapElement<T> insert(T value) { PairingHeapElement<T> l = new PairingHeapElement<>(value, this); if (root != null) { // Als de heap al elementen bevat: maak een nieuwe heap met het element en merge root = merge(root, l); } else { // Maak anders l het eerste element van de heap root = l; } // Geef het aangemaakte element terug return l; } /** * @return * Het kleinste element van de heap * @throws EmptyHeapException * Wanneer de heap leeg is */ @Override public PairingHeapElement<T> findMin() throws EmptyHeapException { if (root != null) { return root; } else { throw new EmptyHeapException(); } } /** * @return * De waarde van het kleinste element van de heap * @throws EmptyHeapException * Wanneer de heap leeg is */ @Override public T removeMin() throws EmptyHeapException { PairingHeapElement<T> min = findMin(); root = removeSubTree(min); return min.value(); } /** * Verwijderd de wortel van de deelboom met wortel root en geeft de nieuwe * deelboom na deze verwijderbewerking terug * @param root * De wortel van de deelboom * @return * Het resultaat van de verwijderbewerking */ PairingHeapElement<T> removeSubTree(PairingHeapElement<T> root) { // Nieuwe heap PairingHeapElement<T> result; if (root.child != null) { LinkedList<PairingHeapElement<T>> stack = new LinkedList<>(); // Van links naar rechts over kinderen verwijderd el gaan en deze 2 aan 2 mergen, daarna op stack pushen PairingHeapElement<T> curr = root.child; while (curr != null && curr.next != null) { curr.previous = null; curr.next.previous = null; PairingHeapElement<T> volg = curr.next.next; stack.push(merge(curr, curr.next)); curr = volg; } // Als het<SUF> if (curr != null) { result = curr; result.previous = null; } else { // Maak anders het tijdelijk resultaat het eerste element van de stack result = stack.pop(); } // Zolang stack niet leeg is pop element van stack en merge dit met resultaat while(stack.size() != 0) { PairingHeapElement<T> el1 = stack.pop(); result = merge(el1, result); } } else { result = null; } return result; } /** * Merged heap 1 met heap 2 * @param t1 * Heap 1 * @param t2 * Heap 2 * @return * De top van de nieuwe heap */ PairingHeapElement<T> merge(PairingHeapElement<T> t1, PairingHeapElement<T> t2) { if (t1 == null) { return t2; } else if(t2 == null) { return t1; } // Als t1 kleiner is dan t2 wordt t2 het linkerkind van t1 if (t1.value.compareTo(t2.value) < 0) { t2.previous = t1; t2.next = t1.child; if (t2.next != null) { t2.next.previous = t2; } t1.child = t2; return t1; } else { t1.previous = t2; t1.next = t2.child; if (t1.next != null) { t1.next.previous = t1; } t2.child = t1; return t2; } } }
True
False
1,447
3,992
73622_1
package bank.bankieren;_x000D_ _x000D_ import centralebank.ICentraleBank;_x000D_ import fontys.observer.Publisher;_x000D_ import fontys.observer.RemotePropertyListener;_x000D_ import fontys.util.*;_x000D_ import java.rmi.RemoteException;_x000D_ _x000D_ /**_x000D_ * @author 871059_x000D_ * _x000D_ */_x000D_ public interface IBank extends Publisher, RemotePropertyListener {_x000D_ /**_x000D_ * creatie van een nieuwe bankrekening; het gegenereerde bankrekeningnummer_x000D_ * is identificerend voor de nieuwe bankrekening; als de klant_x000D_ * geidentificeerd door naam en plaats nog niet bestaat wordt er ook een_x000D_ * nieuwe klant aangemaakt_x000D_ * _x000D_ * @param naam_x000D_ * van de eigenaar van de nieuwe bankrekening_x000D_ * @param plaats_x000D_ * de woonplaats van de eigenaar van de nieuwe bankrekening_x000D_ * @return -1 zodra naam of plaats een lege string of rekeningnummer niet_x000D_ * door centrale kon worden vrijgegeven en anders het nummer van de_x000D_ * gecreeerde bankrekening_x000D_ */_x000D_ int openRekening(String naam, String plaats) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * er wordt bedrag overgemaakt van de bankrekening met nummer bron naar de_x000D_ * bankrekening met nummer bestemming_x000D_ * _x000D_ * @param bron_x000D_ * @param bestemming_x000D_ * ongelijk aan bron_x000D_ * @param bedrag_x000D_ * is groter dan 0_x000D_ * @return <b>true</b> als de overmaking is gelukt, anders <b>false</b>_x000D_ * @throws NumberDoesntExistException_x000D_ * als een van de twee bankrekeningnummers onbekend is_x000D_ */_x000D_ boolean maakOver(int bron, int bestemming, Money bedrag)_x000D_ throws NumberDoesntExistException, RemoteException;_x000D_ _x000D_ /**_x000D_ * @param nr_x000D_ * @return de bankrekening met nummer nr mits bij deze bank bekend, anders null_x000D_ */_x000D_ IRekening getRekening(int nr) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * @return de naam van deze bank_x000D_ */_x000D_ String getName() throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Methode om de centrale bank te wijzigen_x000D_ * @throws RemoteException_x000D_ */_x000D_ void setCentraleBank(ICentraleBank centraleBank) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * @return Centrale bank die bij de bank hoort_x000D_ * @throws RemoteException_x000D_ */_x000D_ public ICentraleBank getCentraleBank() throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Voeg listener aan publisher_x000D_ * @param listener_x000D_ * @param property_x000D_ * @throws RemoteException_x000D_ * Als server niet kan worden gevonden_x000D_ */_x000D_ public void addListener(RemotePropertyListener listener, String property) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Voeg listener aan publisher_x000D_ * @param listener_x000D_ * @param property_x000D_ * @throws RemoteException_x000D_ * Als server niet kan worden gevonden_x000D_ */_x000D_ public void removeListener(RemotePropertyListener listener, String property) throws RemoteException;_x000D_ public void muteerCentraal(int reknr, Money money) throws RemoteException;_x000D_ }_x000D_
pieter888/fontys-gso-32
BankierenNoObserver/src/bank/bankieren/IBank.java
876
/**_x000D_ * creatie van een nieuwe bankrekening; het gegenereerde bankrekeningnummer_x000D_ * is identificerend voor de nieuwe bankrekening; als de klant_x000D_ * geidentificeerd door naam en plaats nog niet bestaat wordt er ook een_x000D_ * nieuwe klant aangemaakt_x000D_ * _x000D_ * @param naam_x000D_ * van de eigenaar van de nieuwe bankrekening_x000D_ * @param plaats_x000D_ * de woonplaats van de eigenaar van de nieuwe bankrekening_x000D_ * @return -1 zodra naam of plaats een lege string of rekeningnummer niet_x000D_ * door centrale kon worden vrijgegeven en anders het nummer van de_x000D_ * gecreeerde bankrekening_x000D_ */
block_comment
nl
package bank.bankieren;_x000D_ _x000D_ import centralebank.ICentraleBank;_x000D_ import fontys.observer.Publisher;_x000D_ import fontys.observer.RemotePropertyListener;_x000D_ import fontys.util.*;_x000D_ import java.rmi.RemoteException;_x000D_ _x000D_ /**_x000D_ * @author 871059_x000D_ * _x000D_ */_x000D_ public interface IBank extends Publisher, RemotePropertyListener {_x000D_ /**_x000D_ * creatie van een<SUF>*/_x000D_ int openRekening(String naam, String plaats) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * er wordt bedrag overgemaakt van de bankrekening met nummer bron naar de_x000D_ * bankrekening met nummer bestemming_x000D_ * _x000D_ * @param bron_x000D_ * @param bestemming_x000D_ * ongelijk aan bron_x000D_ * @param bedrag_x000D_ * is groter dan 0_x000D_ * @return <b>true</b> als de overmaking is gelukt, anders <b>false</b>_x000D_ * @throws NumberDoesntExistException_x000D_ * als een van de twee bankrekeningnummers onbekend is_x000D_ */_x000D_ boolean maakOver(int bron, int bestemming, Money bedrag)_x000D_ throws NumberDoesntExistException, RemoteException;_x000D_ _x000D_ /**_x000D_ * @param nr_x000D_ * @return de bankrekening met nummer nr mits bij deze bank bekend, anders null_x000D_ */_x000D_ IRekening getRekening(int nr) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * @return de naam van deze bank_x000D_ */_x000D_ String getName() throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Methode om de centrale bank te wijzigen_x000D_ * @throws RemoteException_x000D_ */_x000D_ void setCentraleBank(ICentraleBank centraleBank) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * @return Centrale bank die bij de bank hoort_x000D_ * @throws RemoteException_x000D_ */_x000D_ public ICentraleBank getCentraleBank() throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Voeg listener aan publisher_x000D_ * @param listener_x000D_ * @param property_x000D_ * @throws RemoteException_x000D_ * Als server niet kan worden gevonden_x000D_ */_x000D_ public void addListener(RemotePropertyListener listener, String property) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Voeg listener aan publisher_x000D_ * @param listener_x000D_ * @param property_x000D_ * @throws RemoteException_x000D_ * Als server niet kan worden gevonden_x000D_ */_x000D_ public void removeListener(RemotePropertyListener listener, String property) throws RemoteException;_x000D_ public void muteerCentraal(int reknr, Money money) throws RemoteException;_x000D_ }_x000D_
True
False
1,457
262
43986_1
package nl.bve.rabobank.parser; import java.io.File; import java.io.FileReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; final class TransactionParserXMLStAX implements TransactionParser { private XMLStreamReader xmlSr; TransactionParserXMLStAX(File transactionsFile) throws Exception { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlSr = xmlInputFactory.createXMLStreamReader(new FileReader(transactionsFile)); } @Override public Transaction nextTransaction() { try { // Een while-loop, omdat je misschien niet als eerste xml-element een 'record' tegenkomt. while (xmlSr.hasNext()) { int eventType = xmlSr.next(); if (eventType == XMLEvent.START_ELEMENT && xmlSr.getLocalName().equalsIgnoreCase("record")) { Transaction newTransaction = new Transaction(); // attribute 0, omdat het enige attribute de reference is. Mooier zou zijn om te checken of index 0 inderdaad de reference is. newTransaction.setReference(xmlSr.getAttributeValue(0)); // while-loop om in 1 keer alle gegevens van een transaction in te lezen while (xmlSr.hasNext()) { xmlSr.next(); if (xmlSr.getEventType() == XMLEvent.START_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("description")) newTransaction.setDescription(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("startBalance")) newTransaction.setStartBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("endBalance")) newTransaction.setEndBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("mutation")) newTransaction.setMutation(xmlSr.getElementText()); } if (xmlSr.getEventType() == XMLEvent.END_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("record")) { return newTransaction; } } } } } } catch (XMLStreamException ex) { ex.printStackTrace(); } return null; } }
BvEijkelenburg/RaboParser
src/main/java/nl/bve/rabobank/parser/TransactionParserXMLStAX.java
714
// attribute 0, omdat het enige attribute de reference is. Mooier zou zijn om te checken of index 0 inderdaad de reference is.
line_comment
nl
package nl.bve.rabobank.parser; import java.io.File; import java.io.FileReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; final class TransactionParserXMLStAX implements TransactionParser { private XMLStreamReader xmlSr; TransactionParserXMLStAX(File transactionsFile) throws Exception { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlSr = xmlInputFactory.createXMLStreamReader(new FileReader(transactionsFile)); } @Override public Transaction nextTransaction() { try { // Een while-loop, omdat je misschien niet als eerste xml-element een 'record' tegenkomt. while (xmlSr.hasNext()) { int eventType = xmlSr.next(); if (eventType == XMLEvent.START_ELEMENT && xmlSr.getLocalName().equalsIgnoreCase("record")) { Transaction newTransaction = new Transaction(); // attribute 0,<SUF> newTransaction.setReference(xmlSr.getAttributeValue(0)); // while-loop om in 1 keer alle gegevens van een transaction in te lezen while (xmlSr.hasNext()) { xmlSr.next(); if (xmlSr.getEventType() == XMLEvent.START_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("description")) newTransaction.setDescription(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("startBalance")) newTransaction.setStartBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("endBalance")) newTransaction.setEndBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("mutation")) newTransaction.setMutation(xmlSr.getElementText()); } if (xmlSr.getEventType() == XMLEvent.END_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("record")) { return newTransaction; } } } } } } catch (XMLStreamException ex) { ex.printStackTrace(); } return null; } }
True
False
1,458
666
7850_29
package nl.hanze.itann.ttt; // deze import hebben we nodig voor gebruikersinput – let daar maar niet op. import java.util.Scanner; /* EEN EXTRA VOORBEELD BIJ §7.6 VAN BLUEJ EDITIE 6: MULTI-DIMENSIONALE ARRAYS; Een multi-dimensionale array kun je het beste vergelijken met een spelbord. Dit is meestal een systeem waarbij coördinaten als (X,Y) kunnen worden weergegeven – denk aan een schaakbord waarbij je de positie van stukken weergeeft als bijvoorbeeld 'H3'. Om dit om een wat eenvoudiger manier duidelijk te maken, is onderstaand spel 'boter kaas en eieren' uitgeprogrammeerd. Dit heeft een bord als volgt: +------+------+------+ | (0,0 | (1,0 | (2,0 | +------+------+------+ | (0,1 | (1,1 | (2,1 | +------+------+------+ | (0,2 | (1,2 | (2,2 | +------+------+------+ Je ziet hier twee arrays lopen: één voor de X en één voor de Y. Beide lopen van 0 tot 2 (drie elementen). In de code wordt dit in het private veld 'board' bijgehouden, waarvan het data-type een twee-dimensionale array van char's is: private char[3][3] board ^ ^ | | X ----------- --------Y Je kunt dit spel spelen door het op te starten en dan de coördinaten in te vullen wanneer het programma daar om vraagt: als ik bijvoorbeeld een X wil zetten op het rechtsmiddelste vakje, typ ik 2,1 (zonder haakjes). Er is een minimale check op de input, want het gaat niet om een correcte werking; als het stuk gaat door een verkeerde input kun je vast wel bedenken waarom. Bestudeer de programmacode en het commentaar dat er tussendoor gegeven is. */ public class BoterKaasEieren { public static void main(String[] args) { new BoterKaasEieren(); } // Dit is het interessante veld. Een twee-dimensionale array die het speelveld bijhoudt. private char[][] board; // De huidige speler. Dit is ofwel een 'X' of een 'O' private char currentPlayerMark; //constructor public BoterKaasEieren() { board = new char[3][3]; currentPlayerMark = 'X'; initializeBoard(); playGame(); } // Dit is feitelijk de 'main loop'. Dit ding blijft lopen totdat het bord vol is // of er een winnaar is. private void playGame() { //De regels hieronder is om user-input op te vangen. Maak je daar niet druk om. //Van belang is dat de input wordt opgeslagen in de variable 'input'. Scanner reader = new Scanner(System.in); String input = ""; //De onderstaande loop wordt uitgevoerd zolang 'gameNotFinished' geen 'false' //teruggeeft (hoe heet zo'n conditie?). Dat kan omdat er in die loop een methode //wordt aangeroepen die de boel blokkeert tot iemand een input heeft gegeven. while (gameNotFinished()) { //we printen elke keer de nieuwe status van het speelbord even uit printBoard(); changePlayer(); // Hier geven we aan wie er aan de beurt is en wat hij/zij moet invullen. System.out.println("De beurt in aan "+currentPlayerMark); System.out.println("Geef positie op (x,y): "); //Deze methode blijft wachten totdat de gebruiker iets heeft ingeveoerd. //Hierom kunnen we deze loop laten blijven lopen zonder dat er continu //dingen op het scherm verschijnen. input = reader.next(); //We maken een array van Strings van de input – check de API van de string: // https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String) String[] coords = input.split(","); placeMark(coords); } // Even het winnende bord afdrukken printBoard(); //als we hier komen, hebben we die reader niet meer nodig, en het is wel netjes om //die even expliciet te sluiten. reader.close(); } private boolean placeMark(String[] coords) { //We gaan er even van uit dat er in de input twee getallen zijn gegeven. int col = Integer.parseInt(coords[0]); int row = Integer.parseInt(coords[1]); //Let op hoe we opnieuw door een twee-dimensionale array lopen if ((row >= 0) && (row < 3)) { if ((col >= 0) && (col < 3)) { if (board[row][col] == '-') { board[row][col] = currentPlayerMark; return true; } } } return false; } //Hier initialiseren we de twee-dimensionale array. We hebben dus twee for-lussen nodig: //voor elke array eentje. De variabel i loopt van 0 tot 2, net als de variabele j (dat //klopt ook, want we hebben dat ding geïnitialiseerd op char[3][3]). private void initializeBoard() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = '-'; // initieel is elk element een '-' } } //Even voor het gemak de exacte coördinaten weergeven printBoardCoords(); } private void changePlayer() { // hoe heet deze constructie? currentPlayerMark = (currentPlayerMark=='X') ? 'O' : 'X'; } private boolean gameNotFinished() { return !(isBoardFull() || checkForWin()); } private void printBoard() { System.out.println("+---+---+---+"); for (int i = 0; i < 3; i++) { System.out.print("| "); for (int j = 0; j < 3; j++) { System.out.print(board[i][j] + " | "); } System.out.println(); System.out.println("+---+---+---+"); } } private void printBoardCoords() { System.out.println("Vul de coördinaten in zonder haakjes, gescheiden door een komma."); System.out.println("De coördinaten in het bord zijn als volgt:"); System.out.println("+-------+-------+-------+"); for (int i = 0; i < 3; i++) { System.out.print("| "); for (int j = 0; j < 3; j++) { System.out.print("(" +j+","+i + ") | "); } System.out.println(); System.out.println("+-------+-------+-------+"); } } //Opnieuw hebben we hier een dubbele for-lus nodig, om door beide arrays heen te //loopen. We checken hier nu voor elk element wat er exact is zit, en als er nog ergens //een '-' voorkomt, is het bord nog niet vol (want initieel hebben we het bord volgezet //met een '-', in de methode initializeBoard) private boolean isBoardFull() { boolean isFull = true; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == '-') { isFull = false; //welke optimalisatie is hier nog mogelijk? } } } if (isFull) { System.out.println("Het bord is vol; eind van het spel."); return true; } return false; } // voor de rest: nevermind private boolean checkForWin() { if (checkRowsForWin() || checkColumnsForWin() || checkDiagonalsForWin()) { System.out.println("We hebben een winnaar: " +currentPlayerMark); return true; } return false; } private boolean checkRowsForWin() { for (int i = 0; i < 3; i++) { if (checkRowCol(board[i][0], board[i][1], board[i][2]) == true) { return true; } } return false; } private boolean checkColumnsForWin() { for (int i = 0; i < 3; i++) { if (checkRowCol(board[0][i], board[1][i], board[2][i]) == true) { return true; } } return false; } private boolean checkDiagonalsForWin() { return ((checkRowCol(board[0][0], board[1][1], board[2][2]) == true) || (checkRowCol(board[0][2], board[1][1], board[2][0]) == true)); } private boolean checkRowCol(char c1, char c2, char c3) { return ((c1 != '-') && (c1 == c2) && (c2 == c3)); } }
Hanzehogeschool-hbo-ict/boterkaaseieren
BoterKaasEieren.java
2,599
//loopen. We checken hier nu voor elk element wat er exact is zit, en als er nog ergens
line_comment
nl
package nl.hanze.itann.ttt; // deze import hebben we nodig voor gebruikersinput – let daar maar niet op. import java.util.Scanner; /* EEN EXTRA VOORBEELD BIJ §7.6 VAN BLUEJ EDITIE 6: MULTI-DIMENSIONALE ARRAYS; Een multi-dimensionale array kun je het beste vergelijken met een spelbord. Dit is meestal een systeem waarbij coördinaten als (X,Y) kunnen worden weergegeven – denk aan een schaakbord waarbij je de positie van stukken weergeeft als bijvoorbeeld 'H3'. Om dit om een wat eenvoudiger manier duidelijk te maken, is onderstaand spel 'boter kaas en eieren' uitgeprogrammeerd. Dit heeft een bord als volgt: +------+------+------+ | (0,0 | (1,0 | (2,0 | +------+------+------+ | (0,1 | (1,1 | (2,1 | +------+------+------+ | (0,2 | (1,2 | (2,2 | +------+------+------+ Je ziet hier twee arrays lopen: één voor de X en één voor de Y. Beide lopen van 0 tot 2 (drie elementen). In de code wordt dit in het private veld 'board' bijgehouden, waarvan het data-type een twee-dimensionale array van char's is: private char[3][3] board ^ ^ | | X ----------- --------Y Je kunt dit spel spelen door het op te starten en dan de coördinaten in te vullen wanneer het programma daar om vraagt: als ik bijvoorbeeld een X wil zetten op het rechtsmiddelste vakje, typ ik 2,1 (zonder haakjes). Er is een minimale check op de input, want het gaat niet om een correcte werking; als het stuk gaat door een verkeerde input kun je vast wel bedenken waarom. Bestudeer de programmacode en het commentaar dat er tussendoor gegeven is. */ public class BoterKaasEieren { public static void main(String[] args) { new BoterKaasEieren(); } // Dit is het interessante veld. Een twee-dimensionale array die het speelveld bijhoudt. private char[][] board; // De huidige speler. Dit is ofwel een 'X' of een 'O' private char currentPlayerMark; //constructor public BoterKaasEieren() { board = new char[3][3]; currentPlayerMark = 'X'; initializeBoard(); playGame(); } // Dit is feitelijk de 'main loop'. Dit ding blijft lopen totdat het bord vol is // of er een winnaar is. private void playGame() { //De regels hieronder is om user-input op te vangen. Maak je daar niet druk om. //Van belang is dat de input wordt opgeslagen in de variable 'input'. Scanner reader = new Scanner(System.in); String input = ""; //De onderstaande loop wordt uitgevoerd zolang 'gameNotFinished' geen 'false' //teruggeeft (hoe heet zo'n conditie?). Dat kan omdat er in die loop een methode //wordt aangeroepen die de boel blokkeert tot iemand een input heeft gegeven. while (gameNotFinished()) { //we printen elke keer de nieuwe status van het speelbord even uit printBoard(); changePlayer(); // Hier geven we aan wie er aan de beurt is en wat hij/zij moet invullen. System.out.println("De beurt in aan "+currentPlayerMark); System.out.println("Geef positie op (x,y): "); //Deze methode blijft wachten totdat de gebruiker iets heeft ingeveoerd. //Hierom kunnen we deze loop laten blijven lopen zonder dat er continu //dingen op het scherm verschijnen. input = reader.next(); //We maken een array van Strings van de input – check de API van de string: // https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String) String[] coords = input.split(","); placeMark(coords); } // Even het winnende bord afdrukken printBoard(); //als we hier komen, hebben we die reader niet meer nodig, en het is wel netjes om //die even expliciet te sluiten. reader.close(); } private boolean placeMark(String[] coords) { //We gaan er even van uit dat er in de input twee getallen zijn gegeven. int col = Integer.parseInt(coords[0]); int row = Integer.parseInt(coords[1]); //Let op hoe we opnieuw door een twee-dimensionale array lopen if ((row >= 0) && (row < 3)) { if ((col >= 0) && (col < 3)) { if (board[row][col] == '-') { board[row][col] = currentPlayerMark; return true; } } } return false; } //Hier initialiseren we de twee-dimensionale array. We hebben dus twee for-lussen nodig: //voor elke array eentje. De variabel i loopt van 0 tot 2, net als de variabele j (dat //klopt ook, want we hebben dat ding geïnitialiseerd op char[3][3]). private void initializeBoard() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = '-'; // initieel is elk element een '-' } } //Even voor het gemak de exacte coördinaten weergeven printBoardCoords(); } private void changePlayer() { // hoe heet deze constructie? currentPlayerMark = (currentPlayerMark=='X') ? 'O' : 'X'; } private boolean gameNotFinished() { return !(isBoardFull() || checkForWin()); } private void printBoard() { System.out.println("+---+---+---+"); for (int i = 0; i < 3; i++) { System.out.print("| "); for (int j = 0; j < 3; j++) { System.out.print(board[i][j] + " | "); } System.out.println(); System.out.println("+---+---+---+"); } } private void printBoardCoords() { System.out.println("Vul de coördinaten in zonder haakjes, gescheiden door een komma."); System.out.println("De coördinaten in het bord zijn als volgt:"); System.out.println("+-------+-------+-------+"); for (int i = 0; i < 3; i++) { System.out.print("| "); for (int j = 0; j < 3; j++) { System.out.print("(" +j+","+i + ") | "); } System.out.println(); System.out.println("+-------+-------+-------+"); } } //Opnieuw hebben we hier een dubbele for-lus nodig, om door beide arrays heen te //loopen. We<SUF> //een '-' voorkomt, is het bord nog niet vol (want initieel hebben we het bord volgezet //met een '-', in de methode initializeBoard) private boolean isBoardFull() { boolean isFull = true; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == '-') { isFull = false; //welke optimalisatie is hier nog mogelijk? } } } if (isFull) { System.out.println("Het bord is vol; eind van het spel."); return true; } return false; } // voor de rest: nevermind private boolean checkForWin() { if (checkRowsForWin() || checkColumnsForWin() || checkDiagonalsForWin()) { System.out.println("We hebben een winnaar: " +currentPlayerMark); return true; } return false; } private boolean checkRowsForWin() { for (int i = 0; i < 3; i++) { if (checkRowCol(board[i][0], board[i][1], board[i][2]) == true) { return true; } } return false; } private boolean checkColumnsForWin() { for (int i = 0; i < 3; i++) { if (checkRowCol(board[0][i], board[1][i], board[2][i]) == true) { return true; } } return false; } private boolean checkDiagonalsForWin() { return ((checkRowCol(board[0][0], board[1][1], board[2][2]) == true) || (checkRowCol(board[0][2], board[1][1], board[2][0]) == true)); } private boolean checkRowCol(char c1, char c2, char c3) { return ((c1 != '-') && (c1 == c2) && (c2 == c3)); } }
True
False
1,462
171
17292_2
/* * Copyright (C) 2016 - 2017 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.topnl; import org.locationtech.jts.io.ParseException; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.sql.SQLException; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.SAXException; /** * * @author Meine Toonen [email protected] */ public class Main { protected final static Log log = LogFactory.getLog(Main.class); // voeg deze dependency toe als je wilt draaien // <dependency> // <groupId>org.apache.commons</groupId> // <artifactId>commons-dbcp2</artifactId> // </dependency> public static void main (String[] args) throws Exception{ try { BasicDataSource ds = new BasicDataSource(); ds.setUrl("jdbc:postgresql://localhost:5432/topnl"); ds.setDriverClassName("org.postgresql.Driver"); // ds.setUsername("rsgb"); // ds.setPassword("rsgb"); // ds.setUrl("jdbc:oracle:thin:@b3p-demoserver:1521/ORCL"); // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUsername("top50nl"); // ds.setPassword("top50nl"); Processor p = new Processor(ds); // loadtopnl("/mnt/data/Documents/TopNL/Top50NL/TOP50NL_GML_Filechunks_november_2016/TOP50NL_GML_Filechunks", p, TopNLType.TOP50NL); //loadtopnl("/mnt/data/Documents/TopNL/Top10NL/TOP10NL_GML_Filechuncks_november_2016/TOP10NL_GML_Filechuncks", p, TopNLType.TOP10NL); loadtopnl("/mnt/data/Documents/TopNL/Tynaarlo/Top10NL", p, TopNLType.TOP10NL); //loadtopnl("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks", p, TopNLType.TOP100NL); //process("top250NL.gml", p); //process("Hoogte_top250nl.xml", TopNLType.TOP250NL, p); //process("Hoogte_top100nl.xml", TopNLType.TOP100NL, p); } catch (SAXException | ParserConfigurationException | TransformerException ex) { log.error("Cannot parse/convert/save entity: ", ex); } } private static void loadtopnl(String dir, Processor p, TopNLType type) throws Exception{ File f = new File (dir); FilenameFilter filter = (dir1, name) -> name.toLowerCase().endsWith(".gml"); /*File f = new File("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks/Top100NL_000002.gml"); p.importIntoDb(f.toURL(), TopNLType.TOP100NL);*/ File[] files = f.listFiles(filter); for (File file : files) { // String fileString = file.getCanonicalPath(); p.importIntoDb(file.toURI().toURL(), type); } } private static void process(String file, Processor p, TopNLType type) throws Exception { URL in = Main.class.getResource(file); p.importIntoDb(in, type); /* List obj = p.parse(in, type); List<TopNLEntity> entities = p.convert(obj, type); p.save(entities, type);*/ } }
B3Partners/brmo
brmo-topnl-loader/src/src-main/java/nl/b3p/topnl/Main.java
1,299
// voeg deze dependency toe als je wilt draaien
line_comment
nl
/* * Copyright (C) 2016 - 2017 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.topnl; import org.locationtech.jts.io.ParseException; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.sql.SQLException; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.SAXException; /** * * @author Meine Toonen [email protected] */ public class Main { protected final static Log log = LogFactory.getLog(Main.class); // voeg deze<SUF> // <dependency> // <groupId>org.apache.commons</groupId> // <artifactId>commons-dbcp2</artifactId> // </dependency> public static void main (String[] args) throws Exception{ try { BasicDataSource ds = new BasicDataSource(); ds.setUrl("jdbc:postgresql://localhost:5432/topnl"); ds.setDriverClassName("org.postgresql.Driver"); // ds.setUsername("rsgb"); // ds.setPassword("rsgb"); // ds.setUrl("jdbc:oracle:thin:@b3p-demoserver:1521/ORCL"); // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUsername("top50nl"); // ds.setPassword("top50nl"); Processor p = new Processor(ds); // loadtopnl("/mnt/data/Documents/TopNL/Top50NL/TOP50NL_GML_Filechunks_november_2016/TOP50NL_GML_Filechunks", p, TopNLType.TOP50NL); //loadtopnl("/mnt/data/Documents/TopNL/Top10NL/TOP10NL_GML_Filechuncks_november_2016/TOP10NL_GML_Filechuncks", p, TopNLType.TOP10NL); loadtopnl("/mnt/data/Documents/TopNL/Tynaarlo/Top10NL", p, TopNLType.TOP10NL); //loadtopnl("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks", p, TopNLType.TOP100NL); //process("top250NL.gml", p); //process("Hoogte_top250nl.xml", TopNLType.TOP250NL, p); //process("Hoogte_top100nl.xml", TopNLType.TOP100NL, p); } catch (SAXException | ParserConfigurationException | TransformerException ex) { log.error("Cannot parse/convert/save entity: ", ex); } } private static void loadtopnl(String dir, Processor p, TopNLType type) throws Exception{ File f = new File (dir); FilenameFilter filter = (dir1, name) -> name.toLowerCase().endsWith(".gml"); /*File f = new File("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks/Top100NL_000002.gml"); p.importIntoDb(f.toURL(), TopNLType.TOP100NL);*/ File[] files = f.listFiles(filter); for (File file : files) { // String fileString = file.getCanonicalPath(); p.importIntoDb(file.toURI().toURL(), type); } } private static void process(String file, Processor p, TopNLType type) throws Exception { URL in = Main.class.getResource(file); p.importIntoDb(in, type); /* List obj = p.parse(in, type); List<TopNLEntity> entities = p.convert(obj, type); p.save(entities, type);*/ } }
True
False
1,463
1,176
20905_1
/* * Copyright 2013 Netherlands eScience Center * * 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 nl.esciencecenter.eastroviz.flaggers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* Wanneer je informatie hebt in frequentierichting zou je ook kunnen overwegen om (iteratief?) te "smoothen" in die richting: dus eerst een eerste ongevoelige (sum)threshold om de grootste pieken eruit te halen, dan een lowpass filter (e.g. 1d Gaussian convolution) op de frequentierichting uitvoeren, thresholden+smoothen nogmaals herhalen op het verschil en dan een laatste keer sumthresholden. Daardoor "vergelijk" je kanalen onderling en wordt je ook gevoeliger voor veranderingen niet-broadband RFI. Wanneer je een "absolute" sumthreshold "broadband" detector + de gesmoothde spectrale detector combineert is dit is erg effectief, denk ik. Dit is natuurlijk een geavanceerdere thresholder en vast niet het eerste algoritme wat je wilt implementeren -- ik weet uberhaubt niet of het technisch mogelijk is op de blue gene, maar het is een idee. Het is niet zoo zwaar om dit te doen. */ public class PostCorrelationSmoothedSumThresholdFlagger extends PostCorrelationSumThresholdFlagger { private static final Logger logger = LoggerFactory.getLogger(PostCorrelationSumThresholdFlagger.class); public PostCorrelationSmoothedSumThresholdFlagger(final int nrChannels, final float baseSensitivity, final float SIREtaValue) { super(nrChannels, baseSensitivity, SIREtaValue); } // we have the data for one second, all frequencies in a subband. // if one of the polarizations exceeds the threshold, flag them all. @Override protected void flag(final float[] powers, final boolean[] flagged, final int pol) { calculateStatistics(powers, flagged); // sets mean, median, stdDev logger.trace("mean = " + getMean() + ", median = " + getMedian() + ", stdDev = " + getStdDev()); // first do an insensitive sumthreshold final float originalSensitivity = getBaseSensitivity(); setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive! sumThreshold1D(powers, flagged); // sets flags, and replaces flagged samples with threshold // smooth final float[] smoothedPower = oneDimensionalGausConvolution(powers, 0.5f); // 2nd param is sigma, heigth of the gauss curve // calculate difference final float[] diff = new float[getNrChannels()]; for (int i = 0; i < getNrChannels(); i++) { diff[i] = powers[i] - smoothedPower[i]; } // flag based on difference calculateStatistics(diff, flagged); // sets mean, median, stdDev setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive! sumThreshold1D(diff, flagged); // and one final pass on the flagged power calculateStatistics(powers, flagged); // sets mean, median, stdDev setBaseSensitivity(originalSensitivity * 0.80f); // higher number is less sensitive! sumThreshold1D(powers, flagged); setBaseSensitivity(originalSensitivity); } }
NLeSC/eAstroViz
src/nl/esciencecenter/eastroviz/flaggers/PostCorrelationSmoothedSumThresholdFlagger.java
1,038
/* Wanneer je informatie hebt in frequentierichting zou je ook kunnen overwegen om (iteratief?) te "smoothen" in die richting: dus eerst een eerste ongevoelige (sum)threshold om de grootste pieken eruit te halen, dan een lowpass filter (e.g. 1d Gaussian convolution) op de frequentierichting uitvoeren, thresholden+smoothen nogmaals herhalen op het verschil en dan een laatste keer sumthresholden. Daardoor "vergelijk" je kanalen onderling en wordt je ook gevoeliger voor veranderingen niet-broadband RFI. Wanneer je een "absolute" sumthreshold "broadband" detector + de gesmoothde spectrale detector combineert is dit is erg effectief, denk ik. Dit is natuurlijk een geavanceerdere thresholder en vast niet het eerste algoritme wat je wilt implementeren -- ik weet uberhaubt niet of het technisch mogelijk is op de blue gene, maar het is een idee. Het is niet zoo zwaar om dit te doen. */
block_comment
nl
/* * Copyright 2013 Netherlands eScience Center * * 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 nl.esciencecenter.eastroviz.flaggers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* Wanneer je informatie<SUF>*/ public class PostCorrelationSmoothedSumThresholdFlagger extends PostCorrelationSumThresholdFlagger { private static final Logger logger = LoggerFactory.getLogger(PostCorrelationSumThresholdFlagger.class); public PostCorrelationSmoothedSumThresholdFlagger(final int nrChannels, final float baseSensitivity, final float SIREtaValue) { super(nrChannels, baseSensitivity, SIREtaValue); } // we have the data for one second, all frequencies in a subband. // if one of the polarizations exceeds the threshold, flag them all. @Override protected void flag(final float[] powers, final boolean[] flagged, final int pol) { calculateStatistics(powers, flagged); // sets mean, median, stdDev logger.trace("mean = " + getMean() + ", median = " + getMedian() + ", stdDev = " + getStdDev()); // first do an insensitive sumthreshold final float originalSensitivity = getBaseSensitivity(); setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive! sumThreshold1D(powers, flagged); // sets flags, and replaces flagged samples with threshold // smooth final float[] smoothedPower = oneDimensionalGausConvolution(powers, 0.5f); // 2nd param is sigma, heigth of the gauss curve // calculate difference final float[] diff = new float[getNrChannels()]; for (int i = 0; i < getNrChannels(); i++) { diff[i] = powers[i] - smoothedPower[i]; } // flag based on difference calculateStatistics(diff, flagged); // sets mean, median, stdDev setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive! sumThreshold1D(diff, flagged); // and one final pass on the flagged power calculateStatistics(powers, flagged); // sets mean, median, stdDev setBaseSensitivity(originalSensitivity * 0.80f); // higher number is less sensitive! sumThreshold1D(powers, flagged); setBaseSensitivity(originalSensitivity); } }
True
False
1,464
1,077
46809_4
package User; import MixingProxy.MixingProxy; import Registrar.Registrar; import javafx.scene.paint.Color; import javax.xml.bind.DatatypeConverter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.rmi.RemoteException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.rmi.server.UnicastRemoteObject; import java.util.List; import java.util.Scanner; public class UserImpl extends UnicastRemoteObject implements User { private Registrar registrar; private MixingProxy mixingProxy; private Color colorAfterQrScan; private String phone; private String name; private String QRCode; private String metInfectedPerson; private ArrayList<byte[]> userTokens; private ArrayList<String> userLogs = new ArrayList<>(); private byte[] currentToken; public UserImpl(String name, String phone, Registrar registrar, MixingProxy mixingProxy) throws RemoteException { this.name = name; this.phone = phone; this.registrar = registrar; this.userTokens = new ArrayList<>(); this.mixingProxy = mixingProxy; } // Interface methods @Override public String getPhone() throws RemoteException { return phone; } @Override public String getName() throws RemoteException { return name; } @Override public void newDay(List<byte[]> newUserTokens, List<String[]> criticalTokens, LocalDate date) throws RemoteException { // New daily tokens this.userTokens.clear(); this.userTokens.addAll(newUserTokens); // Check if critical tokens are in logs ArrayList<String> logs = readLogs(); ArrayList<String> informedUserTokens = new ArrayList<>(); if(!criticalTokens.isEmpty()){ boolean informed = false; for(String[] sCt: criticalTokens ){ String criticalUserToken = sCt[0]; LocalDateTime timeFrom = LocalDateTime.parse(sCt[1]); LocalDateTime timeUntil = LocalDateTime.parse(sCt[2]); for(int i=0; i<logs.size(); i++) { String logFromString = logs.get(i).split("\\^")[0]; LocalDateTime logFrom = LocalDateTime.parse(logFromString); String QR = logs.get(i).split("\\^")[1]; String userToken = logs.get(i).split("\\^")[2]; i++; String logUntilString = logs.get(i).split("\\^")[0]; LocalDateTime logUntil = LocalDateTime.parse(logUntilString); if (criticalUserToken.equals(userToken) && !logUntil.isBefore(timeFrom) && !logFrom.isAfter(timeUntil)) { System.out.println("Je bent in contact gekomen met een positief getest persoon"); informedUserTokens.add(userToken); informed = true; break; } } if(informed){ break; } } mixingProxy.informedTokens(informedUserTokens); } } @Override public String scanQR(String qr) throws RemoteException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { // User Token this.currentToken = userTokens.get(0); //tijd LocalDate ld = registrar.getDate(); LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now()); //qr code loggen this.QRCode = qr; userLogs.add(ldt + "^" + qr + "^" + currentToken); System.out.println("Following log is added to user logs: " + ldt + "|" + qr + "|" + currentToken); writeToLogFile(ldt, qr, currentToken); //h value van qr code splitten om door te sturen in capsule String h = qr.substring(qr.lastIndexOf("|") + 1); boolean validityToken = mixingProxy.retrieveCapsule(phone, ld, h, currentToken); // Gebruikte token verwijderen userTokens.remove(0); //symbool toekennen indien jusite qr code scan //op basis van business nummer een kleur toekennen String businessNumber = qr.substring(qr.indexOf('|') + 1, qr.lastIndexOf('|')); generateColor(businessNumber); if(validityToken){ return "ok | " + ldt; } else return "not ok" + ldt; } @Override public String leaveCatering(UserImpl user, String qr) throws RemoteException { LocalDate ld = registrar.getDate(); LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now()); userLogs.add(ldt + "^" + qr); writeToLogFile(ldt, qr, currentToken); String h = qr.substring(qr.lastIndexOf("|") + 1); mixingProxy.retrieveExitCapsule(ld, h, currentToken); return "Successfully left catering"; } public void writeToLogFile(LocalDateTime ldt, String qr, byte[] currentToken){ String phoneForLog = phone.replace(" ", "_"); try { File logFile = new File("logs/log_" + phoneForLog + ".txt"); if (!logFile.exists()){ logFile.createNewFile(); } FileWriter logFW = new FileWriter("logs/log_" + phoneForLog + ".txt", true); logFW.write(ldt + "^" + qr + "^" + DatatypeConverter.printHexBinary(currentToken)); logFW.write("\n"); logFW.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } public void generateColor(String b){ switch (b) { case "1": this.colorAfterQrScan = Color.BLUE; break; case "2": this.colorAfterQrScan = Color.GREEN; break; case "3": this.colorAfterQrScan = Color.RED; break; case "4": this.colorAfterQrScan = Color.ORANGE; break; default: this.colorAfterQrScan = Color.BLACK; } } public Color getColorAfterQrScan() { return colorAfterQrScan; } public ArrayList<String> readLogs(){ String phoneForLog = phone.replace(" ", "_"); ArrayList<String> logs = new ArrayList<>(); try { File userLog = new File("logs/log_" + phoneForLog + ".txt"); if (!userLog.exists()){ userLog.createNewFile(); } Scanner userLogReader = new Scanner(userLog); while (userLogReader.hasNextLine()) { logs.add(userLogReader.nextLine()); } userLogReader.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } return logs; } //Setters en getters public ArrayList<byte[]> getUserTokens() { return userTokens; } }
MartijnVanderschelden/ProjectDistributedSystems2
src/User/UserImpl.java
2,053
// Gebruikte token verwijderen
line_comment
nl
package User; import MixingProxy.MixingProxy; import Registrar.Registrar; import javafx.scene.paint.Color; import javax.xml.bind.DatatypeConverter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.rmi.RemoteException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.rmi.server.UnicastRemoteObject; import java.util.List; import java.util.Scanner; public class UserImpl extends UnicastRemoteObject implements User { private Registrar registrar; private MixingProxy mixingProxy; private Color colorAfterQrScan; private String phone; private String name; private String QRCode; private String metInfectedPerson; private ArrayList<byte[]> userTokens; private ArrayList<String> userLogs = new ArrayList<>(); private byte[] currentToken; public UserImpl(String name, String phone, Registrar registrar, MixingProxy mixingProxy) throws RemoteException { this.name = name; this.phone = phone; this.registrar = registrar; this.userTokens = new ArrayList<>(); this.mixingProxy = mixingProxy; } // Interface methods @Override public String getPhone() throws RemoteException { return phone; } @Override public String getName() throws RemoteException { return name; } @Override public void newDay(List<byte[]> newUserTokens, List<String[]> criticalTokens, LocalDate date) throws RemoteException { // New daily tokens this.userTokens.clear(); this.userTokens.addAll(newUserTokens); // Check if critical tokens are in logs ArrayList<String> logs = readLogs(); ArrayList<String> informedUserTokens = new ArrayList<>(); if(!criticalTokens.isEmpty()){ boolean informed = false; for(String[] sCt: criticalTokens ){ String criticalUserToken = sCt[0]; LocalDateTime timeFrom = LocalDateTime.parse(sCt[1]); LocalDateTime timeUntil = LocalDateTime.parse(sCt[2]); for(int i=0; i<logs.size(); i++) { String logFromString = logs.get(i).split("\\^")[0]; LocalDateTime logFrom = LocalDateTime.parse(logFromString); String QR = logs.get(i).split("\\^")[1]; String userToken = logs.get(i).split("\\^")[2]; i++; String logUntilString = logs.get(i).split("\\^")[0]; LocalDateTime logUntil = LocalDateTime.parse(logUntilString); if (criticalUserToken.equals(userToken) && !logUntil.isBefore(timeFrom) && !logFrom.isAfter(timeUntil)) { System.out.println("Je bent in contact gekomen met een positief getest persoon"); informedUserTokens.add(userToken); informed = true; break; } } if(informed){ break; } } mixingProxy.informedTokens(informedUserTokens); } } @Override public String scanQR(String qr) throws RemoteException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { // User Token this.currentToken = userTokens.get(0); //tijd LocalDate ld = registrar.getDate(); LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now()); //qr code loggen this.QRCode = qr; userLogs.add(ldt + "^" + qr + "^" + currentToken); System.out.println("Following log is added to user logs: " + ldt + "|" + qr + "|" + currentToken); writeToLogFile(ldt, qr, currentToken); //h value van qr code splitten om door te sturen in capsule String h = qr.substring(qr.lastIndexOf("|") + 1); boolean validityToken = mixingProxy.retrieveCapsule(phone, ld, h, currentToken); // Gebruikte token<SUF> userTokens.remove(0); //symbool toekennen indien jusite qr code scan //op basis van business nummer een kleur toekennen String businessNumber = qr.substring(qr.indexOf('|') + 1, qr.lastIndexOf('|')); generateColor(businessNumber); if(validityToken){ return "ok | " + ldt; } else return "not ok" + ldt; } @Override public String leaveCatering(UserImpl user, String qr) throws RemoteException { LocalDate ld = registrar.getDate(); LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now()); userLogs.add(ldt + "^" + qr); writeToLogFile(ldt, qr, currentToken); String h = qr.substring(qr.lastIndexOf("|") + 1); mixingProxy.retrieveExitCapsule(ld, h, currentToken); return "Successfully left catering"; } public void writeToLogFile(LocalDateTime ldt, String qr, byte[] currentToken){ String phoneForLog = phone.replace(" ", "_"); try { File logFile = new File("logs/log_" + phoneForLog + ".txt"); if (!logFile.exists()){ logFile.createNewFile(); } FileWriter logFW = new FileWriter("logs/log_" + phoneForLog + ".txt", true); logFW.write(ldt + "^" + qr + "^" + DatatypeConverter.printHexBinary(currentToken)); logFW.write("\n"); logFW.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } public void generateColor(String b){ switch (b) { case "1": this.colorAfterQrScan = Color.BLUE; break; case "2": this.colorAfterQrScan = Color.GREEN; break; case "3": this.colorAfterQrScan = Color.RED; break; case "4": this.colorAfterQrScan = Color.ORANGE; break; default: this.colorAfterQrScan = Color.BLACK; } } public Color getColorAfterQrScan() { return colorAfterQrScan; } public ArrayList<String> readLogs(){ String phoneForLog = phone.replace(" ", "_"); ArrayList<String> logs = new ArrayList<>(); try { File userLog = new File("logs/log_" + phoneForLog + ".txt"); if (!userLog.exists()){ userLog.createNewFile(); } Scanner userLogReader = new Scanner(userLog); while (userLogReader.hasNextLine()) { logs.add(userLogReader.nextLine()); } userLogReader.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } return logs; } //Setters en getters public ArrayList<byte[]> getUserTokens() { return userTokens; } }
True
False
1,465
686
83986_7
package oop.voetbalmanager.model; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.jdom2.DataConversionException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class XMLreader { public XMLreader(){ } public Divisie readDivisie(String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); ArrayList<Team> teamList = new ArrayList<Team>(); String divisieNaam = ""; int speeldag = -1; int stand = -1; String avatarPath = ""; try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); //parse naam en get teamlist divisieNaam = divisieEl.getChildText("naam"); teamList = readTeamList(divisieEl); //parse speeldag speeldag = Integer.parseInt(divisieEl.getChildText("speeldag")); stand = Integer.parseInt(divisieEl.getChildText("stand")); avatarPath = divisieEl.getChildText("avatarPath"); } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } //maak divisie Divisie divisie = new Divisie(divisieNaam, teamList, speeldag, stand, avatarPath); return divisie; } public ArrayList<Team> readTeamList(Element divisie){ ArrayList<Team> teamList = new ArrayList<Team>(); //maak lijst van alle <team> List<Element> teamElementList = divisie.getChildren("team"); //<team> als element in arrraylist toevoegen for (int i = 0; i < teamElementList.size(); i++) { //parse teamNaam, rank en get spelerList Element teamEl = (Element) teamElementList.get(i); //parse naam, rank, spelerslijst, winst .... teamList.add(readTeam(teamEl)); } return teamList; } public Team readTeam(Element teamEl){ //parse naam, rank, spelerslijst, winst .... String teamNaam = teamEl.getChildText("naam"); int rank = Integer.parseInt(teamEl.getChildText("rank")); ArrayList<Speler> spelerList = readSpelerList(teamNaam, teamEl); int winst = Integer.parseInt(teamEl.getChildText("winst")); int verlies = Integer.parseInt(teamEl.getChildText("verlies")); int gelijkspel = Integer.parseInt(teamEl.getChildText("gelijkspel")); int doelsaldo = Integer.parseInt(teamEl.getChildText("doelsaldo")); int doeltegen = Integer.parseInt(teamEl.getChildText("doeltegen")); int doelvoor = Integer.parseInt(teamEl.getChildText("doelvoor")); double budget = Double.parseDouble(teamEl.getChildText("budget")); int score = Integer.parseInt(teamEl.getChildText("score")); Team team = new Team(teamNaam, rank, spelerList, winst, verlies, gelijkspel, doelsaldo, doeltegen, doelvoor, budget, score); return team; } public ArrayList<Speler> readSpelerList(String teamNaam, Element team){ ArrayList<Speler> spelerList = new ArrayList<Speler>(); //maak lijst van alle <team> List<Element> spelerElementList = team.getChildren("speler"); //<team> als element in arrraylist toevoegen for (int i = 0; i < spelerElementList.size(); i++) { //parse teamNaam, rank, get spelerList ... Element spelerEl = (Element) spelerElementList.get(i); spelerList.add(readSpeler(spelerEl)); } return spelerList; } public Speler readSpeler(Element spelerEl){ String spelerNaam = spelerEl.getChildText("naam"); int nummer=-1; try { nummer = spelerEl.getAttribute("id").getIntValue(); } catch (DataConversionException e) { e.printStackTrace(); } String type = spelerEl.getChildText("type"); int offense = Integer.parseInt(spelerEl.getChildText("offense")); int defence = Integer.parseInt(spelerEl.getChildText("defence")); int uithouding = Integer.parseInt(spelerEl.getChildText("uithouding")); String beschikbaarheid = spelerEl.getChildText("beschikbaarheid"); double prijs = Double.parseDouble(spelerEl.getChildText("prijs")); Speler speler = new Speler(spelerNaam, nummer, type, offense, defence, uithouding, beschikbaarheid, prijs); return speler; } public ArrayList<Opstelling> readOpstellingList(String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); ArrayList<Opstelling> opstellingen = new ArrayList<Opstelling>(); try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); Element opsteling = divisieEl.getChild("opstellingen"); //maak lijst van alle opstellingen List<Element> opstElementList = opsteling.getChildren("opstelling_posities"); //<opstelling> als element in arrraylist toevoegen for (int i = 0; i < opstElementList.size(); i++) { //parse teamNaam, rank, get spelerList ... Element opstEl = (Element) opstElementList.get(i); opstellingen.add(readOpstelling(opstEl)); } } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } //parse naam, rank, spelerslijst, winst .... return opstellingen; } public Opstelling readOpstelling(Element opstEl){ List<Element> positiesList = opstEl.getChildren(); ArrayList<Positie> posities = new ArrayList<Positie>(); for (int i = 1; i < positiesList.size(); i++) { int x = Integer.parseInt(positiesList.get(i).getText().split(",")[0]); int y = Integer.parseInt(positiesList.get(i).getText().split(",")[1]); String type = positiesList.get(i).getName(); type = type.substring(0, type.length()-1); Positie speler = new Positie(x, y, type); posities.add(speler); } Collections.sort(posities, new Comparator<Positie>() { @Override public int compare(Positie p1, Positie p2) { return Integer.compare(p2.getY(), p1.getY()); } }); //parse naam, spelerslijst .... Opstelling opstelling = new Opstelling(opstEl.getChildText("naam"), posities); return opstelling; } public Wedstrijdteam readWedstrijdteam(Team userteam, String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); Wedstrijdteam wteam = null; try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); Element wteamElement = divisieEl.getChild("Wedstrijdteam"); //parse naam, rank, spelerslijst, winst .... String opstelling = wteamElement.getChildText("opstelling"); int tactiek = Integer.parseInt(wteamElement.getChildText("tactiek")); String spelers = wteamElement.getChildText("spelers"); String gespeeldMet = wteamElement.getChildText("gespeeldMet"); if(userteam==null){ String teamNaam = wteamElement.getChildText("TeamNaam"); Team team = Divisie.findTeamByName(teamNaam); User.setTeam(team); wteam = new Wedstrijdteam(team); }else{ wteam = new Wedstrijdteam(userteam); } ArrayList<Speler> spelerList = new ArrayList<Speler>(); for(Speler s: wteam.getSpelerList()){ if(spelers.contains(s.getNaam())){ spelerList.add(s); } } if(spelerList.size()<1){ for(Speler s: wteam.getSpelerList()){ if(s.getType().contains("doelman")){ spelerList.add(s); break; } } for(Speler s: wteam.getSpelerList()){ if(!s.getType().contains("doelman")){ spelerList.add(s); } if(spelerList.size()==11){ break; } } } Collections.reverse(spelerList); Speler[] spelersArray = new Speler[11]; spelerList.toArray(spelersArray); ArrayList<Opstelling> opstellingen = readOpstellingList(infile); for(Opstelling op: opstellingen){ if(op.getNaam().equals(opstelling)){ wteam.setOpstelling(op); } } wteam.setTactiek(tactiek); wteam.setWSpelers(spelersArray); wteam.setGespeeldMet(gespeeldMet); System.out.println("xmlreader: "+gespeeldMet); } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } return wteam; } }
Hazinck/OOP-project
Voetbalmanager/src/oop/voetbalmanager/model/XMLreader.java
2,920
//maak lijst van alle <team>
line_comment
nl
package oop.voetbalmanager.model; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.jdom2.DataConversionException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class XMLreader { public XMLreader(){ } public Divisie readDivisie(String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); ArrayList<Team> teamList = new ArrayList<Team>(); String divisieNaam = ""; int speeldag = -1; int stand = -1; String avatarPath = ""; try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); //parse naam en get teamlist divisieNaam = divisieEl.getChildText("naam"); teamList = readTeamList(divisieEl); //parse speeldag speeldag = Integer.parseInt(divisieEl.getChildText("speeldag")); stand = Integer.parseInt(divisieEl.getChildText("stand")); avatarPath = divisieEl.getChildText("avatarPath"); } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } //maak divisie Divisie divisie = new Divisie(divisieNaam, teamList, speeldag, stand, avatarPath); return divisie; } public ArrayList<Team> readTeamList(Element divisie){ ArrayList<Team> teamList = new ArrayList<Team>(); //maak lijst van alle <team> List<Element> teamElementList = divisie.getChildren("team"); //<team> als element in arrraylist toevoegen for (int i = 0; i < teamElementList.size(); i++) { //parse teamNaam, rank en get spelerList Element teamEl = (Element) teamElementList.get(i); //parse naam, rank, spelerslijst, winst .... teamList.add(readTeam(teamEl)); } return teamList; } public Team readTeam(Element teamEl){ //parse naam, rank, spelerslijst, winst .... String teamNaam = teamEl.getChildText("naam"); int rank = Integer.parseInt(teamEl.getChildText("rank")); ArrayList<Speler> spelerList = readSpelerList(teamNaam, teamEl); int winst = Integer.parseInt(teamEl.getChildText("winst")); int verlies = Integer.parseInt(teamEl.getChildText("verlies")); int gelijkspel = Integer.parseInt(teamEl.getChildText("gelijkspel")); int doelsaldo = Integer.parseInt(teamEl.getChildText("doelsaldo")); int doeltegen = Integer.parseInt(teamEl.getChildText("doeltegen")); int doelvoor = Integer.parseInt(teamEl.getChildText("doelvoor")); double budget = Double.parseDouble(teamEl.getChildText("budget")); int score = Integer.parseInt(teamEl.getChildText("score")); Team team = new Team(teamNaam, rank, spelerList, winst, verlies, gelijkspel, doelsaldo, doeltegen, doelvoor, budget, score); return team; } public ArrayList<Speler> readSpelerList(String teamNaam, Element team){ ArrayList<Speler> spelerList = new ArrayList<Speler>(); //maak lijst<SUF> List<Element> spelerElementList = team.getChildren("speler"); //<team> als element in arrraylist toevoegen for (int i = 0; i < spelerElementList.size(); i++) { //parse teamNaam, rank, get spelerList ... Element spelerEl = (Element) spelerElementList.get(i); spelerList.add(readSpeler(spelerEl)); } return spelerList; } public Speler readSpeler(Element spelerEl){ String spelerNaam = spelerEl.getChildText("naam"); int nummer=-1; try { nummer = spelerEl.getAttribute("id").getIntValue(); } catch (DataConversionException e) { e.printStackTrace(); } String type = spelerEl.getChildText("type"); int offense = Integer.parseInt(spelerEl.getChildText("offense")); int defence = Integer.parseInt(spelerEl.getChildText("defence")); int uithouding = Integer.parseInt(spelerEl.getChildText("uithouding")); String beschikbaarheid = spelerEl.getChildText("beschikbaarheid"); double prijs = Double.parseDouble(spelerEl.getChildText("prijs")); Speler speler = new Speler(spelerNaam, nummer, type, offense, defence, uithouding, beschikbaarheid, prijs); return speler; } public ArrayList<Opstelling> readOpstellingList(String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); ArrayList<Opstelling> opstellingen = new ArrayList<Opstelling>(); try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); Element opsteling = divisieEl.getChild("opstellingen"); //maak lijst van alle opstellingen List<Element> opstElementList = opsteling.getChildren("opstelling_posities"); //<opstelling> als element in arrraylist toevoegen for (int i = 0; i < opstElementList.size(); i++) { //parse teamNaam, rank, get spelerList ... Element opstEl = (Element) opstElementList.get(i); opstellingen.add(readOpstelling(opstEl)); } } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } //parse naam, rank, spelerslijst, winst .... return opstellingen; } public Opstelling readOpstelling(Element opstEl){ List<Element> positiesList = opstEl.getChildren(); ArrayList<Positie> posities = new ArrayList<Positie>(); for (int i = 1; i < positiesList.size(); i++) { int x = Integer.parseInt(positiesList.get(i).getText().split(",")[0]); int y = Integer.parseInt(positiesList.get(i).getText().split(",")[1]); String type = positiesList.get(i).getName(); type = type.substring(0, type.length()-1); Positie speler = new Positie(x, y, type); posities.add(speler); } Collections.sort(posities, new Comparator<Positie>() { @Override public int compare(Positie p1, Positie p2) { return Integer.compare(p2.getY(), p1.getY()); } }); //parse naam, spelerslijst .... Opstelling opstelling = new Opstelling(opstEl.getChildText("naam"), posities); return opstelling; } public Wedstrijdteam readWedstrijdteam(Team userteam, String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); Wedstrijdteam wteam = null; try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); Element wteamElement = divisieEl.getChild("Wedstrijdteam"); //parse naam, rank, spelerslijst, winst .... String opstelling = wteamElement.getChildText("opstelling"); int tactiek = Integer.parseInt(wteamElement.getChildText("tactiek")); String spelers = wteamElement.getChildText("spelers"); String gespeeldMet = wteamElement.getChildText("gespeeldMet"); if(userteam==null){ String teamNaam = wteamElement.getChildText("TeamNaam"); Team team = Divisie.findTeamByName(teamNaam); User.setTeam(team); wteam = new Wedstrijdteam(team); }else{ wteam = new Wedstrijdteam(userteam); } ArrayList<Speler> spelerList = new ArrayList<Speler>(); for(Speler s: wteam.getSpelerList()){ if(spelers.contains(s.getNaam())){ spelerList.add(s); } } if(spelerList.size()<1){ for(Speler s: wteam.getSpelerList()){ if(s.getType().contains("doelman")){ spelerList.add(s); break; } } for(Speler s: wteam.getSpelerList()){ if(!s.getType().contains("doelman")){ spelerList.add(s); } if(spelerList.size()==11){ break; } } } Collections.reverse(spelerList); Speler[] spelersArray = new Speler[11]; spelerList.toArray(spelersArray); ArrayList<Opstelling> opstellingen = readOpstellingList(infile); for(Opstelling op: opstellingen){ if(op.getNaam().equals(opstelling)){ wteam.setOpstelling(op); } } wteam.setTactiek(tactiek); wteam.setWSpelers(spelersArray); wteam.setGespeeldMet(gespeeldMet); System.out.println("xmlreader: "+gespeeldMet); } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } return wteam; } }
True
False
1,467
4,385
213151_6
package com.vividsolutions.jump.workbench.imagery.geotiff;_x000D_ _x000D_ /*_x000D_ * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI _x000D_ * for visualizing and manipulating spatial features with geometry and attributes._x000D_ *_x000D_ * Copyright (C) 2003 Vivid Solutions_x000D_ * _x000D_ * This program is free software; you can redistribute it and/or_x000D_ * modify it under the terms of the GNU General Public License_x000D_ * as published by the Free Software Foundation; either version 2_x000D_ * of the License, or (at your option) any later version._x000D_ * _x000D_ * This program is distributed in the hope that it will be useful,_x000D_ * but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_ * GNU General Public License for more details._x000D_ * _x000D_ * You should have received a copy of the GNU General Public License_x000D_ * along with this program; if not, write to the Free Software_x000D_ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA._x000D_ * _x000D_ * For more information, contact:_x000D_ *_x000D_ * Vivid Solutions_x000D_ * Suite #1A_x000D_ * 2328 Government Street_x000D_ * Victoria BC V8T 5G5_x000D_ * Canada_x000D_ *_x000D_ * (250)385-6040_x000D_ * www.vividsolutions.com_x000D_ */_x000D_ import java.awt.geom.AffineTransform;_x000D_ import java.util.List;_x000D_ _x000D_ import org.geotiff.image.jai.GeoTIFFDescriptor;_x000D_ import org.geotiff.image.jai.GeoTIFFDirectory;_x000D_ import org.libtiff.jai.codec.XTIFF;_x000D_ import org.libtiff.jai.codec.XTIFFField;_x000D_ _x000D_ import com.vividsolutions.jts.geom.Coordinate;_x000D_ import com.vividsolutions.jump.util.FileUtil;_x000D_ _x000D_ public class GeoTIFFRaster extends GeoReferencedRaster_x000D_ {_x000D_ private final String MSG_GENERAL = "This is not a valid GeoTIFF file.";_x000D_ String fileName;_x000D_ _x000D_ boolean hoPatch = false;_x000D_ _x000D_ /**_x000D_ * Called by Java2XML_x000D_ */_x000D_ public GeoTIFFRaster(String imageFileLocation)_x000D_ throws Exception_x000D_ {_x000D_ super(imageFileLocation);_x000D_ registerWithJAI();_x000D_ readRasterfile();_x000D_ }_x000D_ _x000D_ private void registerWithJAI()_x000D_ {_x000D_ // Register the GeoTIFF descriptor with JAI._x000D_ GeoTIFFDescriptor.register();_x000D_ }_x000D_ _x000D_ private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception_x000D_ {_x000D_ // Find the ModelTiePoints field_x000D_ XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS);_x000D_ if (fieldModelTiePoints == null)_x000D_ throw new Exception("Missing tiepoints-tag in file.\n" + MSG_GENERAL);_x000D_ _x000D_ // Get the number of modeltiepoints_x000D_ // int numModelTiePoints = fieldModelTiePoints.getCount() / 6;_x000D_ _x000D_ // ToDo: alleen numModelTiePoints == 1 ondersteunen._x000D_ _x000D_ // Map the modeltiepoints from raster to model space_x000D_ _x000D_ // Read the tiepoints_x000D_ setCoorRasterTiff_tiepointLT(new Coordinate(fieldModelTiePoints_x000D_ .getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0));_x000D_ setCoorModel_tiepointLT(new Coordinate(fieldModelTiePoints.getAsDouble(3),_x000D_ fieldModelTiePoints.getAsDouble(4), 0));_x000D_ setEnvelope();_x000D_ // Find the ModelPixelScale field_x000D_ XTIFFField fieldModelPixelScale = dir_x000D_ .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE);_x000D_ if (fieldModelPixelScale == null)_x000D_ throw new Exception("Missing pixelscale-tag in file." + "\n"_x000D_ + MSG_GENERAL);_x000D_ _x000D_ setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0));_x000D_ setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1));_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return filename of the tiff worldfile_x000D_ */_x000D_ private String worldFileName()_x000D_ {_x000D_ int posDot = fileName.lastIndexOf('.');_x000D_ if (posDot == -1)_x000D_ {_x000D_ posDot = fileName.length();_x000D_ }_x000D_ return fileName.substring(0, posDot) + ".tfw";_x000D_ }_x000D_ _x000D_ private void parseWorldFile() throws Exception_x000D_ {_x000D_ // Get the name of the tiff worldfile._x000D_ String name = worldFileName();_x000D_ _x000D_ // Read the tags from the tiff worldfile._x000D_ List lines = FileUtil.getContents(name);_x000D_ double[] tags = new double[6];_x000D_ for (int i = 0; i < 6; i++)_x000D_ {_x000D_ String line = (String) lines.get(i);_x000D_ tags[i] = Double.parseDouble(line);_x000D_ }_x000D_ setAffineTransformation(new AffineTransform(tags));_x000D_ }_x000D_ _x000D_ protected void readRasterfile() throws Exception_x000D_ {_x000D_ // ImageCodec originalCodec = ImageCodec.getCodec("tiff");_x000D_ _x000D_ try_x000D_ {_x000D_ super.readRasterfile();_x000D_ _x000D_ // Get access to the tags and geokeys._x000D_ // First, get the TIFF directory_x000D_ GeoTIFFDirectory dir = (GeoTIFFDirectory) src_x000D_ .getProperty("tiff.directory");_x000D_ if (dir == null)_x000D_ throw new Exception("This is not a (geo)tiff file.");_x000D_ _x000D_ try_x000D_ {_x000D_ // Try to parse any embedded geotiff tags._x000D_ parseGeoTIFFDirectory(dir);_x000D_ } catch (Exception E)_x000D_ {_x000D_ // Embedded geotiff tags have not been found. Try_x000D_ // to use a geotiff world file._x000D_ try_x000D_ {_x000D_ parseWorldFile();_x000D_ } catch (Exception e)_x000D_ {_x000D_ throw new Exception(_x000D_ "Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL);_x000D_ }_x000D_ }_x000D_ } finally_x000D_ {_x000D_ }_x000D_ }_x000D_ _x000D_ }
stackmystack/newmotorbac
src-jump/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
1,666
// ToDo: alleen numModelTiePoints == 1 ondersteunen._x000D_
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff;_x000D_ _x000D_ /*_x000D_ * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI _x000D_ * for visualizing and manipulating spatial features with geometry and attributes._x000D_ *_x000D_ * Copyright (C) 2003 Vivid Solutions_x000D_ * _x000D_ * This program is free software; you can redistribute it and/or_x000D_ * modify it under the terms of the GNU General Public License_x000D_ * as published by the Free Software Foundation; either version 2_x000D_ * of the License, or (at your option) any later version._x000D_ * _x000D_ * This program is distributed in the hope that it will be useful,_x000D_ * but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_ * GNU General Public License for more details._x000D_ * _x000D_ * You should have received a copy of the GNU General Public License_x000D_ * along with this program; if not, write to the Free Software_x000D_ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA._x000D_ * _x000D_ * For more information, contact:_x000D_ *_x000D_ * Vivid Solutions_x000D_ * Suite #1A_x000D_ * 2328 Government Street_x000D_ * Victoria BC V8T 5G5_x000D_ * Canada_x000D_ *_x000D_ * (250)385-6040_x000D_ * www.vividsolutions.com_x000D_ */_x000D_ import java.awt.geom.AffineTransform;_x000D_ import java.util.List;_x000D_ _x000D_ import org.geotiff.image.jai.GeoTIFFDescriptor;_x000D_ import org.geotiff.image.jai.GeoTIFFDirectory;_x000D_ import org.libtiff.jai.codec.XTIFF;_x000D_ import org.libtiff.jai.codec.XTIFFField;_x000D_ _x000D_ import com.vividsolutions.jts.geom.Coordinate;_x000D_ import com.vividsolutions.jump.util.FileUtil;_x000D_ _x000D_ public class GeoTIFFRaster extends GeoReferencedRaster_x000D_ {_x000D_ private final String MSG_GENERAL = "This is not a valid GeoTIFF file.";_x000D_ String fileName;_x000D_ _x000D_ boolean hoPatch = false;_x000D_ _x000D_ /**_x000D_ * Called by Java2XML_x000D_ */_x000D_ public GeoTIFFRaster(String imageFileLocation)_x000D_ throws Exception_x000D_ {_x000D_ super(imageFileLocation);_x000D_ registerWithJAI();_x000D_ readRasterfile();_x000D_ }_x000D_ _x000D_ private void registerWithJAI()_x000D_ {_x000D_ // Register the GeoTIFF descriptor with JAI._x000D_ GeoTIFFDescriptor.register();_x000D_ }_x000D_ _x000D_ private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception_x000D_ {_x000D_ // Find the ModelTiePoints field_x000D_ XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS);_x000D_ if (fieldModelTiePoints == null)_x000D_ throw new Exception("Missing tiepoints-tag in file.\n" + MSG_GENERAL);_x000D_ _x000D_ // Get the number of modeltiepoints_x000D_ // int numModelTiePoints = fieldModelTiePoints.getCount() / 6;_x000D_ _x000D_ // ToDo: alleen<SUF> _x000D_ // Map the modeltiepoints from raster to model space_x000D_ _x000D_ // Read the tiepoints_x000D_ setCoorRasterTiff_tiepointLT(new Coordinate(fieldModelTiePoints_x000D_ .getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0));_x000D_ setCoorModel_tiepointLT(new Coordinate(fieldModelTiePoints.getAsDouble(3),_x000D_ fieldModelTiePoints.getAsDouble(4), 0));_x000D_ setEnvelope();_x000D_ // Find the ModelPixelScale field_x000D_ XTIFFField fieldModelPixelScale = dir_x000D_ .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE);_x000D_ if (fieldModelPixelScale == null)_x000D_ throw new Exception("Missing pixelscale-tag in file." + "\n"_x000D_ + MSG_GENERAL);_x000D_ _x000D_ setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0));_x000D_ setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1));_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return filename of the tiff worldfile_x000D_ */_x000D_ private String worldFileName()_x000D_ {_x000D_ int posDot = fileName.lastIndexOf('.');_x000D_ if (posDot == -1)_x000D_ {_x000D_ posDot = fileName.length();_x000D_ }_x000D_ return fileName.substring(0, posDot) + ".tfw";_x000D_ }_x000D_ _x000D_ private void parseWorldFile() throws Exception_x000D_ {_x000D_ // Get the name of the tiff worldfile._x000D_ String name = worldFileName();_x000D_ _x000D_ // Read the tags from the tiff worldfile._x000D_ List lines = FileUtil.getContents(name);_x000D_ double[] tags = new double[6];_x000D_ for (int i = 0; i < 6; i++)_x000D_ {_x000D_ String line = (String) lines.get(i);_x000D_ tags[i] = Double.parseDouble(line);_x000D_ }_x000D_ setAffineTransformation(new AffineTransform(tags));_x000D_ }_x000D_ _x000D_ protected void readRasterfile() throws Exception_x000D_ {_x000D_ // ImageCodec originalCodec = ImageCodec.getCodec("tiff");_x000D_ _x000D_ try_x000D_ {_x000D_ super.readRasterfile();_x000D_ _x000D_ // Get access to the tags and geokeys._x000D_ // First, get the TIFF directory_x000D_ GeoTIFFDirectory dir = (GeoTIFFDirectory) src_x000D_ .getProperty("tiff.directory");_x000D_ if (dir == null)_x000D_ throw new Exception("This is not a (geo)tiff file.");_x000D_ _x000D_ try_x000D_ {_x000D_ // Try to parse any embedded geotiff tags._x000D_ parseGeoTIFFDirectory(dir);_x000D_ } catch (Exception E)_x000D_ {_x000D_ // Embedded geotiff tags have not been found. Try_x000D_ // to use a geotiff world file._x000D_ try_x000D_ {_x000D_ parseWorldFile();_x000D_ } catch (Exception e)_x000D_ {_x000D_ throw new Exception(_x000D_ "Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL);_x000D_ }_x000D_ }_x000D_ } finally_x000D_ {_x000D_ }_x000D_ }_x000D_ _x000D_ }
True
False
1,468
1,857
25134_1
package gamejam.weapons; import gamejam.GameManager; import gamejam.event.EventConsumer; import gamejam.event.EventQueue; import gamejam.event.EventType; import gamejam.event.events.WeaponFireEvent; import gamejam.weapons.augmentation.WeaponAugmenter; import java.util.Random; public abstract class Weapon { protected float damage; protected float bulletSpeed; protected float bulletSize; protected int bulletAmount; protected float bulletAngleSpread; // firing logic stuffs protected int coolDownMs; protected long lastFireTime = 0; protected Random random = new Random(); public Weapon(float damage, float bulletSpeed, float bulletSize, int bulletAmount, float bulletAngleSpread, int coolDownMs) { this.damage = damage; this.bulletSpeed = bulletSpeed; this.bulletSize = bulletSize; this.bulletAmount = bulletAmount; this.bulletAngleSpread = bulletAngleSpread; this.coolDownMs = coolDownMs; EventConsumer<WeaponFireEvent> consumer = this::onWeaponFire; EventQueue.getInstance().registerConsumer(consumer, EventType.WEAPON_FIRED); } private void onWeaponFire(WeaponFireEvent event) { if (event.getWeapon() == this) { GameManager.getInstance().getCamera().startShake(); } } /** * Wanneer de {@link gamejam.objects.collidable.Player} isFiringWeapon true is, dan wordt deze methode aangeroepen. * @return True als het wapen werd afgevuurd, anders false (cooldown tijd nog niet verstreken). */ public boolean fire(float originX, float originY, float xVelocity, float yVelocity) { final long now = System.currentTimeMillis(); if (now - this.lastFireTime > this.coolDownMs) { this.lastFireTime = now; EventQueue.getInstance().invoke(new WeaponFireEvent(this)); return true; } else { return false; } } public void applyAugmentation(WeaponAugmenter weaponAugmenter) { weaponAugmenter.augment(this); } public void scaleBulletSize(float scale) { bulletSize = bulletSize * scale; } public void scaleBulletSize(int scale) { bulletSize += scale; } public void scaleBulletDamage(float scale) { damage = damage * scale; } public void scaleBulletDamage(int scale) { damage += scale; } public void addBulletAmount(int amount) { this.bulletAmount += amount; } public void addBulletSpeed(int amount) { this.bulletSpeed += amount; } public float getDamage() { return damage; } public int getCoolDownMs() { return coolDownMs; } public void setCoolDownMs(int coolDownMs) { this.coolDownMs = coolDownMs; } public void augmentExplosion(int initialAmount, int addAmount) { } }
Vulcanostrol/lipsum-game-2022
core/src/gamejam/weapons/Weapon.java
835
/** * Wanneer de {@link gamejam.objects.collidable.Player} isFiringWeapon true is, dan wordt deze methode aangeroepen. * @return True als het wapen werd afgevuurd, anders false (cooldown tijd nog niet verstreken). */
block_comment
nl
package gamejam.weapons; import gamejam.GameManager; import gamejam.event.EventConsumer; import gamejam.event.EventQueue; import gamejam.event.EventType; import gamejam.event.events.WeaponFireEvent; import gamejam.weapons.augmentation.WeaponAugmenter; import java.util.Random; public abstract class Weapon { protected float damage; protected float bulletSpeed; protected float bulletSize; protected int bulletAmount; protected float bulletAngleSpread; // firing logic stuffs protected int coolDownMs; protected long lastFireTime = 0; protected Random random = new Random(); public Weapon(float damage, float bulletSpeed, float bulletSize, int bulletAmount, float bulletAngleSpread, int coolDownMs) { this.damage = damage; this.bulletSpeed = bulletSpeed; this.bulletSize = bulletSize; this.bulletAmount = bulletAmount; this.bulletAngleSpread = bulletAngleSpread; this.coolDownMs = coolDownMs; EventConsumer<WeaponFireEvent> consumer = this::onWeaponFire; EventQueue.getInstance().registerConsumer(consumer, EventType.WEAPON_FIRED); } private void onWeaponFire(WeaponFireEvent event) { if (event.getWeapon() == this) { GameManager.getInstance().getCamera().startShake(); } } /** * Wanneer de {@link<SUF>*/ public boolean fire(float originX, float originY, float xVelocity, float yVelocity) { final long now = System.currentTimeMillis(); if (now - this.lastFireTime > this.coolDownMs) { this.lastFireTime = now; EventQueue.getInstance().invoke(new WeaponFireEvent(this)); return true; } else { return false; } } public void applyAugmentation(WeaponAugmenter weaponAugmenter) { weaponAugmenter.augment(this); } public void scaleBulletSize(float scale) { bulletSize = bulletSize * scale; } public void scaleBulletSize(int scale) { bulletSize += scale; } public void scaleBulletDamage(float scale) { damage = damage * scale; } public void scaleBulletDamage(int scale) { damage += scale; } public void addBulletAmount(int amount) { this.bulletAmount += amount; } public void addBulletSpeed(int amount) { this.bulletSpeed += amount; } public float getDamage() { return damage; } public int getCoolDownMs() { return coolDownMs; } public void setCoolDownMs(int coolDownMs) { this.coolDownMs = coolDownMs; } public void augmentExplosion(int initialAmount, int addAmount) { } }
True
False
1,469
2,320
105214_1
package nl.hva.ict.ss.pathfinding.weigthedgraph; import java.util.LinkedList; import nl.hva.ict.ss.pathfinding.tileworld.TileType; import nl.hva.ict.ss.pathfinding.tileworld.TileWorldUtil; /** * The {@code EdgeWeightedDigraph} class represents a edge-weighted * digraph of vertices named 0 through <em>V</em> - 1, where each * directed edge is of type {@link DirectedEdge} and has a real-valued weight. * It supports the following two primary operations: add a directed edge * to the digraph and iterate over all of edges incident from a given vertex. * It also provides * methods for returning the number of vertices <em>V</em> and the number * of edges <em>E</em>. Parallel edges and self-loops are permitted. * <p> * This implementation uses an adjacency-lists representation, which * is a vertex-indexed array of @link{Bag} objects. * All operations take constant time (in the worst case) except * iterating over the edges incident from a given vertex, which takes * time proportional to the number of such edges. * <p> * For additional documentation, * see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * Overgenomen uit de library algs4-package.jar van Robert Sedgwick * Aanpassingen specifiek t.b.v. PO2 Sorting&amp;Searching * * @author Robert Sedgewick * @author Kevin Wayne * @author Eric Ravestein * @author Nico Tromp */ public class EdgeWeightedDigraph { private final int V; private int E; private final int startIndex; private final int endIndex; private final LinkedList<DirectedEdge>[] adj; private final TileWorldUtil t; private final int breedte; private final int hoogte; /** * Constructor maakt een Digraph aan met V knooppunten (vertices) * Direct overgenomen uit Sedgwick. T.b.v. Floyd-Warshall * @param V aantal knooppunten */ public EdgeWeightedDigraph(int V) { if (V < 0) { throw new IllegalArgumentException("Number of vertices in a Digraph must be nonnegative"); } this.V = V; this.E = 0; hoogte = 0; breedte = 0; t = null; startIndex = 0; endIndex = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; for (int v = 0; v < V; v++) { adj[v] = new LinkedList<DirectedEdge>(); } } /** * Constructor. * Leest de TileWorldUtil in van bitmap fileName+".png" en * maakt de adjacency list adj * * @param fileName filenaam van de bitmap */ public EdgeWeightedDigraph(String fileName) { t = new TileWorldUtil(fileName + ".png"); // Aantal knopen hoogte = t.getHeight(); breedte = t.getWidth(); this.V = hoogte * breedte; // Start- en Eindindex this.startIndex = t.findStartIndex(); this.endIndex = t.findEndIndex(); this.E = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; int v; for (v = 0; v < V; v++) { adj[v] = findAdjacent(v); } } /** * getter voor het aantal knooppunten * @return aantal knooppunten */ public int V() { return V; } /** * Bewaart de bitmap onder de naam fileName. * @param fileName naam van de bitmap */ public void save(String fileName) { t.save(fileName); } /** * Maakt een Digraph met een adjacency matrix in plaats van een * adjacencylist. * Nodig voor Floyd=Warshall algoritme. * * @return een Digraph met Adjacencymatrix in plaats van list. */ public AdjMatrixEdgeWeightedDigraph createAdjMatrixEdgeWeightedDigraph() { AdjMatrixEdgeWeightedDigraph g; Iterable<DirectedEdge> edges; g = new AdjMatrixEdgeWeightedDigraph(V); edges = edges(); for (DirectedEdge d : edges) { g.addEdge(d); } return g; } /** * Zoekt alle aanliggende knoopunten van knooppunt v. * * @param v het te onderzoeken knooppunt * @return LinkedList van alle aanliggende (=bereikbare) * knooppunten met de cost om daar te komen. */ private LinkedList<DirectedEdge> findAdjacent(int v) { int x = t.oneDimToTwoDimXCoordinate(v); int y = t.oneDimToTwoDimYCoordinate(v); LinkedList<DirectedEdge> b = new LinkedList<DirectedEdge>(); if (x > 0) { // naar Links b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y), t.getTileType(x - 1, y).getCost())); if (y > 0) { // Links onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y - 1), t.getTileType(x - 1, y - 1).getDiagonalCost())); } if (y < hoogte - 1) { // Links boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y + 1), t.getTileType(x - 1, y + 1).getDiagonalCost())); } } if (x < breedte - 1) { // Rechts b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y), t.getTileType(x + 1, y).getCost())); if (y > 0) { // Rechts onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y - 1), t.getTileType(x + 1, y - 1).getDiagonalCost())); } if (y < hoogte - 1) { // Rechts boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y + 1), t.getTileType(x + 1, y + 1).getDiagonalCost())); } } if (y > 0) { // Onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y - 1), t.getTileType(x, y - 1).getCost())); } if (y < hoogte - 1) { // Boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y + 1), t.getTileType(x, y + 1).getCost())); } return b; } /** * Geeft de x coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getX(int v) { return t.oneDimToTwoDimXCoordinate(v); } /** * Geeft de y coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getY(int v) { return t.oneDimToTwoDimYCoordinate(v); } /** * Geeft de index in de adjacency list van het knooppunt dat in de TileWorldUtil t een coordinaat (x,y) heeft. * @param x x-coordinaat van te onderzoeken punt * @param y y-coordinaat van te onderzoeken punt * @return index van dit punt in de adjacencylist adj */ public int getIndex(int x, int y) { return t.twoDimIndexToOneDimIndex(x, y); } /** * Bepaalt alle aanliggende edges van knooppunt v * @param v het te onderzoeken knooppunt * @return lijst van edges die beginnen of eindigen in v */ public Iterable<DirectedEdge> adj(int v) { return adj[v]; } /** * Maakt een grote list van alle edges in de Digraph * @return LinkedList met alle edges */ public Iterable<DirectedEdge> edges() { LinkedList<DirectedEdge> list = new LinkedList<>(); for (int v = 0; v < V; v++) { for (DirectedEdge e : adj[v]) { list.add(e); } } return list; } /** * getter voor het Startpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getStart() { return (startIndex); } /** * getter voor het Eindpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getEnd() { return (endIndex); } /** * Laat de bitmap zien in een jFrame * @param filename naam van de bitmap * @param title aanvullende titel ter specificatie van de bitmap */ public void show(String filename, String title) { t.show(filename + ".png " + title, 10, 0, 0); } /** * Tekent het pad sp in de juiste kleur in de bitmap. * @param sp het te tekenen pad */ public void tekenPad(Iterable<DirectedEdge> sp) { for (DirectedEdge de : sp) { int x = t.oneDimToTwoDimXCoordinate(de.from()); int y = t.oneDimToTwoDimYCoordinate(de.from()); t.setTileType(x, y, TileType.PATH); } } public TileType markAsVisited(int v) { int x = t.oneDimToTwoDimXCoordinate(v); int y = t.oneDimToTwoDimYCoordinate(v); TileType currentType = t.getTileType(x, y); t.setTileType(x, y, TileType.UNKNOWN); return currentType; } /** * Adds the directed edge e to the edge-weighted digraph. * * Uit Sedgwick: tbv Floyd-Warshall * @param e the edge */ public void addEdge(DirectedEdge e) { int v = e.from(); adj[v].add(e); E++; } }
buracc/Sorting-Searching
Assignment-2/src/main/java/nl/hva/ict/ss/pathfinding/weigthedgraph/EdgeWeightedDigraph.java
3,109
/** * Constructor maakt een Digraph aan met V knooppunten (vertices) * Direct overgenomen uit Sedgwick. T.b.v. Floyd-Warshall * @param V aantal knooppunten */
block_comment
nl
package nl.hva.ict.ss.pathfinding.weigthedgraph; import java.util.LinkedList; import nl.hva.ict.ss.pathfinding.tileworld.TileType; import nl.hva.ict.ss.pathfinding.tileworld.TileWorldUtil; /** * The {@code EdgeWeightedDigraph} class represents a edge-weighted * digraph of vertices named 0 through <em>V</em> - 1, where each * directed edge is of type {@link DirectedEdge} and has a real-valued weight. * It supports the following two primary operations: add a directed edge * to the digraph and iterate over all of edges incident from a given vertex. * It also provides * methods for returning the number of vertices <em>V</em> and the number * of edges <em>E</em>. Parallel edges and self-loops are permitted. * <p> * This implementation uses an adjacency-lists representation, which * is a vertex-indexed array of @link{Bag} objects. * All operations take constant time (in the worst case) except * iterating over the edges incident from a given vertex, which takes * time proportional to the number of such edges. * <p> * For additional documentation, * see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * Overgenomen uit de library algs4-package.jar van Robert Sedgwick * Aanpassingen specifiek t.b.v. PO2 Sorting&amp;Searching * * @author Robert Sedgewick * @author Kevin Wayne * @author Eric Ravestein * @author Nico Tromp */ public class EdgeWeightedDigraph { private final int V; private int E; private final int startIndex; private final int endIndex; private final LinkedList<DirectedEdge>[] adj; private final TileWorldUtil t; private final int breedte; private final int hoogte; /** * Constructor maakt een<SUF>*/ public EdgeWeightedDigraph(int V) { if (V < 0) { throw new IllegalArgumentException("Number of vertices in a Digraph must be nonnegative"); } this.V = V; this.E = 0; hoogte = 0; breedte = 0; t = null; startIndex = 0; endIndex = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; for (int v = 0; v < V; v++) { adj[v] = new LinkedList<DirectedEdge>(); } } /** * Constructor. * Leest de TileWorldUtil in van bitmap fileName+".png" en * maakt de adjacency list adj * * @param fileName filenaam van de bitmap */ public EdgeWeightedDigraph(String fileName) { t = new TileWorldUtil(fileName + ".png"); // Aantal knopen hoogte = t.getHeight(); breedte = t.getWidth(); this.V = hoogte * breedte; // Start- en Eindindex this.startIndex = t.findStartIndex(); this.endIndex = t.findEndIndex(); this.E = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; int v; for (v = 0; v < V; v++) { adj[v] = findAdjacent(v); } } /** * getter voor het aantal knooppunten * @return aantal knooppunten */ public int V() { return V; } /** * Bewaart de bitmap onder de naam fileName. * @param fileName naam van de bitmap */ public void save(String fileName) { t.save(fileName); } /** * Maakt een Digraph met een adjacency matrix in plaats van een * adjacencylist. * Nodig voor Floyd=Warshall algoritme. * * @return een Digraph met Adjacencymatrix in plaats van list. */ public AdjMatrixEdgeWeightedDigraph createAdjMatrixEdgeWeightedDigraph() { AdjMatrixEdgeWeightedDigraph g; Iterable<DirectedEdge> edges; g = new AdjMatrixEdgeWeightedDigraph(V); edges = edges(); for (DirectedEdge d : edges) { g.addEdge(d); } return g; } /** * Zoekt alle aanliggende knoopunten van knooppunt v. * * @param v het te onderzoeken knooppunt * @return LinkedList van alle aanliggende (=bereikbare) * knooppunten met de cost om daar te komen. */ private LinkedList<DirectedEdge> findAdjacent(int v) { int x = t.oneDimToTwoDimXCoordinate(v); int y = t.oneDimToTwoDimYCoordinate(v); LinkedList<DirectedEdge> b = new LinkedList<DirectedEdge>(); if (x > 0) { // naar Links b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y), t.getTileType(x - 1, y).getCost())); if (y > 0) { // Links onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y - 1), t.getTileType(x - 1, y - 1).getDiagonalCost())); } if (y < hoogte - 1) { // Links boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y + 1), t.getTileType(x - 1, y + 1).getDiagonalCost())); } } if (x < breedte - 1) { // Rechts b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y), t.getTileType(x + 1, y).getCost())); if (y > 0) { // Rechts onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y - 1), t.getTileType(x + 1, y - 1).getDiagonalCost())); } if (y < hoogte - 1) { // Rechts boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y + 1), t.getTileType(x + 1, y + 1).getDiagonalCost())); } } if (y > 0) { // Onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y - 1), t.getTileType(x, y - 1).getCost())); } if (y < hoogte - 1) { // Boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y + 1), t.getTileType(x, y + 1).getCost())); } return b; } /** * Geeft de x coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getX(int v) { return t.oneDimToTwoDimXCoordinate(v); } /** * Geeft de y coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getY(int v) { return t.oneDimToTwoDimYCoordinate(v); } /** * Geeft de index in de adjacency list van het knooppunt dat in de TileWorldUtil t een coordinaat (x,y) heeft. * @param x x-coordinaat van te onderzoeken punt * @param y y-coordinaat van te onderzoeken punt * @return index van dit punt in de adjacencylist adj */ public int getIndex(int x, int y) { return t.twoDimIndexToOneDimIndex(x, y); } /** * Bepaalt alle aanliggende edges van knooppunt v * @param v het te onderzoeken knooppunt * @return lijst van edges die beginnen of eindigen in v */ public Iterable<DirectedEdge> adj(int v) { return adj[v]; } /** * Maakt een grote list van alle edges in de Digraph * @return LinkedList met alle edges */ public Iterable<DirectedEdge> edges() { LinkedList<DirectedEdge> list = new LinkedList<>(); for (int v = 0; v < V; v++) { for (DirectedEdge e : adj[v]) { list.add(e); } } return list; } /** * getter voor het Startpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getStart() { return (startIndex); } /** * getter voor het Eindpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getEnd() { return (endIndex); } /** * Laat de bitmap zien in een jFrame * @param filename naam van de bitmap * @param title aanvullende titel ter specificatie van de bitmap */ public void show(String filename, String title) { t.show(filename + ".png " + title, 10, 0, 0); } /** * Tekent het pad sp in de juiste kleur in de bitmap. * @param sp het te tekenen pad */ public void tekenPad(Iterable<DirectedEdge> sp) { for (DirectedEdge de : sp) { int x = t.oneDimToTwoDimXCoordinate(de.from()); int y = t.oneDimToTwoDimYCoordinate(de.from()); t.setTileType(x, y, TileType.PATH); } } public TileType markAsVisited(int v) { int x = t.oneDimToTwoDimXCoordinate(v); int y = t.oneDimToTwoDimYCoordinate(v); TileType currentType = t.getTileType(x, y); t.setTileType(x, y, TileType.UNKNOWN); return currentType; } /** * Adds the directed edge e to the edge-weighted digraph. * * Uit Sedgwick: tbv Floyd-Warshall * @param e the edge */ public void addEdge(DirectedEdge e) { int v = e.from(); adj[v].add(e); E++; } }
True
False
1,473
2,118
41146_4
/** * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * * 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 * * https://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.pkl.core; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.stream.StreamSupport; import org.pkl.core.packages.PackageAssetUri; import org.pkl.core.runtime.VmContext; import org.pkl.core.settings.PklSettings; import org.pkl.core.util.IoUtils; /** Static factory for stack frame transformers. */ public final class StackFrameTransformers { private StackFrameTransformers() {} public static final StackFrameTransformer empty = s -> s; public static final StackFrameTransformer convertStdLibUrlToExternalUrl = frame -> { var uri = frame.getModuleUri(); if (uri.startsWith("pkl:")) { var moduleName = uri.substring(4); return frame.withModuleUri( Release.current() .sourceCode() .getFilePage("stdlib/" + moduleName + ".pkl#L" + frame.getStartLine())); } return frame; }; public static final StackFrameTransformer replacePackageUriWithSourceCodeUrl = frame -> { var uri = URI.create(frame.getModuleUri()); if (!uri.getScheme().equalsIgnoreCase("package")) { return frame; } try { var assetUri = new PackageAssetUri(uri); var packageResolver = VmContext.get(null).getPackageResolver(); assert packageResolver != null; var pkg = packageResolver.getDependencyMetadata(assetUri.getPackageUri(), null); var sourceCode = pkg.getSourceCodeUrlScheme(); if (sourceCode == null) { return frame; } return transformUri(frame, uri.getFragment(), sourceCode); } catch (IOException | URISyntaxException | SecurityManagerException e) { // should never get here. by this point, we should have already performed all validation // and downloaded all assets. throw PklBugException.unreachableCode(); } }; public static final StackFrameTransformer fromServiceProviders = loadFromServiceProviders(); public static final StackFrameTransformer defaultTransformer = fromServiceProviders .andThen(convertStdLibUrlToExternalUrl) .andThen(replacePackageUriWithSourceCodeUrl); private static StackFrame transformUri(StackFrame frame, String path, String format) { var uri = frame.getModuleUri(); var newUri = format .replace("%{path}", path) .replace("%{url}", uri) .replace("%{line}", String.valueOf(frame.getStartLine())) .replace("%{endLine}", String.valueOf(frame.getEndLine())) .replace("%{column}", String.valueOf(frame.getStartColumn())) .replace("%{endColumn}", String.valueOf(frame.getEndColumn())); return frame.withModuleUri(newUri); } public static StackFrameTransformer convertFilePathToUriScheme(String scheme) { return frame -> { var uri = frame.getModuleUri(); if (!uri.startsWith("file:")) return frame; return transformUri(frame, Path.of(URI.create(uri)).toString(), scheme); }; } public static StackFrameTransformer relativizeModuleUri(URI baseUri) { return frame -> { var uri = URI.create(frame.getModuleUri()); var relativized = baseUri.relativize(uri); return frame.withModuleUri(relativized.toString()); }; } public static StackFrameTransformer createDefault(PklSettings settings) { return defaultTransformer // order is relevant .andThen(convertFilePathToUriScheme(settings.getEditor().getUrlScheme())); } private static StackFrameTransformer loadFromServiceProviders() { var loader = IoUtils.createServiceLoader(StackFrameTransformer.class); return StreamSupport.stream(loader.spliterator(), false) .reduce((t1, t2) -> t1.andThen(t2)) .orElse(t -> t); // use no-op transformer if no service providers found } }
apple/pkl
pkl-core/src/main/java/org/pkl/core/StackFrameTransformers.java
1,259
// order is relevant
line_comment
nl
/** * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * * 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 * * https://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.pkl.core; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.stream.StreamSupport; import org.pkl.core.packages.PackageAssetUri; import org.pkl.core.runtime.VmContext; import org.pkl.core.settings.PklSettings; import org.pkl.core.util.IoUtils; /** Static factory for stack frame transformers. */ public final class StackFrameTransformers { private StackFrameTransformers() {} public static final StackFrameTransformer empty = s -> s; public static final StackFrameTransformer convertStdLibUrlToExternalUrl = frame -> { var uri = frame.getModuleUri(); if (uri.startsWith("pkl:")) { var moduleName = uri.substring(4); return frame.withModuleUri( Release.current() .sourceCode() .getFilePage("stdlib/" + moduleName + ".pkl#L" + frame.getStartLine())); } return frame; }; public static final StackFrameTransformer replacePackageUriWithSourceCodeUrl = frame -> { var uri = URI.create(frame.getModuleUri()); if (!uri.getScheme().equalsIgnoreCase("package")) { return frame; } try { var assetUri = new PackageAssetUri(uri); var packageResolver = VmContext.get(null).getPackageResolver(); assert packageResolver != null; var pkg = packageResolver.getDependencyMetadata(assetUri.getPackageUri(), null); var sourceCode = pkg.getSourceCodeUrlScheme(); if (sourceCode == null) { return frame; } return transformUri(frame, uri.getFragment(), sourceCode); } catch (IOException | URISyntaxException | SecurityManagerException e) { // should never get here. by this point, we should have already performed all validation // and downloaded all assets. throw PklBugException.unreachableCode(); } }; public static final StackFrameTransformer fromServiceProviders = loadFromServiceProviders(); public static final StackFrameTransformer defaultTransformer = fromServiceProviders .andThen(convertStdLibUrlToExternalUrl) .andThen(replacePackageUriWithSourceCodeUrl); private static StackFrame transformUri(StackFrame frame, String path, String format) { var uri = frame.getModuleUri(); var newUri = format .replace("%{path}", path) .replace("%{url}", uri) .replace("%{line}", String.valueOf(frame.getStartLine())) .replace("%{endLine}", String.valueOf(frame.getEndLine())) .replace("%{column}", String.valueOf(frame.getStartColumn())) .replace("%{endColumn}", String.valueOf(frame.getEndColumn())); return frame.withModuleUri(newUri); } public static StackFrameTransformer convertFilePathToUriScheme(String scheme) { return frame -> { var uri = frame.getModuleUri(); if (!uri.startsWith("file:")) return frame; return transformUri(frame, Path.of(URI.create(uri)).toString(), scheme); }; } public static StackFrameTransformer relativizeModuleUri(URI baseUri) { return frame -> { var uri = URI.create(frame.getModuleUri()); var relativized = baseUri.relativize(uri); return frame.withModuleUri(relativized.toString()); }; } public static StackFrameTransformer createDefault(PklSettings settings) { return defaultTransformer // order is<SUF> .andThen(convertFilePathToUriScheme(settings.getEditor().getUrlScheme())); } private static StackFrameTransformer loadFromServiceProviders() { var loader = IoUtils.createServiceLoader(StackFrameTransformer.class); return StreamSupport.stream(loader.spliterator(), false) .reduce((t1, t2) -> t1.andThen(t2)) .orElse(t -> t); // use no-op transformer if no service providers found } }
True
False
1,474
4,123
24577_6
package nl.consumergram.consumergramv2.services; import jakarta.persistence.EntityNotFoundException; import nl.consumergram.consumergramv2.dtos.UserDto; import nl.consumergram.consumergramv2.models.User; import nl.consumergram.consumergramv2.repositories.UserRepository; import nl.consumergram.consumergramv2.utils.RandomStringGenerator; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class UserService { public PasswordEncoder passwordEncoder; // De constructor injecteert een instantie van UserRepository private final UserRepository userRepository; public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } // // Opslaan van het versleutelde wachtwoord in de database of ergens anders // userRepository.save(new User(UserDto.getUsername(), encodedPassword)); // } public List<UserDto> getUsers() { List<UserDto> collection = new ArrayList<>(); List<User> list = userRepository.findAll(); for (User user : list) { collection.add(fromUser(user)); } return collection; } // Haalt een specifieke gebruiker op basis van de gebruikersnaam en converteert deze naar een UserDto public UserDto getUser(String username) { UserDto dto = new UserDto(); Optional<User> user = userRepository.findById(username); if (user.isPresent()) { dto = fromUser(user.get()); } else { throw new UsernameNotFoundException(username); } return dto; } // Controleert of een gebruiker met de opgegeven gebruikersnaam bestaat. public boolean userExists(String username) { return userRepository.existsById(username); } // Genereert een willekeurige API-sleutel, stelt deze in op de UserDto en slaat een nieuwe gebruiker op in de database. Geeft de gebruikersnaam van de aangemaakte gebruiker terug. public String createUser(UserDto userDto) { String randomString = RandomStringGenerator.generateAlphaNumeric(20); userDto.setApikey(randomString); User newUser = userRepository.save(toUser(userDto)); return newUser.getUsername(); } // Verwijdert een gebruiker op basis van de gebruikersnaam. public void deleteUser(String username) { userRepository.deleteById(username); } public UserDto updateUser(String username, UserDto dto) { User user = userRepository.findByUsername(username) .orElseThrow(() -> new EntityNotFoundException("User not found with username " + username)); user.setEmail(dto.getEmail()); user.setUsername(dto.getUsername()); // Check if the password field in the incoming UserDto is null or empty if (dto.getPassword() != null && !dto.getPassword().isEmpty()) { user.setPassword(passwordEncoder.encode(dto.getPassword())); } User updatedUser = userRepository.save(user); UserDto updatedUserDto = convertToDto(updatedUser); return updatedUserDto; } public UserDto convertToDto(User user) { UserDto userDto = new UserDto(); userDto.setUsername(user.getUsername()); userDto.setPassword(user.getPassword()); userDto.setEnabled(user.isEnabled()); userDto.setApikey(user.getApikey()); userDto.setEmail(user.getEmail()); userDto.setAuthorities(user.getAuthorities()); return userDto; } // Zet een User-object om naar een UserDto public static UserDto fromUser(User user) { var dto = new UserDto(); // In de code lijkt getUsername() de // gebruikersnaam terug te geven, die vaak wordt gebruikt als een unieke // identificator voor een gebruiker. dto.username = user.getUsername(); dto.password = user.getPassword(); dto.enabled = user.isEnabled(); dto.apikey = user.getApikey(); dto.email = user.getEmail(); dto.authorities = user.getAuthorities(); return dto; } // Zet een UserDto-object om naar een User. public User toUser(UserDto userDto) { var user = new User(); user.setUsername(userDto.getUsername()); user.setPassword(passwordEncoder.encode(userDto.password)); // user.setPassword(userDto.getPassword()); user.setEnabled(userDto.getEnabled()); user.setApikey(userDto.getApikey()); user.setEmail(userDto.getEmail()); return user; } }
rayzathegrave/ConsumerGramBackendv2
src/main/java/nl/consumergram/consumergramv2/services/UserService.java
1,406
// Verwijdert een gebruiker op basis van de gebruikersnaam.
line_comment
nl
package nl.consumergram.consumergramv2.services; import jakarta.persistence.EntityNotFoundException; import nl.consumergram.consumergramv2.dtos.UserDto; import nl.consumergram.consumergramv2.models.User; import nl.consumergram.consumergramv2.repositories.UserRepository; import nl.consumergram.consumergramv2.utils.RandomStringGenerator; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class UserService { public PasswordEncoder passwordEncoder; // De constructor injecteert een instantie van UserRepository private final UserRepository userRepository; public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } // // Opslaan van het versleutelde wachtwoord in de database of ergens anders // userRepository.save(new User(UserDto.getUsername(), encodedPassword)); // } public List<UserDto> getUsers() { List<UserDto> collection = new ArrayList<>(); List<User> list = userRepository.findAll(); for (User user : list) { collection.add(fromUser(user)); } return collection; } // Haalt een specifieke gebruiker op basis van de gebruikersnaam en converteert deze naar een UserDto public UserDto getUser(String username) { UserDto dto = new UserDto(); Optional<User> user = userRepository.findById(username); if (user.isPresent()) { dto = fromUser(user.get()); } else { throw new UsernameNotFoundException(username); } return dto; } // Controleert of een gebruiker met de opgegeven gebruikersnaam bestaat. public boolean userExists(String username) { return userRepository.existsById(username); } // Genereert een willekeurige API-sleutel, stelt deze in op de UserDto en slaat een nieuwe gebruiker op in de database. Geeft de gebruikersnaam van de aangemaakte gebruiker terug. public String createUser(UserDto userDto) { String randomString = RandomStringGenerator.generateAlphaNumeric(20); userDto.setApikey(randomString); User newUser = userRepository.save(toUser(userDto)); return newUser.getUsername(); } // Verwijdert een<SUF> public void deleteUser(String username) { userRepository.deleteById(username); } public UserDto updateUser(String username, UserDto dto) { User user = userRepository.findByUsername(username) .orElseThrow(() -> new EntityNotFoundException("User not found with username " + username)); user.setEmail(dto.getEmail()); user.setUsername(dto.getUsername()); // Check if the password field in the incoming UserDto is null or empty if (dto.getPassword() != null && !dto.getPassword().isEmpty()) { user.setPassword(passwordEncoder.encode(dto.getPassword())); } User updatedUser = userRepository.save(user); UserDto updatedUserDto = convertToDto(updatedUser); return updatedUserDto; } public UserDto convertToDto(User user) { UserDto userDto = new UserDto(); userDto.setUsername(user.getUsername()); userDto.setPassword(user.getPassword()); userDto.setEnabled(user.isEnabled()); userDto.setApikey(user.getApikey()); userDto.setEmail(user.getEmail()); userDto.setAuthorities(user.getAuthorities()); return userDto; } // Zet een User-object om naar een UserDto public static UserDto fromUser(User user) { var dto = new UserDto(); // In de code lijkt getUsername() de // gebruikersnaam terug te geven, die vaak wordt gebruikt als een unieke // identificator voor een gebruiker. dto.username = user.getUsername(); dto.password = user.getPassword(); dto.enabled = user.isEnabled(); dto.apikey = user.getApikey(); dto.email = user.getEmail(); dto.authorities = user.getAuthorities(); return dto; } // Zet een UserDto-object om naar een User. public User toUser(UserDto userDto) { var user = new User(); user.setUsername(userDto.getUsername()); user.setPassword(passwordEncoder.encode(userDto.password)); // user.setPassword(userDto.getPassword()); user.setEnabled(userDto.getEnabled()); user.setApikey(userDto.getApikey()); user.setEmail(userDto.getEmail()); return user; } }
True
False
1,475
3,636
11857_12
/* LanguageTool, a natural language style checker * Copyright (C) 2023 Mark Baas * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.nl; import com.google.common.collect.ImmutableSet; import org.languagetool.*; import org.languagetool.rules.RuleMatch; import org.languagetool.tagging.nl.DutchTagger; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.regex.Pattern; /** * Accept Dutch compounds that are not accepted by the speller. This code * is supposed to accept more words in order to extend the speller, but it's not meant * to accept all valid compounds. * It works on 2-part compounds only for now. */ public class CompoundAcceptor { private static final Pattern acronymPattern = Pattern.compile("[A-Z]{2,4}-"); private static final Pattern specialAcronymPattern = Pattern.compile("[A-Za-z]{2,4}-"); private static final Pattern normalCasePattern = Pattern.compile("[A-Za-z][a-zé]*"); private static final int MAX_WORD_SIZE = 35; // if part 1 ends with this, it always needs an 's' appended private final Set<String> alwaysNeedsS = ImmutableSet.of( "heids", "ings", "schaps", "teits" ); // compound parts that need an 's' appended to be used as first part of the compound: private final Set<String> needsS = ImmutableSet.of( "afgods", "afstands", "allemans", "arbeids", "arbeiders", "bedrijfs", "beleids", "beroeps", "bestuurders", "bestuurs", "deurwaarders", "dichters", "dorps", "eindejaars", "etens", "gebruiks", "gebruikers", "geluids", "gevechts", "gezichts", "gezins", "handels", "honds", "jongens", "langeafstands", "koopmans", "levens", "lijdens", "martelaars", "meisjes", "onderhouds", "onderzoeks", "oorlogs", "oudejaars", "ouderdoms", "overlijdens", "padvinders", "passagiers", "personeels", "rijks", "scheeps", "staats", "stads", "varkens", "verkeers", "volks", "vrijwilligers" ); // exceptions to the list "alwaysNeedsS" private final Set<String> part1Exceptions = ImmutableSet.of( "belasting", "dating", "doping", "gaming", "grooming", "honing", "kleding", "kring", "matching", "outsourcing", "paling", "rekening", "spring", "styling", "tracking", "tweeling", "viking" ); private final Set<String> part2Exceptions = ImmutableSet.of( "actor", "actoren", "baar", "baren", "ding", "enen", "fries", "lijk", "loos", "lopen", "lozen", "mara", "ping", "raat", "reek", "reen", "stag", "sten", "tand", "ting", "voor" ); private final Set<String> acronymExceptions = ImmutableSet.of( "aids", "alv", "AMvB", "Anw", "apk", "arbo", "Awb", "bbl", "Bevi", "Bopz", "bso", "btw", "cao", "cd", "dj", "dvd", "ecg", "gft", "ggz", "gps", "gsm", "hbs", "hifi", "hiv", "hr", "hrm", "hsl", "hts", "Hvb", "Hvw", "iMac", "iOS", "iPad", "iPod", "ivf", "lbo", "lcd", "lts", "mbo", "mdf", "mkb", "Opw", "ozb", "pc", "pdf", "pgb", "sms", "soa", "tbs", "tv", "ufo", "vip", "vwo", "Wabo", "Waz", "Wazo", "Wbp", "wifi", "Wft", "Wlz", "WvS", "Wwft", "Wzd", "xtc", "Zvw", "zzp" ); // compound parts that must not have an 's' appended to be used as first part of the compound: private final Set<String> noS = ImmutableSet.of( "aandeel", "aangifte", "aanname", "aard", "aardappel", "aardbeien", "aardgas", "aardolie", "abortus", "achter", "accessoire", "achtergrond", "actie", "adres", "afgifte", "afname", "afval", "aids", "akte", "algoritme", "allure", "alpen", "ambulance", "analyse", "anders", "anekdote", "anijs", "animatie", "antenne", "appel", "aqua", "aquarium", "attitude", "auto", "avond", "baby", "bagage", "bagger", "bal", "balustrade", "bank", "basis", "bediende", "beeld", "beeldhouw", "begin", "behoefte", "belangen", "belofte", "bende", "berg", "beroerte", "bestek", "bestel", "betekenis", "bezoek", "bibliotheek", "bier", "bijdrage", "bijlage", "binnenste", "blad", "blauw", "blessure", "bloed", "bodem", "boeren", "boete", "bolide", "bom", "bord", "bordeel", "borduur", "borstel", "bouw", "brand", "breedte", "brigade", "buiten", "burger", "buurt", "cabaret", "café", "campagne", "camping", "cantate", "cassette", "centrum", "catastrofe", "chocolade", "club", "collecte", "combinatie", "competitie", "computer", "contact", "contract", "contra", "contrast", "controverse", "cosmetica", "cult", "cultuur", "curve", "dag", "dames", "dans", "data", "deel", "deeltijd", "demo", "demonstratie", "design", "detective", "deur", "diagnose", "dienst", "diepte", "diepzee", "dikte", "disco", "doel", "dossier", "douane", "draai", "droogte", "druk", "dubbel", "eind", "einde", "elektro", "ellende", "energie", "episode", "ere", "erf", "erfgoed", "estafette", "etappe", "expertise", "export", "façade", "familie", "fan", "fanfare", "fantasie", "fase", "feest", "film", "finale", "fitness", "fluoride", "formatie", "foto", "fractie", "fruit", "game", "gast", "gebergte", "geboorte", "gedaante", "gedachte", "gedeelte", "gehalte", "geld", "gemeente", "gemiddelde", "genade", "genocide", "gestalte", "gesteente", "gevaarte", "gewoonte", "gezegde", "gilde", "glas", "goederen", "golf", "goud", "graf", "gras", "gravure", "groente", "grond", "grootte", "haar", "half", "halte", "hand", "haven", "haver", "hectare", "hitte", "hobby", "hof", "hogedruk", "holte", "homo", "honden", "hoofd", "hoog", "hoogte", "horde", "hotel", "hout", "huid", "huis", "hulp", "humor", "huur", "hybride", "hyper", "hypotheek", "hypothese", "impasse", "info", "informatie", "inname", "internet", "inzage", "jaar", "jeugd", "jongeren", "kade", "kamer", "kamp", "kampeer", "kantoor", "karakter", "kastanje", "kasteel", "kazerne", "kennis", "kerk", "kern", "kerst", "keuken", "keuze", "kijk", "kilo", "kilometer", "kind", "kinder", "klei", "klim", "klimaat", "koffie", "kool", "koolmees", "koolstof", "koolzaad", "koop", "krapte", "kruis", "kudde", "kuit", "kunst", "kussen", "kust", "lade", "landbouw", "langetermijn", "leegte", "leer", "legende", "leger", "leken", "lengte", "lever", "licht", "lijn", "literatuur", "lok", "long", "loon", "loop", "lotus", "lucht", "luchtvaart", "maan", "maand", "maat", "machine", "made", "mammoet", "manden", "mannen", "markt", "martel", "mascotte", "massa", "massage", "mast", "materiaal", "mechanisme", "mede", "media", "meester", "melk", "menigte", "mensen", "mensenrechten", "merk", "meta", "metaal", "metamorfose", "methode", "meute", "micro", "midden", "mieren", "mijn", "milieu", "mini", "mode", "model", "module", "moeder", "mond", "moslim", "motor", "multi", "multimedia", "muziek", "mythe", "nacht", "natuur", "netwerk", "nieuws", "nood", "normaal", "novelle", "nuance", "oase", "offerte", "olie", "onderwijs", "ontwerp", "oorkonde", "oplage", "opname", "opper", "orde", "organisatie", "organisme", "orgasme", "ouderen", "overname", "paarden", "padden", "papier", "park", "parkeer", "partij", "party", "passie", "pauze", "pedicure", "periode", "pers", "pistool", "piramide", "piste", "plaats", "plas", "plasma", "plastic", "podium", "polis", "politie", "portefeuille", "portiek", "portret", "post", "power", "praktijk", "prijs", "privé", "probleem", "proces", "product", "productie", "proef", "prof", "programma", "programmeer", "project", "propaganda", "prothese", "prototype", "psycho", "psychose", "pyjama", "radio", "rail", "rand", "rap", "reis", "regel", "regen", "regio", "rente", "reserve", "rest", "restauratie", "rij", "ritme", "rock", "ronde", "rotonde", "route", "rubber", "ruimte", "ruimtevaart", "ruïne", "runder", "rundvlees", "satire", "schaarste", "schade", "scheer", "schild", "school", "schoon", "seconde", "secretaresse", "sekte", "sfeer", "sier", "sieraden", "ski", "slaap", "slaapkamer", "slag", "sneeuw", "span", "spiegel", "spier", "spinnen", "spoor", "sport", "stamp", "stand", "standaard", "start", "steen", "stem", "ster", "stereo", "sterfte", "sterkte", "stilte", "stof", "straat", "strand", "stroom", "studenten", "studie", "suiker", "super", "synagoge", "synode", "synthese", "systeem", "taal", "tafel", "takel", "team", "tekst", "telefoon", "televisie", "tentamen", "tenue", "terzijde", "test", "theater", "thuis", "tiener", "titel", "toelage", "toer", "toeristen", "toets", "tol", "tombe", "trans", "transfer", "transport", "trede", "trek", "tube", "tuin", "type", "uiteinde", "uitgifte", "vakantie", "veld", "verkoop", "verloofde", "verte", "vete", "video", "vip", "vitamine", "vlakte", "vlees", "voedsel", "voer", "voertuig", "voet", "voeten", "voetbal", "vogel", "volume", "voorbeeld", "voorbode", "voorhoede", "voorliefde", "voorronde", "vorm", "vreugde", "vrienden", "vrouwen", "vuur", "waarde", "wacht", "wand", "wandel", "wapen", "warmte", "water", "waterstof", "wiel", "wieler", "wind", "winter", "wijn", "web", "weduwe", "week", "weer", "weergave", "weide", "wereld", "werk", "wijk", "winkel", "wonder", "woning", "woord", "zand", "zieken", "ziekenfonds", "ziekenhuis", "ziekte", "zijde", "zit", "zomer", "zonde", "zorg", "zwaarte", "zwakte", "zwanger" ); // Make sure we don't allow compound words where part 1 ends with a specific vowel and part2 starts with one, for words like "politieeenheid". private final Set<String> collidingVowels = ImmutableSet.of( "aa", "ae", "ai", "au", "ee", "ée", "ei", "éi", "eu", "éu", "ie", "ii", "ij", "oe", "oi", "oo", "ou", "ui", "uu" ); private static final MorfologikDutchSpellerRule speller; static { try { speller = new MorfologikDutchSpellerRule(JLanguageTool.getMessageBundle(), Languages.getLanguageForShortCode("nl"), null); } catch (IOException e) { throw new RuntimeException(e); } } private DutchTagger dutchTagger = DutchTagger.INSTANCE; public CompoundAcceptor() { } boolean acceptCompound(String word) { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return false; } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (!part1.equals(part2) && acceptCompound(part1, part2)) { System.out.println(part1+part2 + " -> accepted"); return true; } } return false; } public List<String> getParts(String word) { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return Collections.emptyList(); } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (!part1.equals(part2) && acceptCompound(part1, part2)) { return Arrays.asList(part1, part2); } } return Collections.emptyList(); } boolean acceptCompound(String part1, String part2) { try { String part1lc = part1.toLowerCase(); // reject if it's in the exceptions list or if a wildcard is the entirety of part1 if (part1.endsWith("s") && !part1Exceptions.contains(part1.substring(0, part1.length() -1)) && !alwaysNeedsS.contains(part1) && !noS.contains(part1) && !part1.contains("-")) { for (String suffix : alwaysNeedsS) { if (part1lc.endsWith(suffix)) { return isNoun(part2) && isExistingWord(part1lc.substring(0, part1lc.length() - 1)) && spellingOk(part2); } } return needsS.contains(part1lc) && isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2); } else if (part1.endsWith("-")) { // abbreviations return acronymOk(part1) && spellingOk(part2); } else if (part2.startsWith("-")) { // vowel collision part2 = part2.substring(1); return noS.contains(part1lc) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && hasCollidingVowels(part1, part2); } else { return (noS.contains(part1lc) || part1Exceptions.contains(part1lc)) && isNoun(part2) && spellingOk(part1) && !hasCollidingVowels(part1, part2); } } catch (IOException e) { throw new RuntimeException(e); } } private boolean isNoun(String word) throws IOException { return dutchTagger.getPostags(word).stream().anyMatch(k -> { assert k.getPOSTag() != null; return k.getPOSTag().startsWith("ZNW") && !part2Exceptions.contains(word); }); } private boolean isExistingWord(String word) throws IOException { return dutchTagger.getPostags(word).stream().anyMatch(k -> k.getPOSTag() != null); } private boolean hasCollidingVowels(String part1, String part2) { char char1 = part1.charAt(part1.length() - 1); char char2 = part2.charAt(0); String vowels = String.valueOf(char1) + char2; return collidingVowels.contains(vowels.toLowerCase()); } private boolean acronymOk(String nonCompound) { // for compound words like IRA-akkoord, MIDI-bestanden, WK-finalisten if ( acronymPattern.matcher(nonCompound).matches() ){ return acronymExceptions.stream().noneMatch(exception -> exception.toUpperCase().equals(nonCompound.substring(0, nonCompound.length() -1))); } else if ( specialAcronymPattern.matcher(nonCompound).matches() ) { // special case acronyms that are accepted only with specific casing return acronymExceptions.contains(nonCompound.substring(0, nonCompound.length() -1)); } else { return false; } } private boolean spellingOk(String nonCompound) throws IOException { if (!normalCasePattern.matcher(nonCompound).matches()) { return false; // e.g. kinderenHet -> split as kinder,enHet } AnalyzedSentence as = new AnalyzedSentence(new AnalyzedTokenReadings[] { new AnalyzedTokenReadings(new AnalyzedToken(nonCompound.toLowerCase(), "FAKE_POS", "fakeLemma")) }); RuleMatch[] matches = speller.match(as); return matches.length == 0; } public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: " + CompoundAcceptor.class.getName() + " <file>"); System.exit(1); } CompoundAcceptor acceptor = new CompoundAcceptor(); List<String> words = Files.readAllLines(Paths.get(args[0])); for (String word : words) { boolean accepted = acceptor.acceptCompound(word); System.out.println(accepted + " " + word); } } }
mexa-team/languagetool
languagetool-language-modules/nl/src/main/java/org/languagetool/rules/nl/CompoundAcceptor.java
6,961
// e.g. kinderenHet -> split as kinder,enHet
line_comment
nl
/* LanguageTool, a natural language style checker * Copyright (C) 2023 Mark Baas * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.nl; import com.google.common.collect.ImmutableSet; import org.languagetool.*; import org.languagetool.rules.RuleMatch; import org.languagetool.tagging.nl.DutchTagger; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.regex.Pattern; /** * Accept Dutch compounds that are not accepted by the speller. This code * is supposed to accept more words in order to extend the speller, but it's not meant * to accept all valid compounds. * It works on 2-part compounds only for now. */ public class CompoundAcceptor { private static final Pattern acronymPattern = Pattern.compile("[A-Z]{2,4}-"); private static final Pattern specialAcronymPattern = Pattern.compile("[A-Za-z]{2,4}-"); private static final Pattern normalCasePattern = Pattern.compile("[A-Za-z][a-zé]*"); private static final int MAX_WORD_SIZE = 35; // if part 1 ends with this, it always needs an 's' appended private final Set<String> alwaysNeedsS = ImmutableSet.of( "heids", "ings", "schaps", "teits" ); // compound parts that need an 's' appended to be used as first part of the compound: private final Set<String> needsS = ImmutableSet.of( "afgods", "afstands", "allemans", "arbeids", "arbeiders", "bedrijfs", "beleids", "beroeps", "bestuurders", "bestuurs", "deurwaarders", "dichters", "dorps", "eindejaars", "etens", "gebruiks", "gebruikers", "geluids", "gevechts", "gezichts", "gezins", "handels", "honds", "jongens", "langeafstands", "koopmans", "levens", "lijdens", "martelaars", "meisjes", "onderhouds", "onderzoeks", "oorlogs", "oudejaars", "ouderdoms", "overlijdens", "padvinders", "passagiers", "personeels", "rijks", "scheeps", "staats", "stads", "varkens", "verkeers", "volks", "vrijwilligers" ); // exceptions to the list "alwaysNeedsS" private final Set<String> part1Exceptions = ImmutableSet.of( "belasting", "dating", "doping", "gaming", "grooming", "honing", "kleding", "kring", "matching", "outsourcing", "paling", "rekening", "spring", "styling", "tracking", "tweeling", "viking" ); private final Set<String> part2Exceptions = ImmutableSet.of( "actor", "actoren", "baar", "baren", "ding", "enen", "fries", "lijk", "loos", "lopen", "lozen", "mara", "ping", "raat", "reek", "reen", "stag", "sten", "tand", "ting", "voor" ); private final Set<String> acronymExceptions = ImmutableSet.of( "aids", "alv", "AMvB", "Anw", "apk", "arbo", "Awb", "bbl", "Bevi", "Bopz", "bso", "btw", "cao", "cd", "dj", "dvd", "ecg", "gft", "ggz", "gps", "gsm", "hbs", "hifi", "hiv", "hr", "hrm", "hsl", "hts", "Hvb", "Hvw", "iMac", "iOS", "iPad", "iPod", "ivf", "lbo", "lcd", "lts", "mbo", "mdf", "mkb", "Opw", "ozb", "pc", "pdf", "pgb", "sms", "soa", "tbs", "tv", "ufo", "vip", "vwo", "Wabo", "Waz", "Wazo", "Wbp", "wifi", "Wft", "Wlz", "WvS", "Wwft", "Wzd", "xtc", "Zvw", "zzp" ); // compound parts that must not have an 's' appended to be used as first part of the compound: private final Set<String> noS = ImmutableSet.of( "aandeel", "aangifte", "aanname", "aard", "aardappel", "aardbeien", "aardgas", "aardolie", "abortus", "achter", "accessoire", "achtergrond", "actie", "adres", "afgifte", "afname", "afval", "aids", "akte", "algoritme", "allure", "alpen", "ambulance", "analyse", "anders", "anekdote", "anijs", "animatie", "antenne", "appel", "aqua", "aquarium", "attitude", "auto", "avond", "baby", "bagage", "bagger", "bal", "balustrade", "bank", "basis", "bediende", "beeld", "beeldhouw", "begin", "behoefte", "belangen", "belofte", "bende", "berg", "beroerte", "bestek", "bestel", "betekenis", "bezoek", "bibliotheek", "bier", "bijdrage", "bijlage", "binnenste", "blad", "blauw", "blessure", "bloed", "bodem", "boeren", "boete", "bolide", "bom", "bord", "bordeel", "borduur", "borstel", "bouw", "brand", "breedte", "brigade", "buiten", "burger", "buurt", "cabaret", "café", "campagne", "camping", "cantate", "cassette", "centrum", "catastrofe", "chocolade", "club", "collecte", "combinatie", "competitie", "computer", "contact", "contract", "contra", "contrast", "controverse", "cosmetica", "cult", "cultuur", "curve", "dag", "dames", "dans", "data", "deel", "deeltijd", "demo", "demonstratie", "design", "detective", "deur", "diagnose", "dienst", "diepte", "diepzee", "dikte", "disco", "doel", "dossier", "douane", "draai", "droogte", "druk", "dubbel", "eind", "einde", "elektro", "ellende", "energie", "episode", "ere", "erf", "erfgoed", "estafette", "etappe", "expertise", "export", "façade", "familie", "fan", "fanfare", "fantasie", "fase", "feest", "film", "finale", "fitness", "fluoride", "formatie", "foto", "fractie", "fruit", "game", "gast", "gebergte", "geboorte", "gedaante", "gedachte", "gedeelte", "gehalte", "geld", "gemeente", "gemiddelde", "genade", "genocide", "gestalte", "gesteente", "gevaarte", "gewoonte", "gezegde", "gilde", "glas", "goederen", "golf", "goud", "graf", "gras", "gravure", "groente", "grond", "grootte", "haar", "half", "halte", "hand", "haven", "haver", "hectare", "hitte", "hobby", "hof", "hogedruk", "holte", "homo", "honden", "hoofd", "hoog", "hoogte", "horde", "hotel", "hout", "huid", "huis", "hulp", "humor", "huur", "hybride", "hyper", "hypotheek", "hypothese", "impasse", "info", "informatie", "inname", "internet", "inzage", "jaar", "jeugd", "jongeren", "kade", "kamer", "kamp", "kampeer", "kantoor", "karakter", "kastanje", "kasteel", "kazerne", "kennis", "kerk", "kern", "kerst", "keuken", "keuze", "kijk", "kilo", "kilometer", "kind", "kinder", "klei", "klim", "klimaat", "koffie", "kool", "koolmees", "koolstof", "koolzaad", "koop", "krapte", "kruis", "kudde", "kuit", "kunst", "kussen", "kust", "lade", "landbouw", "langetermijn", "leegte", "leer", "legende", "leger", "leken", "lengte", "lever", "licht", "lijn", "literatuur", "lok", "long", "loon", "loop", "lotus", "lucht", "luchtvaart", "maan", "maand", "maat", "machine", "made", "mammoet", "manden", "mannen", "markt", "martel", "mascotte", "massa", "massage", "mast", "materiaal", "mechanisme", "mede", "media", "meester", "melk", "menigte", "mensen", "mensenrechten", "merk", "meta", "metaal", "metamorfose", "methode", "meute", "micro", "midden", "mieren", "mijn", "milieu", "mini", "mode", "model", "module", "moeder", "mond", "moslim", "motor", "multi", "multimedia", "muziek", "mythe", "nacht", "natuur", "netwerk", "nieuws", "nood", "normaal", "novelle", "nuance", "oase", "offerte", "olie", "onderwijs", "ontwerp", "oorkonde", "oplage", "opname", "opper", "orde", "organisatie", "organisme", "orgasme", "ouderen", "overname", "paarden", "padden", "papier", "park", "parkeer", "partij", "party", "passie", "pauze", "pedicure", "periode", "pers", "pistool", "piramide", "piste", "plaats", "plas", "plasma", "plastic", "podium", "polis", "politie", "portefeuille", "portiek", "portret", "post", "power", "praktijk", "prijs", "privé", "probleem", "proces", "product", "productie", "proef", "prof", "programma", "programmeer", "project", "propaganda", "prothese", "prototype", "psycho", "psychose", "pyjama", "radio", "rail", "rand", "rap", "reis", "regel", "regen", "regio", "rente", "reserve", "rest", "restauratie", "rij", "ritme", "rock", "ronde", "rotonde", "route", "rubber", "ruimte", "ruimtevaart", "ruïne", "runder", "rundvlees", "satire", "schaarste", "schade", "scheer", "schild", "school", "schoon", "seconde", "secretaresse", "sekte", "sfeer", "sier", "sieraden", "ski", "slaap", "slaapkamer", "slag", "sneeuw", "span", "spiegel", "spier", "spinnen", "spoor", "sport", "stamp", "stand", "standaard", "start", "steen", "stem", "ster", "stereo", "sterfte", "sterkte", "stilte", "stof", "straat", "strand", "stroom", "studenten", "studie", "suiker", "super", "synagoge", "synode", "synthese", "systeem", "taal", "tafel", "takel", "team", "tekst", "telefoon", "televisie", "tentamen", "tenue", "terzijde", "test", "theater", "thuis", "tiener", "titel", "toelage", "toer", "toeristen", "toets", "tol", "tombe", "trans", "transfer", "transport", "trede", "trek", "tube", "tuin", "type", "uiteinde", "uitgifte", "vakantie", "veld", "verkoop", "verloofde", "verte", "vete", "video", "vip", "vitamine", "vlakte", "vlees", "voedsel", "voer", "voertuig", "voet", "voeten", "voetbal", "vogel", "volume", "voorbeeld", "voorbode", "voorhoede", "voorliefde", "voorronde", "vorm", "vreugde", "vrienden", "vrouwen", "vuur", "waarde", "wacht", "wand", "wandel", "wapen", "warmte", "water", "waterstof", "wiel", "wieler", "wind", "winter", "wijn", "web", "weduwe", "week", "weer", "weergave", "weide", "wereld", "werk", "wijk", "winkel", "wonder", "woning", "woord", "zand", "zieken", "ziekenfonds", "ziekenhuis", "ziekte", "zijde", "zit", "zomer", "zonde", "zorg", "zwaarte", "zwakte", "zwanger" ); // Make sure we don't allow compound words where part 1 ends with a specific vowel and part2 starts with one, for words like "politieeenheid". private final Set<String> collidingVowels = ImmutableSet.of( "aa", "ae", "ai", "au", "ee", "ée", "ei", "éi", "eu", "éu", "ie", "ii", "ij", "oe", "oi", "oo", "ou", "ui", "uu" ); private static final MorfologikDutchSpellerRule speller; static { try { speller = new MorfologikDutchSpellerRule(JLanguageTool.getMessageBundle(), Languages.getLanguageForShortCode("nl"), null); } catch (IOException e) { throw new RuntimeException(e); } } private DutchTagger dutchTagger = DutchTagger.INSTANCE; public CompoundAcceptor() { } boolean acceptCompound(String word) { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return false; } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (!part1.equals(part2) && acceptCompound(part1, part2)) { System.out.println(part1+part2 + " -> accepted"); return true; } } return false; } public List<String> getParts(String word) { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return Collections.emptyList(); } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (!part1.equals(part2) && acceptCompound(part1, part2)) { return Arrays.asList(part1, part2); } } return Collections.emptyList(); } boolean acceptCompound(String part1, String part2) { try { String part1lc = part1.toLowerCase(); // reject if it's in the exceptions list or if a wildcard is the entirety of part1 if (part1.endsWith("s") && !part1Exceptions.contains(part1.substring(0, part1.length() -1)) && !alwaysNeedsS.contains(part1) && !noS.contains(part1) && !part1.contains("-")) { for (String suffix : alwaysNeedsS) { if (part1lc.endsWith(suffix)) { return isNoun(part2) && isExistingWord(part1lc.substring(0, part1lc.length() - 1)) && spellingOk(part2); } } return needsS.contains(part1lc) && isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2); } else if (part1.endsWith("-")) { // abbreviations return acronymOk(part1) && spellingOk(part2); } else if (part2.startsWith("-")) { // vowel collision part2 = part2.substring(1); return noS.contains(part1lc) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && hasCollidingVowels(part1, part2); } else { return (noS.contains(part1lc) || part1Exceptions.contains(part1lc)) && isNoun(part2) && spellingOk(part1) && !hasCollidingVowels(part1, part2); } } catch (IOException e) { throw new RuntimeException(e); } } private boolean isNoun(String word) throws IOException { return dutchTagger.getPostags(word).stream().anyMatch(k -> { assert k.getPOSTag() != null; return k.getPOSTag().startsWith("ZNW") && !part2Exceptions.contains(word); }); } private boolean isExistingWord(String word) throws IOException { return dutchTagger.getPostags(word).stream().anyMatch(k -> k.getPOSTag() != null); } private boolean hasCollidingVowels(String part1, String part2) { char char1 = part1.charAt(part1.length() - 1); char char2 = part2.charAt(0); String vowels = String.valueOf(char1) + char2; return collidingVowels.contains(vowels.toLowerCase()); } private boolean acronymOk(String nonCompound) { // for compound words like IRA-akkoord, MIDI-bestanden, WK-finalisten if ( acronymPattern.matcher(nonCompound).matches() ){ return acronymExceptions.stream().noneMatch(exception -> exception.toUpperCase().equals(nonCompound.substring(0, nonCompound.length() -1))); } else if ( specialAcronymPattern.matcher(nonCompound).matches() ) { // special case acronyms that are accepted only with specific casing return acronymExceptions.contains(nonCompound.substring(0, nonCompound.length() -1)); } else { return false; } } private boolean spellingOk(String nonCompound) throws IOException { if (!normalCasePattern.matcher(nonCompound).matches()) { return false; // e.g. kinderenHet<SUF> } AnalyzedSentence as = new AnalyzedSentence(new AnalyzedTokenReadings[] { new AnalyzedTokenReadings(new AnalyzedToken(nonCompound.toLowerCase(), "FAKE_POS", "fakeLemma")) }); RuleMatch[] matches = speller.match(as); return matches.length == 0; } public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: " + CompoundAcceptor.class.getName() + " <file>"); System.exit(1); } CompoundAcceptor acceptor = new CompoundAcceptor(); List<String> words = Files.readAllLines(Paths.get(args[0])); for (String word : words) { boolean accepted = acceptor.acceptCompound(word); System.out.println(accepted + " " + word); } } }
True
False
1,477
1,926
78592_10
package sen.groep4;_x000D_ _x000D_ import java.awt.Container;_x000D_ import java.awt.Dimension;_x000D_ import java.awt.GridLayout;_x000D_ import java.awt.event.ActionEvent;_x000D_ import java.awt.event.ActionListener;_x000D_ import java.io.BufferedReader;_x000D_ import java.io.File;_x000D_ import java.io.FileNotFoundException;_x000D_ import java.io.FileReader;_x000D_ import java.io.IOException;_x000D_ import java.net.InetAddress;_x000D_ import java.net.NetworkInterface;_x000D_ import java.text.SimpleDateFormat;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Calendar;_x000D_ import java.util.Date;_x000D_ import java.util.Enumeration;_x000D_ import java.util.List;_x000D_ import javax.swing.BoxLayout;_x000D_ import javax.swing.JButton;_x000D_ import javax.swing.JFileChooser;_x000D_ import javax.swing.JFrame;_x000D_ import javax.swing.JLabel;_x000D_ import javax.swing.JPanel;_x000D_ import javax.swing.JScrollPane;_x000D_ import javax.swing.JTextArea;_x000D_ import javax.swing.JTextField;_x000D_ import javax.swing.SwingConstants;_x000D_ import javax.swing.filechooser.FileFilter;_x000D_ _x000D_ public class UserInterface extends JFrame_x000D_ {_x000D_ private JButton _btnLoad;_x000D_ private JButton _btnStart;_x000D_ private Communication _communication;_x000D_ private JFileChooser _fileChooser;_x000D_ private List<String> _xml;_x000D_ private static JTextArea _txtConsole; _x000D_ private JTextField _txtPort;_x000D_ _x000D_ public UserInterface() throws IOException_x000D_ {_x000D_ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);_x000D_ _x000D_ addComponentsToPane(getContentPane());_x000D_ _x000D_ pack();_x000D_ setSize(new Dimension(333, 777));_x000D_ setTitle(Strings.title + Strings.space + Strings.four);_x000D_ setLocationRelativeTo(null);_x000D_ setVisible(true);_x000D_ }_x000D_ _x000D_ public static void setText(String text)_x000D_ {_x000D_ Date date = Calendar.getInstance().getTime();_x000D_ String time = new SimpleDateFormat("HH:mm:ss.SSS").format(date);_x000D_ _x000D_ _txtConsole.append(_x000D_ time +_x000D_ Strings.space +_x000D_ text +_x000D_ Strings.newLine_x000D_ );_x000D_ }_x000D_ _x000D_ private void addComponentsToPane(Container pane) throws IOException_x000D_ {_x000D_ // Layout_x000D_ pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));_x000D_ _x000D_ JPanel labels = new JPanel();_x000D_ labels.setLayout(new GridLayout(0,2));_x000D_ _x000D_ JPanel port = new JPanel();_x000D_ port.setLayout(new GridLayout(0,2));_x000D_ _x000D_ JPanel controls = new JPanel();_x000D_ controls.setLayout(new GridLayout(0,2));_x000D_ _x000D_ JPanel console = new JPanel();_x000D_ console.setLayout(new GridLayout(0,1));_x000D_ _x000D_ // Controls_x000D_ JLabel lblAddress = new JLabel(_x000D_ Strings.space +_x000D_ Strings.addressKey +_x000D_ Strings.space +_x000D_ getIPAddress()_x000D_ );_x000D_ _x000D_ labels.add(lblAddress);_x000D_ _x000D_ JLabel lblPort = new JLabel(Strings.portKey + Strings.space);_x000D_ lblPort.setHorizontalAlignment(SwingConstants.RIGHT);_x000D_ _txtPort = new JTextField();_x000D_ _txtPort.setText(_x000D_ Strings.one +_x000D_ Strings.three +_x000D_ Strings.three +_x000D_ Strings.seven_x000D_ );_x000D_ _x000D_ port.add(lblPort);_x000D_ port.add(_txtPort);_x000D_ _x000D_ labels.add(port);_x000D_ _x000D_ _btnLoad = new JButton(Strings.load);_x000D_ _btnStart = new JButton(Strings.start);_x000D_ _btnStart.setEnabled(false);_x000D_ _x000D_ controls.add(_btnLoad);_x000D_ controls.add(_btnStart);_x000D_ _x000D_ _txtConsole = new JTextArea(37, 0);_x000D_ _txtConsole.setEditable(false);_x000D_ _x000D_ JScrollPane scrollPane = new JScrollPane(_txtConsole); _x000D_ scrollPane.setAutoscrolls(true);_x000D_ _x000D_ console.add(scrollPane);_x000D_ _x000D_ _fileChooser = new JFileChooser();_x000D_ _fileChooser.setAcceptAllFileFilterUsed(false);_x000D_ _fileChooser.setFileFilter(new XMLFileFilter());_x000D_ _x000D_ // Events_x000D_ _btnLoad.addActionListener(new ActionListener()_x000D_ {_x000D_ @Override_x000D_ public void actionPerformed(ActionEvent e)_x000D_ {_x000D_ int returnVal = _fileChooser.showOpenDialog(new JPanel());_x000D_ _x000D_ if (returnVal == JFileChooser.APPROVE_OPTION)_x000D_ {_x000D_ File file = _fileChooser.getSelectedFile();_x000D_ _x000D_ readXMLFile(file);_x000D_ _x000D_ // Disable button Load_x000D_ _btnLoad.setEnabled(false);_x000D_ _x000D_ // Enable button Connect_x000D_ _btnStart.setEnabled(true);_x000D_ }_x000D_ }_x000D_ });_x000D_ _x000D_ _btnStart.addActionListener(new ActionListener()_x000D_ {_x000D_ @Override_x000D_ public void actionPerformed(ActionEvent e)_x000D_ {_x000D_ if (_btnStart.getText().equals(Strings.start))_x000D_ {_x000D_ _communication = new Communication();_x000D_ int port = Integer.valueOf(_txtPort.getText());_x000D_ _x000D_ try_x000D_ {_x000D_ _communication.connect(port);_x000D_ }_x000D_ catch (IOException ex){setText(ex.getMessage());}_x000D_ _x000D_ // Disable button Load_x000D_ _btnLoad.setEnabled(false);_x000D_ _x000D_ // Change text of button Start_x000D_ _btnStart.setText(Strings.stop);_x000D_ }_x000D_ else_x000D_ {_x000D_ _communication = null;_x000D_ _x000D_ // Enable button Load_x000D_ _btnLoad.setEnabled(true);_x000D_ _x000D_ // Change text of button Start_x000D_ _btnStart.setText(Strings.start);_x000D_ }_x000D_ }_x000D_ });_x000D_ _x000D_ // Pane_x000D_ pane.add(labels, pane);_x000D_ pane.add(controls, pane);_x000D_ pane.add(console, pane);_x000D_ }_x000D_ _x000D_ private String getIPAddress() throws IOException_x000D_ {_x000D_ String ipAddress =_x000D_ Strings.one +_x000D_ Strings.two +_x000D_ Strings.seven +_x000D_ Strings.dot +_x000D_ Strings.zero +_x000D_ Strings.dot +_x000D_ Strings.zero +_x000D_ Strings.dot +_x000D_ Strings.one;_x000D_ List<String> addresses = new ArrayList();_x000D_ _x000D_ Enumeration e = NetworkInterface.getNetworkInterfaces();_x000D_ _x000D_ while (e.hasMoreElements())_x000D_ {_x000D_ NetworkInterface n = (NetworkInterface) e.nextElement();_x000D_ Enumeration ee = n.getInetAddresses();_x000D_ _x000D_ while (ee.hasMoreElements())_x000D_ {_x000D_ InetAddress i = (InetAddress) ee.nextElement();_x000D_ _x000D_ addresses.add(i.getHostAddress());_x000D_ }_x000D_ }_x000D_ _x000D_ for (int i = 0; i < addresses.size(); i ++)_x000D_ {_x000D_ String address = addresses.get(i);_x000D_ _x000D_ if (address.length() <= 28 &&_x000D_ !address.startsWith(Strings.zero + Strings.doubleDot) &&_x000D_ !address.startsWith(Strings.one + Strings.zero) &&_x000D_ !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.two +_x000D_ Strings.seven_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.one +_x000D_ Strings.six_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.one +_x000D_ Strings.seven_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.one +_x000D_ Strings.eight_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.one +_x000D_ Strings.nine_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.zero_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.one_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.two_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.three_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.four_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.five_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.six_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.seven_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.eight_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.nine_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.three +_x000D_ Strings.zero_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.three +_x000D_ Strings.one_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.nine +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.one +_x000D_ Strings.six +_x000D_ Strings.eight_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.four_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.five_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.six_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.seven_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.eight_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.nine_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.zero_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.one_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.two_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.four_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.five_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.six_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.seven_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.eight_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.nine_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.five +_x000D_ Strings.five +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.five +_x000D_ Strings.five +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.five +_x000D_ Strings.five +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.five +_x000D_ Strings.five_x000D_ )_x000D_ ){_x000D_ ipAddress = address;_x000D_ }_x000D_ }_x000D_ _x000D_ return ipAddress;_x000D_ }_x000D_ _x000D_ private void readXMLFile(File file)_x000D_ {_x000D_ // Een invoerlijst wordt gemaakt_x000D_ List<String> listInput = new ArrayList();_x000D_ _x000D_ // Een bestandslezer wordt gemaakt_x000D_ FileReader fileReader = null;_x000D_ try_x000D_ {_x000D_ fileReader = new FileReader(file);_x000D_ }_x000D_ catch (FileNotFoundException ex){}_x000D_ _x000D_ // Een bufferende lezer wordt gemaakt_x000D_ try (BufferedReader bufferedReader = new BufferedReader(fileReader))_x000D_ {_x000D_ // Een invoerregel wordt gemaakt_x000D_ String strInput;_x000D_ _x000D_ // Zolang de invoerregel niet niets is_x000D_ while ((strInput = bufferedReader.readLine()) != null)_x000D_ {_x000D_ // De invoerregel wordt aan de invoerlijst toegevoegd_x000D_ listInput.add(strInput);_x000D_ }_x000D_ }_x000D_ catch (IOException ex){}_x000D_ _x000D_ XMLParser xmlParser = new XMLParser();_x000D_ _x000D_ _xml = xmlParser.parse(listInput);_x000D_ _x000D_ showXMLFile();_x000D_ }_x000D_ _x000D_ private void showXMLFile()_x000D_ {_x000D_ for (int i = 0; i < _xml.size(); i ++)_x000D_ {_x000D_ setText(_xml.get(i));_x000D_ }_x000D_ }_x000D_ _x000D_ private class XMLFileFilter extends FileFilter_x000D_ {_x000D_ @Override_x000D_ public boolean accept(File file)_x000D_ {_x000D_ if (file.isDirectory())_x000D_ {_x000D_ return true;_x000D_ }_x000D_ _x000D_ String extension = getExtension(file);_x000D_ _x000D_ if (extension != null)_x000D_ {_x000D_ if (extension.equals(Strings.xml))_x000D_ {_x000D_ return true;_x000D_ }_x000D_ else_x000D_ {_x000D_ return false;_x000D_ }_x000D_ }_x000D_ _x000D_ return false;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public String getDescription()_x000D_ {_x000D_ return Strings.inputFiles;_x000D_ }_x000D_ _x000D_ private String getExtension(File file)_x000D_ {_x000D_ String ext = null;_x000D_ String s = file.getName();_x000D_ int i = s.lastIndexOf('.');_x000D_ _x000D_ if (i > 0 && i < s.length() - 1)_x000D_ {_x000D_ ext = s.substring(i + 1).toLowerCase();_x000D_ }_x000D_ _x000D_ return ext;_x000D_ }_x000D_ }_x000D_ }
Zaibatsu89/skrzyzowanie
SEN_Controller/src/sen/groep4/UserInterface.java
4,503
// Zolang de invoerregel niet niets is_x000D_
line_comment
nl
package sen.groep4;_x000D_ _x000D_ import java.awt.Container;_x000D_ import java.awt.Dimension;_x000D_ import java.awt.GridLayout;_x000D_ import java.awt.event.ActionEvent;_x000D_ import java.awt.event.ActionListener;_x000D_ import java.io.BufferedReader;_x000D_ import java.io.File;_x000D_ import java.io.FileNotFoundException;_x000D_ import java.io.FileReader;_x000D_ import java.io.IOException;_x000D_ import java.net.InetAddress;_x000D_ import java.net.NetworkInterface;_x000D_ import java.text.SimpleDateFormat;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Calendar;_x000D_ import java.util.Date;_x000D_ import java.util.Enumeration;_x000D_ import java.util.List;_x000D_ import javax.swing.BoxLayout;_x000D_ import javax.swing.JButton;_x000D_ import javax.swing.JFileChooser;_x000D_ import javax.swing.JFrame;_x000D_ import javax.swing.JLabel;_x000D_ import javax.swing.JPanel;_x000D_ import javax.swing.JScrollPane;_x000D_ import javax.swing.JTextArea;_x000D_ import javax.swing.JTextField;_x000D_ import javax.swing.SwingConstants;_x000D_ import javax.swing.filechooser.FileFilter;_x000D_ _x000D_ public class UserInterface extends JFrame_x000D_ {_x000D_ private JButton _btnLoad;_x000D_ private JButton _btnStart;_x000D_ private Communication _communication;_x000D_ private JFileChooser _fileChooser;_x000D_ private List<String> _xml;_x000D_ private static JTextArea _txtConsole; _x000D_ private JTextField _txtPort;_x000D_ _x000D_ public UserInterface() throws IOException_x000D_ {_x000D_ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);_x000D_ _x000D_ addComponentsToPane(getContentPane());_x000D_ _x000D_ pack();_x000D_ setSize(new Dimension(333, 777));_x000D_ setTitle(Strings.title + Strings.space + Strings.four);_x000D_ setLocationRelativeTo(null);_x000D_ setVisible(true);_x000D_ }_x000D_ _x000D_ public static void setText(String text)_x000D_ {_x000D_ Date date = Calendar.getInstance().getTime();_x000D_ String time = new SimpleDateFormat("HH:mm:ss.SSS").format(date);_x000D_ _x000D_ _txtConsole.append(_x000D_ time +_x000D_ Strings.space +_x000D_ text +_x000D_ Strings.newLine_x000D_ );_x000D_ }_x000D_ _x000D_ private void addComponentsToPane(Container pane) throws IOException_x000D_ {_x000D_ // Layout_x000D_ pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));_x000D_ _x000D_ JPanel labels = new JPanel();_x000D_ labels.setLayout(new GridLayout(0,2));_x000D_ _x000D_ JPanel port = new JPanel();_x000D_ port.setLayout(new GridLayout(0,2));_x000D_ _x000D_ JPanel controls = new JPanel();_x000D_ controls.setLayout(new GridLayout(0,2));_x000D_ _x000D_ JPanel console = new JPanel();_x000D_ console.setLayout(new GridLayout(0,1));_x000D_ _x000D_ // Controls_x000D_ JLabel lblAddress = new JLabel(_x000D_ Strings.space +_x000D_ Strings.addressKey +_x000D_ Strings.space +_x000D_ getIPAddress()_x000D_ );_x000D_ _x000D_ labels.add(lblAddress);_x000D_ _x000D_ JLabel lblPort = new JLabel(Strings.portKey + Strings.space);_x000D_ lblPort.setHorizontalAlignment(SwingConstants.RIGHT);_x000D_ _txtPort = new JTextField();_x000D_ _txtPort.setText(_x000D_ Strings.one +_x000D_ Strings.three +_x000D_ Strings.three +_x000D_ Strings.seven_x000D_ );_x000D_ _x000D_ port.add(lblPort);_x000D_ port.add(_txtPort);_x000D_ _x000D_ labels.add(port);_x000D_ _x000D_ _btnLoad = new JButton(Strings.load);_x000D_ _btnStart = new JButton(Strings.start);_x000D_ _btnStart.setEnabled(false);_x000D_ _x000D_ controls.add(_btnLoad);_x000D_ controls.add(_btnStart);_x000D_ _x000D_ _txtConsole = new JTextArea(37, 0);_x000D_ _txtConsole.setEditable(false);_x000D_ _x000D_ JScrollPane scrollPane = new JScrollPane(_txtConsole); _x000D_ scrollPane.setAutoscrolls(true);_x000D_ _x000D_ console.add(scrollPane);_x000D_ _x000D_ _fileChooser = new JFileChooser();_x000D_ _fileChooser.setAcceptAllFileFilterUsed(false);_x000D_ _fileChooser.setFileFilter(new XMLFileFilter());_x000D_ _x000D_ // Events_x000D_ _btnLoad.addActionListener(new ActionListener()_x000D_ {_x000D_ @Override_x000D_ public void actionPerformed(ActionEvent e)_x000D_ {_x000D_ int returnVal = _fileChooser.showOpenDialog(new JPanel());_x000D_ _x000D_ if (returnVal == JFileChooser.APPROVE_OPTION)_x000D_ {_x000D_ File file = _fileChooser.getSelectedFile();_x000D_ _x000D_ readXMLFile(file);_x000D_ _x000D_ // Disable button Load_x000D_ _btnLoad.setEnabled(false);_x000D_ _x000D_ // Enable button Connect_x000D_ _btnStart.setEnabled(true);_x000D_ }_x000D_ }_x000D_ });_x000D_ _x000D_ _btnStart.addActionListener(new ActionListener()_x000D_ {_x000D_ @Override_x000D_ public void actionPerformed(ActionEvent e)_x000D_ {_x000D_ if (_btnStart.getText().equals(Strings.start))_x000D_ {_x000D_ _communication = new Communication();_x000D_ int port = Integer.valueOf(_txtPort.getText());_x000D_ _x000D_ try_x000D_ {_x000D_ _communication.connect(port);_x000D_ }_x000D_ catch (IOException ex){setText(ex.getMessage());}_x000D_ _x000D_ // Disable button Load_x000D_ _btnLoad.setEnabled(false);_x000D_ _x000D_ // Change text of button Start_x000D_ _btnStart.setText(Strings.stop);_x000D_ }_x000D_ else_x000D_ {_x000D_ _communication = null;_x000D_ _x000D_ // Enable button Load_x000D_ _btnLoad.setEnabled(true);_x000D_ _x000D_ // Change text of button Start_x000D_ _btnStart.setText(Strings.start);_x000D_ }_x000D_ }_x000D_ });_x000D_ _x000D_ // Pane_x000D_ pane.add(labels, pane);_x000D_ pane.add(controls, pane);_x000D_ pane.add(console, pane);_x000D_ }_x000D_ _x000D_ private String getIPAddress() throws IOException_x000D_ {_x000D_ String ipAddress =_x000D_ Strings.one +_x000D_ Strings.two +_x000D_ Strings.seven +_x000D_ Strings.dot +_x000D_ Strings.zero +_x000D_ Strings.dot +_x000D_ Strings.zero +_x000D_ Strings.dot +_x000D_ Strings.one;_x000D_ List<String> addresses = new ArrayList();_x000D_ _x000D_ Enumeration e = NetworkInterface.getNetworkInterfaces();_x000D_ _x000D_ while (e.hasMoreElements())_x000D_ {_x000D_ NetworkInterface n = (NetworkInterface) e.nextElement();_x000D_ Enumeration ee = n.getInetAddresses();_x000D_ _x000D_ while (ee.hasMoreElements())_x000D_ {_x000D_ InetAddress i = (InetAddress) ee.nextElement();_x000D_ _x000D_ addresses.add(i.getHostAddress());_x000D_ }_x000D_ }_x000D_ _x000D_ for (int i = 0; i < addresses.size(); i ++)_x000D_ {_x000D_ String address = addresses.get(i);_x000D_ _x000D_ if (address.length() <= 28 &&_x000D_ !address.startsWith(Strings.zero + Strings.doubleDot) &&_x000D_ !address.startsWith(Strings.one + Strings.zero) &&_x000D_ !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.two +_x000D_ Strings.seven_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.one +_x000D_ Strings.six_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.one +_x000D_ Strings.seven_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.one +_x000D_ Strings.eight_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.one +_x000D_ Strings.nine_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.zero_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.one_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.two_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.three_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.four_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.five_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.six_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.seven_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.eight_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.nine_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.three +_x000D_ Strings.zero_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.seven +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.three +_x000D_ Strings.one_x000D_ ) && !address.startsWith(_x000D_ Strings.one +_x000D_ Strings.nine +_x000D_ Strings.two +_x000D_ Strings.dot +_x000D_ Strings.one +_x000D_ Strings.six +_x000D_ Strings.eight_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.four_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.five_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.six_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.seven_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.eight_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.two +_x000D_ Strings.nine_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.zero_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.one_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.two_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.four_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.five_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.six_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.seven_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.eight_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.three +_x000D_ Strings.nine_x000D_ ) && !address.startsWith(_x000D_ Strings.two +_x000D_ Strings.five +_x000D_ Strings.five +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.five +_x000D_ Strings.five +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.five +_x000D_ Strings.five +_x000D_ Strings.dot +_x000D_ Strings.two +_x000D_ Strings.five +_x000D_ Strings.five_x000D_ )_x000D_ ){_x000D_ ipAddress = address;_x000D_ }_x000D_ }_x000D_ _x000D_ return ipAddress;_x000D_ }_x000D_ _x000D_ private void readXMLFile(File file)_x000D_ {_x000D_ // Een invoerlijst wordt gemaakt_x000D_ List<String> listInput = new ArrayList();_x000D_ _x000D_ // Een bestandslezer wordt gemaakt_x000D_ FileReader fileReader = null;_x000D_ try_x000D_ {_x000D_ fileReader = new FileReader(file);_x000D_ }_x000D_ catch (FileNotFoundException ex){}_x000D_ _x000D_ // Een bufferende lezer wordt gemaakt_x000D_ try (BufferedReader bufferedReader = new BufferedReader(fileReader))_x000D_ {_x000D_ // Een invoerregel wordt gemaakt_x000D_ String strInput;_x000D_ _x000D_ // Zolang de<SUF> while ((strInput = bufferedReader.readLine()) != null)_x000D_ {_x000D_ // De invoerregel wordt aan de invoerlijst toegevoegd_x000D_ listInput.add(strInput);_x000D_ }_x000D_ }_x000D_ catch (IOException ex){}_x000D_ _x000D_ XMLParser xmlParser = new XMLParser();_x000D_ _x000D_ _xml = xmlParser.parse(listInput);_x000D_ _x000D_ showXMLFile();_x000D_ }_x000D_ _x000D_ private void showXMLFile()_x000D_ {_x000D_ for (int i = 0; i < _xml.size(); i ++)_x000D_ {_x000D_ setText(_xml.get(i));_x000D_ }_x000D_ }_x000D_ _x000D_ private class XMLFileFilter extends FileFilter_x000D_ {_x000D_ @Override_x000D_ public boolean accept(File file)_x000D_ {_x000D_ if (file.isDirectory())_x000D_ {_x000D_ return true;_x000D_ }_x000D_ _x000D_ String extension = getExtension(file);_x000D_ _x000D_ if (extension != null)_x000D_ {_x000D_ if (extension.equals(Strings.xml))_x000D_ {_x000D_ return true;_x000D_ }_x000D_ else_x000D_ {_x000D_ return false;_x000D_ }_x000D_ }_x000D_ _x000D_ return false;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public String getDescription()_x000D_ {_x000D_ return Strings.inputFiles;_x000D_ }_x000D_ _x000D_ private String getExtension(File file)_x000D_ {_x000D_ String ext = null;_x000D_ String s = file.getName();_x000D_ int i = s.lastIndexOf('.');_x000D_ _x000D_ if (i > 0 && i < s.length() - 1)_x000D_ {_x000D_ ext = s.substring(i + 1).toLowerCase();_x000D_ }_x000D_ _x000D_ return ext;_x000D_ }_x000D_ }_x000D_ }
True
False
1,479
3,124
101472_0
package afvink3; /** * Race class * Class Race maakt gebruik van de class Paard * * @author Martijn van der Bruggen * @version alpha - aanroep van cruciale methodes ontbreekt * (c) 2009 Hogeschool van Arnhem en Nijmegen * * Note: deze code is bewust niet op alle punten generiek * dit om nog onbekende constructies te vermijden. * * Updates * 2010: verduidelijking van opdrachten in de code MvdB * 2011: verbetering leesbaarheid code MvdB * 2012: verbetering layout code en aanpassing commentaar MvdB * 2013: commentaar aangepast aan nieuwe opdracht MvdB * ************************************************* * Afvinkopdracht: werken met methodes en objecten ************************************************* * Opdrachten zitten verwerkt in de code * 1) Declaratie constante * 2) Declaratie van Paard (niet instantiering) * 3) Declareer een button * 4) Zet breedte en hoogte van het frame * 5) Teken een finish streep * 6) Creatie van 4 paarden * 7) Pauzeer * 8) Teken 4 paarden * 9) Plaats tekst op de button * 10) Start de race, methode aanroep * * */ import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; public class Race extends JFrame implements ActionListener { /** declaratie van variabelen */ private final int lengte = 250; private Paard[] horses = new Paard[5]; private JButton button; private BufferedImage horse_image; /* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */ /* (2) Declareer hier h1, h2, h3, h4 van het type Paard * Deze paarden instantieer je later in het programma */ /* (3) Declareer een button met de naam button van het type JButton */ private RacePanel panel; public Race(){ try { horse_image = ImageIO.read(new File("/home/bastiaan/IdeaProjects/Afvinkopdracht3/src/afvink3/horse.png")); } catch (IOException e) { } String[] names = { "Winey", "Blaze", "Pinky", "Hopper", "Shadow" }; Color[] hColors = { new Color(95, 2, 31), new Color(236, 71, 28), new Color(250, 28, 183), new Color(50, 200, 29), new Color(0,0,0) }; for (int x = 0; x < horses.length; x++){ horses[x] = new Paard(names[x], hColors[x]); //tekenPaard(g, horses[x]); } } /** Applicatie - main functie voor runnen applicatie */ public static void main(String[] args) { Race frame = new Race(); /* (4) Geef het frame een breedte van 400 en hoogte van 140 */ frame.setSize(new Dimension(400, 300)); frame.createGUI(); frame.setVisible(true); } /** Loop de race */ private void startRace(Graphics g) { panel.setBackground(Color.white); /** Tekenen van de finish streep */ /* (5) Geef de finish streep een rode kleur */ //g.setColor(Color.RED); //g.fillRect(lengte+10, 0, 3, 200); /* String[] names = { "Winey", "Blaze", "Pinky", "Hopper", "Shadow" }; Color[] hColors = { new Color(95, 2, 31), new Color(236, 71, 28), new Color(250, 28, 183), new Color(50, 200, 29), new Color(0,0,0) }; for (int x = 0; x < horses.length; x++){ horses[x] = new Paard(names[x], hColors[x]); //tekenPaard(g, horses[x]); } */ //panel.repaint(); for (Paard horse : horses){ horse.setAfstand(0); } /**(6) Creatie van 4 paarden * Dit is een instantiering van de 4 paard objecten * Bij de instantiering geef je de paarden een naam en een kleur mee * Kijk in de class Paard hoe je de paarden * kunt initialiseren. */ /** Loop tot een paard over de finish is*/ boolean keepRunning = true; while (keepRunning) { g.setColor(Color.white); g.fillRect(0, 0, 300, 200); for (Paard horse : horses){ horse.run(); tekenPaard(g, horse); if (horse.getAfstand() >= lengte){ keepRunning = false; } } g.setColor(Color.RED); g.fillRect(lengte+10, 0, 3, 200); //panel.repaint(); /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig * dat er 1 seconde pauze is. De methode pauzeer is onderdeel * van deze class */ pauzeer(200); /* (8) Voeg hier code in om 4 paarden te tekenen die rennen * Dus een call van de methode tekenPaard */ /** for (Paard horse : horses){ tekenPaard(g, horse); } for (Paard horse : horses){ if (horse.getAfstand() >= lengte){ keepRunning = false; } } */ } /** Kijk welk paard gewonnen heeft */ for (Paard horse : horses){ if (horse.getAfstand() >= lengte) { JOptionPane.showMessageDialog(null, horse.getNaam() + " heeft gewonnen!"); } } } /** Creatie van de GUI*/ private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); panel = new RacePanel(); panel.setPreferredSize(new Dimension(300, 200)); panel.setBackground(Color.white); window.add(panel); /* (9) Zet hier de tekst Run! op de button */ button = new JButton("Run!"); window.add(button); button.addActionListener(this); } /** Teken het paard */ private void tekenPaard(Graphics g, Paard h) { //g.setColor(h.getKleur()); //g.fillRect(h.getAfstand(), 20 * h.getPaardNummer(), 10, 5); g.drawImage(horse_image, h.getAfstand(), 40 * (h.getPaardNummer()-1), 30, 30,null); //g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } /** Actie indien de button geklikt is*/ public void actionPerformed(ActionEvent event) { Graphics paper = panel.getGraphics(); /* (10) Roep hier de methode startrace aan met de juiste parameterisering */ startRace (paper); } /** Pauzeer gedurende x millisecondes*/ public void pauzeer(int msec) { try { Thread.sleep(msec); } catch (InterruptedException e) { System.out.println("Pauze interruptie"); } } private class RacePanel extends JPanel{ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); for (Paard h : horses) { System.out.println(h.getAfstand()); //g.fillRect(h.getAfstand(), 20 * h.getPaardNummer(), 10, 5); g.drawImage(horse_image, h.getAfstand(), 40 * (h.getPaardNummer() - 1), 30, 30, null); //g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } g.setColor(Color.RED); g.fillRect(lengte+10, 0, 3, 200); } } }
itbc-bin/1819-owe5a-afvinkopdracht3-BastiaanBrier
src/afvink3/Race.java
2,450
/** * Race class * Class Race maakt gebruik van de class Paard * * @author Martijn van der Bruggen * @version alpha - aanroep van cruciale methodes ontbreekt * (c) 2009 Hogeschool van Arnhem en Nijmegen * * Note: deze code is bewust niet op alle punten generiek * dit om nog onbekende constructies te vermijden. * * Updates * 2010: verduidelijking van opdrachten in de code MvdB * 2011: verbetering leesbaarheid code MvdB * 2012: verbetering layout code en aanpassing commentaar MvdB * 2013: commentaar aangepast aan nieuwe opdracht MvdB * ************************************************* * Afvinkopdracht: werken met methodes en objecten ************************************************* * Opdrachten zitten verwerkt in de code * 1) Declaratie constante * 2) Declaratie van Paard (niet instantiering) * 3) Declareer een button * 4) Zet breedte en hoogte van het frame * 5) Teken een finish streep * 6) Creatie van 4 paarden * 7) Pauzeer * 8) Teken 4 paarden * 9) Plaats tekst op de button * 10) Start de race, methode aanroep * * */
block_comment
nl
package afvink3; /** * Race class <SUF>*/ import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; public class Race extends JFrame implements ActionListener { /** declaratie van variabelen */ private final int lengte = 250; private Paard[] horses = new Paard[5]; private JButton button; private BufferedImage horse_image; /* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */ /* (2) Declareer hier h1, h2, h3, h4 van het type Paard * Deze paarden instantieer je later in het programma */ /* (3) Declareer een button met de naam button van het type JButton */ private RacePanel panel; public Race(){ try { horse_image = ImageIO.read(new File("/home/bastiaan/IdeaProjects/Afvinkopdracht3/src/afvink3/horse.png")); } catch (IOException e) { } String[] names = { "Winey", "Blaze", "Pinky", "Hopper", "Shadow" }; Color[] hColors = { new Color(95, 2, 31), new Color(236, 71, 28), new Color(250, 28, 183), new Color(50, 200, 29), new Color(0,0,0) }; for (int x = 0; x < horses.length; x++){ horses[x] = new Paard(names[x], hColors[x]); //tekenPaard(g, horses[x]); } } /** Applicatie - main functie voor runnen applicatie */ public static void main(String[] args) { Race frame = new Race(); /* (4) Geef het frame een breedte van 400 en hoogte van 140 */ frame.setSize(new Dimension(400, 300)); frame.createGUI(); frame.setVisible(true); } /** Loop de race */ private void startRace(Graphics g) { panel.setBackground(Color.white); /** Tekenen van de finish streep */ /* (5) Geef de finish streep een rode kleur */ //g.setColor(Color.RED); //g.fillRect(lengte+10, 0, 3, 200); /* String[] names = { "Winey", "Blaze", "Pinky", "Hopper", "Shadow" }; Color[] hColors = { new Color(95, 2, 31), new Color(236, 71, 28), new Color(250, 28, 183), new Color(50, 200, 29), new Color(0,0,0) }; for (int x = 0; x < horses.length; x++){ horses[x] = new Paard(names[x], hColors[x]); //tekenPaard(g, horses[x]); } */ //panel.repaint(); for (Paard horse : horses){ horse.setAfstand(0); } /**(6) Creatie van 4 paarden * Dit is een instantiering van de 4 paard objecten * Bij de instantiering geef je de paarden een naam en een kleur mee * Kijk in de class Paard hoe je de paarden * kunt initialiseren. */ /** Loop tot een paard over de finish is*/ boolean keepRunning = true; while (keepRunning) { g.setColor(Color.white); g.fillRect(0, 0, 300, 200); for (Paard horse : horses){ horse.run(); tekenPaard(g, horse); if (horse.getAfstand() >= lengte){ keepRunning = false; } } g.setColor(Color.RED); g.fillRect(lengte+10, 0, 3, 200); //panel.repaint(); /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig * dat er 1 seconde pauze is. De methode pauzeer is onderdeel * van deze class */ pauzeer(200); /* (8) Voeg hier code in om 4 paarden te tekenen die rennen * Dus een call van de methode tekenPaard */ /** for (Paard horse : horses){ tekenPaard(g, horse); } for (Paard horse : horses){ if (horse.getAfstand() >= lengte){ keepRunning = false; } } */ } /** Kijk welk paard gewonnen heeft */ for (Paard horse : horses){ if (horse.getAfstand() >= lengte) { JOptionPane.showMessageDialog(null, horse.getNaam() + " heeft gewonnen!"); } } } /** Creatie van de GUI*/ private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); panel = new RacePanel(); panel.setPreferredSize(new Dimension(300, 200)); panel.setBackground(Color.white); window.add(panel); /* (9) Zet hier de tekst Run! op de button */ button = new JButton("Run!"); window.add(button); button.addActionListener(this); } /** Teken het paard */ private void tekenPaard(Graphics g, Paard h) { //g.setColor(h.getKleur()); //g.fillRect(h.getAfstand(), 20 * h.getPaardNummer(), 10, 5); g.drawImage(horse_image, h.getAfstand(), 40 * (h.getPaardNummer()-1), 30, 30,null); //g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } /** Actie indien de button geklikt is*/ public void actionPerformed(ActionEvent event) { Graphics paper = panel.getGraphics(); /* (10) Roep hier de methode startrace aan met de juiste parameterisering */ startRace (paper); } /** Pauzeer gedurende x millisecondes*/ public void pauzeer(int msec) { try { Thread.sleep(msec); } catch (InterruptedException e) { System.out.println("Pauze interruptie"); } } private class RacePanel extends JPanel{ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); for (Paard h : horses) { System.out.println(h.getAfstand()); //g.fillRect(h.getAfstand(), 20 * h.getPaardNummer(), 10, 5); g.drawImage(horse_image, h.getAfstand(), 40 * (h.getPaardNummer() - 1), 30, 30, null); //g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } g.setColor(Color.RED); g.fillRect(lengte+10, 0, 3, 200); } } }
True
False
1,480
3,846
15321_0
package nl.novi.stuivenberg.springboot.example.security.service; import nl.novi.stuivenberg.springboot.example.security.domain.ERole; import nl.novi.stuivenberg.springboot.example.security.domain.Role; import nl.novi.stuivenberg.springboot.example.security.domain.User; import nl.novi.stuivenberg.springboot.example.security.payload.request.LoginRequest; import nl.novi.stuivenberg.springboot.example.security.payload.request.SignupRequest; import nl.novi.stuivenberg.springboot.example.security.payload.response.JwtResponse; import nl.novi.stuivenberg.springboot.example.security.payload.response.MessageResponse; import nl.novi.stuivenberg.springboot.example.security.repository.RoleRepository; import nl.novi.stuivenberg.springboot.example.security.repository.UserRepository; import nl.novi.stuivenberg.springboot.example.security.service.security.jwt.JwtUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Service public class AuthorizationService { private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found."; private UserRepository userRepository; private PasswordEncoder encoder; private RoleRepository roleRepository; private AuthenticationManager authenticationManager; private JwtUtils jwtUtils; @Autowired public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; } @Autowired public void setEncoder(PasswordEncoder passwordEncoder) { this.encoder = passwordEncoder; } @Autowired public void setRoleRepository(RoleRepository roleRepository) { this.roleRepository = roleRepository; } @Autowired public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Autowired public void setJwtUtils(JwtUtils jwtUtils) { this.jwtUtils = jwtUtils; } /** * * Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen * worden toegevoegd en de gebruiker wordt opgeslagen in de database. * * @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord. * @return een HTTP response met daarin een succesbericht. */ public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) { if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) { return ResponseEntity .badRequest() .body(new MessageResponse("Error: Username is already taken!")); } if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) { return ResponseEntity .badRequest() .body(new MessageResponse("Error: Email is already in use!")); } // Create new user's account User user = new User(signUpRequest.getUsername(), signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword())); Set<String> strRoles = signUpRequest.getRole(); Set<Role> roles = new HashSet<>(); if (strRoles == null) { Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } else { strRoles.forEach(role -> { switch (role) { case "admin": Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(adminRole); break; case "mod": Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(modRole); break; default: Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } }); } user.setRoles(roles); userRepository.save(user); return ResponseEntity.ok(new MessageResponse("User registered successfully!")); } /** * Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de * AuthenticationManager. I.a.w. Spring security doet die allemaal voor ons. * * Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid: * 401 Unauthorized. Deze wordt gegooid door * {@link nl.novi.stuivenberg.springboot.example.security.service.security.jwt.AuthEntryPointJwt} * * * @param loginRequest De payload met username en password. * @return een HTTP-response met daarin de JWT-token. */ public ResponseEntity<JwtResponse> authenticateUser(LoginRequest loginRequest) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtUtils.generateJwtToken(authentication); UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); List<String> roles = userDetails.getAuthorities().stream() .map(item -> item.getAuthority()) .collect(Collectors.toList()); return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles)); } }
novaeeken/sd-novi-authentication-backend
src/main/java/nl/novi/stuivenberg/springboot/example/security/service/AuthorizationService.java
1,789
/** * * Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen * worden toegevoegd en de gebruiker wordt opgeslagen in de database. * * @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord. * @return een HTTP response met daarin een succesbericht. */
block_comment
nl
package nl.novi.stuivenberg.springboot.example.security.service; import nl.novi.stuivenberg.springboot.example.security.domain.ERole; import nl.novi.stuivenberg.springboot.example.security.domain.Role; import nl.novi.stuivenberg.springboot.example.security.domain.User; import nl.novi.stuivenberg.springboot.example.security.payload.request.LoginRequest; import nl.novi.stuivenberg.springboot.example.security.payload.request.SignupRequest; import nl.novi.stuivenberg.springboot.example.security.payload.response.JwtResponse; import nl.novi.stuivenberg.springboot.example.security.payload.response.MessageResponse; import nl.novi.stuivenberg.springboot.example.security.repository.RoleRepository; import nl.novi.stuivenberg.springboot.example.security.repository.UserRepository; import nl.novi.stuivenberg.springboot.example.security.service.security.jwt.JwtUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Service public class AuthorizationService { private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found."; private UserRepository userRepository; private PasswordEncoder encoder; private RoleRepository roleRepository; private AuthenticationManager authenticationManager; private JwtUtils jwtUtils; @Autowired public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; } @Autowired public void setEncoder(PasswordEncoder passwordEncoder) { this.encoder = passwordEncoder; } @Autowired public void setRoleRepository(RoleRepository roleRepository) { this.roleRepository = roleRepository; } @Autowired public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Autowired public void setJwtUtils(JwtUtils jwtUtils) { this.jwtUtils = jwtUtils; } /** * * Deze methode verwerkt<SUF>*/ public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) { if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) { return ResponseEntity .badRequest() .body(new MessageResponse("Error: Username is already taken!")); } if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) { return ResponseEntity .badRequest() .body(new MessageResponse("Error: Email is already in use!")); } // Create new user's account User user = new User(signUpRequest.getUsername(), signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword())); Set<String> strRoles = signUpRequest.getRole(); Set<Role> roles = new HashSet<>(); if (strRoles == null) { Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } else { strRoles.forEach(role -> { switch (role) { case "admin": Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(adminRole); break; case "mod": Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(modRole); break; default: Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } }); } user.setRoles(roles); userRepository.save(user); return ResponseEntity.ok(new MessageResponse("User registered successfully!")); } /** * Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de * AuthenticationManager. I.a.w. Spring security doet die allemaal voor ons. * * Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid: * 401 Unauthorized. Deze wordt gegooid door * {@link nl.novi.stuivenberg.springboot.example.security.service.security.jwt.AuthEntryPointJwt} * * * @param loginRequest De payload met username en password. * @return een HTTP-response met daarin de JWT-token. */ public ResponseEntity<JwtResponse> authenticateUser(LoginRequest loginRequest) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtUtils.generateJwtToken(authentication); UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); List<String> roles = userDetails.getAuthorities().stream() .map(item -> item.getAuthority()) .collect(Collectors.toList()); return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles)); } }
True
False
1,483
1,751
101007_2
package io.github.stealingdapenta.idletd.command; import io.github.stealingdapenta.idletd.idleplayer.IdlePlayer; import io.github.stealingdapenta.idletd.idleplayer.IdlePlayerService; import io.github.stealingdapenta.idletd.plot.Plot; import io.github.stealingdapenta.idletd.plot.PlotService; import io.github.stealingdapenta.idletd.towerdefense.TowerDefense; import io.github.stealingdapenta.idletd.towerdefense.TowerDefenseManager; import io.github.stealingdapenta.idletd.towerdefense.TowerDefenseService; import lombok.RequiredArgsConstructor; import net.kyori.adventure.text.Component; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Objects; import static io.github.stealingdapenta.idletd.Idletd.logger; @RequiredArgsConstructor public class TowerDefenseCommand implements CommandExecutor { private static final String NO_PLOT = "Please create a plot before launching a TD game!"; private static final String NO_IDLE_PLAYER = "Internal error. Please contact a system admin."; private final PlotService plotService; private final TowerDefenseService towerDefenseService; private final IdlePlayerService idlePlayerService; private final TowerDefenseManager towerDefenseManager; @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { Player player = (Player) commandSender; IdlePlayer idlePlayer = idlePlayerService.getIdlePlayer(player); if (Objects.isNull(idlePlayer)) { logger.severe(player.getName() + " doesn't have a linked IdlePlayer."); player.sendMessage(Component.text(NO_IDLE_PLAYER)); return true; } TowerDefense towerDefense = towerDefenseManager.getActiveTDGame(idlePlayer); if (Objects.nonNull(towerDefense)) { player.sendMessage("You already have an active game."); return true; } towerDefense = towerDefenseService.findTowerDefense(idlePlayer); if (Objects.isNull(towerDefense)) { Plot plot = plotService.findPlot(player); if (Objects.isNull(plot)) { logger.info(player.getName() + " tried to start a TD game without even owning a plot yet."); player.sendMessage(Component.text(NO_PLOT)); return true; } towerDefense = TowerDefense.builder() .plot(plot.getId()) .playerUUID(idlePlayer.getPlayerUUID()) .stageLevel(1) .build(); towerDefenseService.saveTowerDefense(towerDefense); } towerDefenseManager.activateTDGame(towerDefense); // todo calculate AFK income (idle) // todo add economy, reward per kill, bank value // todo voor afk gold income, misschien "highest income op een round" + "duur round" saven en dan percentage daarvan per minuut uitbetalen met zelfde verhouding return true; } }
TomDesch/idletd
src/main/java/io/github/stealingdapenta/idletd/command/TowerDefenseCommand.java
899
// todo voor afk gold income, misschien "highest income op een round" + "duur round" saven en dan percentage daarvan per minuut uitbetalen met zelfde verhouding
line_comment
nl
package io.github.stealingdapenta.idletd.command; import io.github.stealingdapenta.idletd.idleplayer.IdlePlayer; import io.github.stealingdapenta.idletd.idleplayer.IdlePlayerService; import io.github.stealingdapenta.idletd.plot.Plot; import io.github.stealingdapenta.idletd.plot.PlotService; import io.github.stealingdapenta.idletd.towerdefense.TowerDefense; import io.github.stealingdapenta.idletd.towerdefense.TowerDefenseManager; import io.github.stealingdapenta.idletd.towerdefense.TowerDefenseService; import lombok.RequiredArgsConstructor; import net.kyori.adventure.text.Component; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Objects; import static io.github.stealingdapenta.idletd.Idletd.logger; @RequiredArgsConstructor public class TowerDefenseCommand implements CommandExecutor { private static final String NO_PLOT = "Please create a plot before launching a TD game!"; private static final String NO_IDLE_PLAYER = "Internal error. Please contact a system admin."; private final PlotService plotService; private final TowerDefenseService towerDefenseService; private final IdlePlayerService idlePlayerService; private final TowerDefenseManager towerDefenseManager; @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { Player player = (Player) commandSender; IdlePlayer idlePlayer = idlePlayerService.getIdlePlayer(player); if (Objects.isNull(idlePlayer)) { logger.severe(player.getName() + " doesn't have a linked IdlePlayer."); player.sendMessage(Component.text(NO_IDLE_PLAYER)); return true; } TowerDefense towerDefense = towerDefenseManager.getActiveTDGame(idlePlayer); if (Objects.nonNull(towerDefense)) { player.sendMessage("You already have an active game."); return true; } towerDefense = towerDefenseService.findTowerDefense(idlePlayer); if (Objects.isNull(towerDefense)) { Plot plot = plotService.findPlot(player); if (Objects.isNull(plot)) { logger.info(player.getName() + " tried to start a TD game without even owning a plot yet."); player.sendMessage(Component.text(NO_PLOT)); return true; } towerDefense = TowerDefense.builder() .plot(plot.getId()) .playerUUID(idlePlayer.getPlayerUUID()) .stageLevel(1) .build(); towerDefenseService.saveTowerDefense(towerDefense); } towerDefenseManager.activateTDGame(towerDefense); // todo calculate AFK income (idle) // todo add economy, reward per kill, bank value // todo voor<SUF> return true; } }
True
False
1,484
541
83128_1
package components;_x000D_ /**_x000D_ * SSD class. Contains all the information that a Solid State Drive has._x000D_ * All the fields match the fields in the Neo4j Database._x000D_ * Extends {@link components.Hardware}_x000D_ *_x000D_ * @author Frenesius_x000D_ * @since 1-1-2015_x000D_ * @version 0.1_x000D_ */_x000D_ public class SSD extends Hardware{_x000D_ private String beoordeling;_x000D_ private String hoogte;_x000D_ private String verkoopstatus;_x000D_ private String fabrieksgarantie;_x000D_ private String product;_x000D_ private String serie;_x000D_ private String hardeschijfbusintern; // origineel Hardeschijf bus (intern)_x000D_ private String behuizingbayintern;_x000D_ private String ssdeigenschappen;_x000D_ private String opslagcapaciteit;_x000D_ private String lezensequentieel; // origineel Lezen (sequentieel)_x000D_ private String prijspergb;_x000D_ private String ssdtype; // origineel SSD-type_x000D_ private String ssdcontroller; // origineel SSD-controller_x000D_ private String schrijvensequentieel; // origineel Schrijven (sequentieel)_x000D_ private String stroomverbruiklezen; // origineel Stroomverbruik (lezen)_x000D_ private String lezenrandom4k; // origineel Lezen (random 4K)_x000D_ private String schrijvenrandom4k; // origineel Schrijven (random 4K)_x000D_ private String drivecache;_x000D_ private String stroomverbruikschrijven; // origineel Stroomverbruik (schrijven)_x000D_ private String meantimebetweenfailures;_x000D_ private String hddssdaansluiting; // HDD/SSD-aansluiting_x000D_ _x000D_ public String getBeoordeling() {_x000D_ return beoordeling;_x000D_ }_x000D_ public void setBeoordeling(String beoordeling) {_x000D_ this.beoordeling = beoordeling;_x000D_ }_x000D_ public String getHoogte() {_x000D_ return hoogte;_x000D_ }_x000D_ public void setHoogte(String hoogte) {_x000D_ this.hoogte = hoogte;_x000D_ }_x000D_ public String getVerkoopstatus() {_x000D_ return verkoopstatus;_x000D_ }_x000D_ public void setVerkoopstatus(String verkoopstatus) {_x000D_ this.verkoopstatus = verkoopstatus;_x000D_ }_x000D_ public String getFabrieksgarantie() {_x000D_ return fabrieksgarantie;_x000D_ }_x000D_ public void setFabrieksgarantie(String fabrieksgarantie) {_x000D_ this.fabrieksgarantie = fabrieksgarantie;_x000D_ }_x000D_ public String getProduct() {_x000D_ return product;_x000D_ }_x000D_ public void setProduct(String product) {_x000D_ this.product = product;_x000D_ }_x000D_ public String getSerie() {_x000D_ return serie;_x000D_ }_x000D_ public void setSerie(String serie) {_x000D_ this.serie = serie;_x000D_ }_x000D_ public String getHardeschijfbusintern() {_x000D_ return hardeschijfbusintern;_x000D_ }_x000D_ public void setHardeschijfbusintern(String hardeschijfbusintern) {_x000D_ this.hardeschijfbusintern = hardeschijfbusintern;_x000D_ }_x000D_ public String getBehuizingbayintern() {_x000D_ return behuizingbayintern;_x000D_ }_x000D_ public void setBehuizingbayintern(String behuizingbayintern) {_x000D_ this.behuizingbayintern = behuizingbayintern;_x000D_ }_x000D_ public String getSsdeigenschappen() {_x000D_ return ssdeigenschappen;_x000D_ }_x000D_ public void setSsdeigenschappen(String ssdeigenschappen) {_x000D_ this.ssdeigenschappen = ssdeigenschappen;_x000D_ }_x000D_ public String getOpslagcapaciteit() {_x000D_ return opslagcapaciteit;_x000D_ }_x000D_ public void setOpslagcapaciteit(String opslagcapaciteit) {_x000D_ this.opslagcapaciteit = opslagcapaciteit;_x000D_ }_x000D_ public String getLezensequentieel() {_x000D_ return lezensequentieel;_x000D_ }_x000D_ public void setLezensequentieel(String lezensequentieel) {_x000D_ this.lezensequentieel = lezensequentieel;_x000D_ }_x000D_ public String getPrijspergb() {_x000D_ return prijspergb;_x000D_ }_x000D_ public void setPrijspergb(String prijspergb) {_x000D_ this.prijspergb = prijspergb;_x000D_ }_x000D_ public String getSsdtype() {_x000D_ return ssdtype;_x000D_ }_x000D_ public void setSsdtype(String ssdtype) {_x000D_ this.ssdtype = ssdtype;_x000D_ }_x000D_ public String getSsdcontroller() {_x000D_ return ssdcontroller;_x000D_ }_x000D_ public void setSsdcontroller(String ssdcontroller) {_x000D_ this.ssdcontroller = ssdcontroller;_x000D_ }_x000D_ public String getSchrijvensequentieel() {_x000D_ return schrijvensequentieel;_x000D_ }_x000D_ public void setSchrijvensequentieel(String schrijvensequentieel) {_x000D_ this.schrijvensequentieel = schrijvensequentieel;_x000D_ }_x000D_ public String getStroomverbruiklezen() {_x000D_ return stroomverbruiklezen;_x000D_ }_x000D_ public void setStroomverbruiklezen(String stroomverbruiklezen) {_x000D_ this.stroomverbruiklezen = stroomverbruiklezen;_x000D_ }_x000D_ public String getLezenrandom4k() {_x000D_ return lezenrandom4k;_x000D_ }_x000D_ public void setLezenrandom4k(String lezenrandom4k) {_x000D_ this.lezenrandom4k = lezenrandom4k;_x000D_ }_x000D_ public String getSchrijvenrandom4k() {_x000D_ return schrijvenrandom4k;_x000D_ }_x000D_ public void setSchrijvenrandom4k(String schrijvenrandom4k) {_x000D_ this.schrijvenrandom4k = schrijvenrandom4k;_x000D_ }_x000D_ public String getDrivecache() {_x000D_ return drivecache;_x000D_ }_x000D_ public void setDrivecache(String drivecache) {_x000D_ this.drivecache = drivecache;_x000D_ }_x000D_ public String getStroomverbruikschrijven() {_x000D_ return stroomverbruikschrijven;_x000D_ }_x000D_ public void setStroomverbruikschrijven(String stroomverbruikschrijven) {_x000D_ this.stroomverbruikschrijven = stroomverbruikschrijven;_x000D_ }_x000D_ public String getMeantimebetweenfailures() {_x000D_ return meantimebetweenfailures;_x000D_ }_x000D_ public void setMeantimebetweenfailures(String meantimebetweenfailures) {_x000D_ this.meantimebetweenfailures = meantimebetweenfailures;_x000D_ }_x000D_ public String getHddssdaansluiting() {_x000D_ return hddssdaansluiting;_x000D_ }_x000D_ public void setHddssdaansluiting(String hddssdaansluiting) {_x000D_ this.hddssdaansluiting = hddssdaansluiting;_x000D_ }_x000D_ }
Frenesius/PC-Builder-Matcher
src/components/SSD.java
1,785
// origineel Hardeschijf bus (intern)_x000D_
line_comment
nl
package components;_x000D_ /**_x000D_ * SSD class. Contains all the information that a Solid State Drive has._x000D_ * All the fields match the fields in the Neo4j Database._x000D_ * Extends {@link components.Hardware}_x000D_ *_x000D_ * @author Frenesius_x000D_ * @since 1-1-2015_x000D_ * @version 0.1_x000D_ */_x000D_ public class SSD extends Hardware{_x000D_ private String beoordeling;_x000D_ private String hoogte;_x000D_ private String verkoopstatus;_x000D_ private String fabrieksgarantie;_x000D_ private String product;_x000D_ private String serie;_x000D_ private String hardeschijfbusintern; // origineel Hardeschijf<SUF> private String behuizingbayintern;_x000D_ private String ssdeigenschappen;_x000D_ private String opslagcapaciteit;_x000D_ private String lezensequentieel; // origineel Lezen (sequentieel)_x000D_ private String prijspergb;_x000D_ private String ssdtype; // origineel SSD-type_x000D_ private String ssdcontroller; // origineel SSD-controller_x000D_ private String schrijvensequentieel; // origineel Schrijven (sequentieel)_x000D_ private String stroomverbruiklezen; // origineel Stroomverbruik (lezen)_x000D_ private String lezenrandom4k; // origineel Lezen (random 4K)_x000D_ private String schrijvenrandom4k; // origineel Schrijven (random 4K)_x000D_ private String drivecache;_x000D_ private String stroomverbruikschrijven; // origineel Stroomverbruik (schrijven)_x000D_ private String meantimebetweenfailures;_x000D_ private String hddssdaansluiting; // HDD/SSD-aansluiting_x000D_ _x000D_ public String getBeoordeling() {_x000D_ return beoordeling;_x000D_ }_x000D_ public void setBeoordeling(String beoordeling) {_x000D_ this.beoordeling = beoordeling;_x000D_ }_x000D_ public String getHoogte() {_x000D_ return hoogte;_x000D_ }_x000D_ public void setHoogte(String hoogte) {_x000D_ this.hoogte = hoogte;_x000D_ }_x000D_ public String getVerkoopstatus() {_x000D_ return verkoopstatus;_x000D_ }_x000D_ public void setVerkoopstatus(String verkoopstatus) {_x000D_ this.verkoopstatus = verkoopstatus;_x000D_ }_x000D_ public String getFabrieksgarantie() {_x000D_ return fabrieksgarantie;_x000D_ }_x000D_ public void setFabrieksgarantie(String fabrieksgarantie) {_x000D_ this.fabrieksgarantie = fabrieksgarantie;_x000D_ }_x000D_ public String getProduct() {_x000D_ return product;_x000D_ }_x000D_ public void setProduct(String product) {_x000D_ this.product = product;_x000D_ }_x000D_ public String getSerie() {_x000D_ return serie;_x000D_ }_x000D_ public void setSerie(String serie) {_x000D_ this.serie = serie;_x000D_ }_x000D_ public String getHardeschijfbusintern() {_x000D_ return hardeschijfbusintern;_x000D_ }_x000D_ public void setHardeschijfbusintern(String hardeschijfbusintern) {_x000D_ this.hardeschijfbusintern = hardeschijfbusintern;_x000D_ }_x000D_ public String getBehuizingbayintern() {_x000D_ return behuizingbayintern;_x000D_ }_x000D_ public void setBehuizingbayintern(String behuizingbayintern) {_x000D_ this.behuizingbayintern = behuizingbayintern;_x000D_ }_x000D_ public String getSsdeigenschappen() {_x000D_ return ssdeigenschappen;_x000D_ }_x000D_ public void setSsdeigenschappen(String ssdeigenschappen) {_x000D_ this.ssdeigenschappen = ssdeigenschappen;_x000D_ }_x000D_ public String getOpslagcapaciteit() {_x000D_ return opslagcapaciteit;_x000D_ }_x000D_ public void setOpslagcapaciteit(String opslagcapaciteit) {_x000D_ this.opslagcapaciteit = opslagcapaciteit;_x000D_ }_x000D_ public String getLezensequentieel() {_x000D_ return lezensequentieel;_x000D_ }_x000D_ public void setLezensequentieel(String lezensequentieel) {_x000D_ this.lezensequentieel = lezensequentieel;_x000D_ }_x000D_ public String getPrijspergb() {_x000D_ return prijspergb;_x000D_ }_x000D_ public void setPrijspergb(String prijspergb) {_x000D_ this.prijspergb = prijspergb;_x000D_ }_x000D_ public String getSsdtype() {_x000D_ return ssdtype;_x000D_ }_x000D_ public void setSsdtype(String ssdtype) {_x000D_ this.ssdtype = ssdtype;_x000D_ }_x000D_ public String getSsdcontroller() {_x000D_ return ssdcontroller;_x000D_ }_x000D_ public void setSsdcontroller(String ssdcontroller) {_x000D_ this.ssdcontroller = ssdcontroller;_x000D_ }_x000D_ public String getSchrijvensequentieel() {_x000D_ return schrijvensequentieel;_x000D_ }_x000D_ public void setSchrijvensequentieel(String schrijvensequentieel) {_x000D_ this.schrijvensequentieel = schrijvensequentieel;_x000D_ }_x000D_ public String getStroomverbruiklezen() {_x000D_ return stroomverbruiklezen;_x000D_ }_x000D_ public void setStroomverbruiklezen(String stroomverbruiklezen) {_x000D_ this.stroomverbruiklezen = stroomverbruiklezen;_x000D_ }_x000D_ public String getLezenrandom4k() {_x000D_ return lezenrandom4k;_x000D_ }_x000D_ public void setLezenrandom4k(String lezenrandom4k) {_x000D_ this.lezenrandom4k = lezenrandom4k;_x000D_ }_x000D_ public String getSchrijvenrandom4k() {_x000D_ return schrijvenrandom4k;_x000D_ }_x000D_ public void setSchrijvenrandom4k(String schrijvenrandom4k) {_x000D_ this.schrijvenrandom4k = schrijvenrandom4k;_x000D_ }_x000D_ public String getDrivecache() {_x000D_ return drivecache;_x000D_ }_x000D_ public void setDrivecache(String drivecache) {_x000D_ this.drivecache = drivecache;_x000D_ }_x000D_ public String getStroomverbruikschrijven() {_x000D_ return stroomverbruikschrijven;_x000D_ }_x000D_ public void setStroomverbruikschrijven(String stroomverbruikschrijven) {_x000D_ this.stroomverbruikschrijven = stroomverbruikschrijven;_x000D_ }_x000D_ public String getMeantimebetweenfailures() {_x000D_ return meantimebetweenfailures;_x000D_ }_x000D_ public void setMeantimebetweenfailures(String meantimebetweenfailures) {_x000D_ this.meantimebetweenfailures = meantimebetweenfailures;_x000D_ }_x000D_ public String getHddssdaansluiting() {_x000D_ return hddssdaansluiting;_x000D_ }_x000D_ public void setHddssdaansluiting(String hddssdaansluiting) {_x000D_ this.hddssdaansluiting = hddssdaansluiting;_x000D_ }_x000D_ }
True
False
1,485
711
8497_0
package Spel; import Tools.*; import javax.swing.JFrame; import java.util.ArrayList; /** * Deze klasse zorgt voor de dynamica van het spel. * * @author (E.E. Koldenhof) * @version (V.1.0) * * Deze klasse mag je NIET veranderen * */ public class Beweeg{ private ArrayList<KanBewegen> beweegLijst; /** * Vult de 4 basis objecten die de controller nodig heeft om de * dynamica van het spel te kunnen afhandelen */ public Beweeg(){ beweegLijst = new ArrayList<KanBewegen>(); } public void voegObjectToe(KanBewegen o){ beweegLijst.add(o); } public void verwijderObject(KanBewegen o){ beweegLijst.remove(o); } public void voegLijstToe(ArrayList lijst){ beweegLijst.addAll(lijst); } public void verwijderLijst(ArrayList lijst){ beweegLijst.removeAll(lijst); } public void beweegAlles(float stapGrootte){ int teller = 0; while (teller < beweegLijst.size()){ beweegLijst.get(teller).beweeg(stapGrootte); teller ++; } } }
Hutsmeister/Spel
Spelluhtjuh/Spel/Beweeg.java
413
/** * Deze klasse zorgt voor de dynamica van het spel. * * @author (E.E. Koldenhof) * @version (V.1.0) * * Deze klasse mag je NIET veranderen * */
block_comment
nl
package Spel; import Tools.*; import javax.swing.JFrame; import java.util.ArrayList; /** * Deze klasse zorgt<SUF>*/ public class Beweeg{ private ArrayList<KanBewegen> beweegLijst; /** * Vult de 4 basis objecten die de controller nodig heeft om de * dynamica van het spel te kunnen afhandelen */ public Beweeg(){ beweegLijst = new ArrayList<KanBewegen>(); } public void voegObjectToe(KanBewegen o){ beweegLijst.add(o); } public void verwijderObject(KanBewegen o){ beweegLijst.remove(o); } public void voegLijstToe(ArrayList lijst){ beweegLijst.addAll(lijst); } public void verwijderLijst(ArrayList lijst){ beweegLijst.removeAll(lijst); } public void beweegAlles(float stapGrootte){ int teller = 0; while (teller < beweegLijst.size()){ beweegLijst.get(teller).beweeg(stapGrootte); teller ++; } } }
True
False
1,486
1,729
79106_0
package Chess.Core.Pieces; import Chess.Core.*; import Chess.Core.Usecases.ListAvailableMoves.ListAvailableBlackPawnMoves; import Chess.Core.Usecases.ListAvailableMoves.ListAvailableWhitePawnMoves; import Chess.Core.Usecases.LocateKing.LocateKing; import java.util.HashSet; // TODO // - De witte pawn geeft een verkeerde available move: // +-------+-------+-------+-------+-------+-------+-------+-------+ // | | | | * * | | | | | // | | | | | | | | | 6 // | | | | * * | | | | | // +-------+-------+-------+-------+-------+-------+-------+-------+ // | | | | | | | | | // | | | | | (P) | P | | | 5 (En passant row) // | | | | | | | | | // +-------+-------+-------+-------+-------+-------+-------+-------+ public class Pawn extends Piece { private final PromotionHandler promotionHandler; public Pawn(Color color, Board board) { super(color, board); this.promotionHandler = (pawn, location) -> {}; } public Pawn(Color color, Board board, PromotionHandler promotionHandler) { super(color, board); this.promotionHandler = promotionHandler; } /** * Checks if the pawn reached the end of the board and if so calls the promotion-handler to handle the promotion of the pawn. * * @param state The current state of the game. * @param location The current location of the chess piece. * @param destination The destination of the chess piece. * @throws MoveNotPossible When the piece cannot be moved the the specified destination. */ @Override public void move(State state, Coords location, Coords destination) throws MoveNotPossible, Field.NoPieceAvailable, Board.FieldNotFound, LocateKing.KingNotFound { if (isEnPassantMove(location, destination)) { executeEnPassantMove(location, destination); setMoves(getMoves() + 1); } else super.move(state, location, destination); if (destination.y() >= 8 || destination.y() <= 1) promotionHandler.handlePromotion(this, destination); } @Override public HashSet<Coords> availableMoves(State state, Coords location) throws Field.NoPieceAvailable, Board.FieldNotFound, LocateKing.KingNotFound { var listMoves = switch (getColor()) { case white -> new ListAvailableWhitePawnMoves(); case black -> new ListAvailableBlackPawnMoves(); }; var moves = listMoves.list(getBoard(), location); removeMovesThatCausesChecks(state, location, moves); return moves; } private boolean isEnPassantMove(Coords location, Coords destination) { return !getBoard().pieceOnField(destination) && location.x() != destination.x(); } private void executeEnPassantMove(Coords location, Coords destination) throws Field.NoPieceAvailable, Board.FieldNotFound { var board = getBoard(); switch (getColor()) { case black -> board.removePiece(new Coords(destination.x(), destination.y() + 1)); case white -> board.removePiece(new Coords(destination.x(), destination.y() - 1)); } board.setPiece(destination, this); board.removePiece(location); } }
ThomasLuchies/projecten
OOP projecten/schaken/src/Chess/Core/Pieces/Pawn.java
1,041
// - De witte pawn geeft een verkeerde available move:
line_comment
nl
package Chess.Core.Pieces; import Chess.Core.*; import Chess.Core.Usecases.ListAvailableMoves.ListAvailableBlackPawnMoves; import Chess.Core.Usecases.ListAvailableMoves.ListAvailableWhitePawnMoves; import Chess.Core.Usecases.LocateKing.LocateKing; import java.util.HashSet; // TODO // - De<SUF> // +-------+-------+-------+-------+-------+-------+-------+-------+ // | | | | * * | | | | | // | | | | | | | | | 6 // | | | | * * | | | | | // +-------+-------+-------+-------+-------+-------+-------+-------+ // | | | | | | | | | // | | | | | (P) | P | | | 5 (En passant row) // | | | | | | | | | // +-------+-------+-------+-------+-------+-------+-------+-------+ public class Pawn extends Piece { private final PromotionHandler promotionHandler; public Pawn(Color color, Board board) { super(color, board); this.promotionHandler = (pawn, location) -> {}; } public Pawn(Color color, Board board, PromotionHandler promotionHandler) { super(color, board); this.promotionHandler = promotionHandler; } /** * Checks if the pawn reached the end of the board and if so calls the promotion-handler to handle the promotion of the pawn. * * @param state The current state of the game. * @param location The current location of the chess piece. * @param destination The destination of the chess piece. * @throws MoveNotPossible When the piece cannot be moved the the specified destination. */ @Override public void move(State state, Coords location, Coords destination) throws MoveNotPossible, Field.NoPieceAvailable, Board.FieldNotFound, LocateKing.KingNotFound { if (isEnPassantMove(location, destination)) { executeEnPassantMove(location, destination); setMoves(getMoves() + 1); } else super.move(state, location, destination); if (destination.y() >= 8 || destination.y() <= 1) promotionHandler.handlePromotion(this, destination); } @Override public HashSet<Coords> availableMoves(State state, Coords location) throws Field.NoPieceAvailable, Board.FieldNotFound, LocateKing.KingNotFound { var listMoves = switch (getColor()) { case white -> new ListAvailableWhitePawnMoves(); case black -> new ListAvailableBlackPawnMoves(); }; var moves = listMoves.list(getBoard(), location); removeMovesThatCausesChecks(state, location, moves); return moves; } private boolean isEnPassantMove(Coords location, Coords destination) { return !getBoard().pieceOnField(destination) && location.x() != destination.x(); } private void executeEnPassantMove(Coords location, Coords destination) throws Field.NoPieceAvailable, Board.FieldNotFound { var board = getBoard(); switch (getColor()) { case black -> board.removePiece(new Coords(destination.x(), destination.y() + 1)); case white -> board.removePiece(new Coords(destination.x(), destination.y() - 1)); } board.setPiece(destination, this); board.removePiece(location); } }
True
False
1,489
630
3031_1
package controller;_x000D_ _x000D_ import java.util.ArrayList;_x000D_ _x000D_ import javax.json.Json;_x000D_ import javax.json.JsonArrayBuilder;_x000D_ import javax.json.JsonObject;_x000D_ _x000D_ import model.Docent;_x000D_ import model.PrIS;_x000D_ import model.Vak;_x000D_ import server.Conversation;_x000D_ import server.Handler;_x000D_ _x000D_ public class DocentController implements Handler {_x000D_ private PrIS informatieSysteem;_x000D_ _x000D_ /**_x000D_ * De DocentController klasse moet alle docent-gerelateerde aanvragen_x000D_ * afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat_x000D_ * dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI_x000D_ * een nieuwe methode schrijven._x000D_ * _x000D_ * @param infoSys - het toegangspunt tot het domeinmodel_x000D_ */_x000D_ public DocentController(PrIS infoSys) {_x000D_ informatieSysteem = infoSys;_x000D_ }_x000D_ _x000D_ public void handle(Conversation conversation) {_x000D_ if (conversation.getRequestedURI().startsWith("/docent/mijnvakken")) {_x000D_ mijnVakken(conversation);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden_x000D_ * de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden_x000D_ * dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!_x000D_ * _x000D_ * @param conversation - alle informatie over het request_x000D_ */_x000D_ private void mijnVakken(Conversation conversation) {_x000D_ JsonObject jsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();_x000D_ String gebruikersnaam = jsonObjectIn.getString("username");_x000D_ _x000D_ Docent docent = informatieSysteem.getDocent(gebruikersnaam); // Docent-object ophalen!_x000D_ ArrayList<Vak> vakken = docent.getVakken(); // Vakken van de docent ophalen!_x000D_ _x000D_ JsonArrayBuilder jab = Json.createArrayBuilder(); // En uiteindelijk gaat er een JSON-array met..._x000D_ _x000D_ for (Vak v : vakken) {_x000D_ jab.add(Json.createObjectBuilder() // daarin voor elk vak een JSON-object..._x000D_ .add("vakcode", v.getVakCode())_x000D_ .add("vaknaam", v.getVakNaam()));_x000D_ }_x000D_ _x000D_ conversation.sendJSONMessage(jab.build().toString()); // terug naar de Polymer-GUI!_x000D_ }_x000D_ }_x000D_
Gundraub/PrIS
src/controller/DocentController.java
697
/**_x000D_ * Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden_x000D_ * de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden_x000D_ * dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!_x000D_ * _x000D_ * @param conversation - alle informatie over het request_x000D_ */
block_comment
nl
package controller;_x000D_ _x000D_ import java.util.ArrayList;_x000D_ _x000D_ import javax.json.Json;_x000D_ import javax.json.JsonArrayBuilder;_x000D_ import javax.json.JsonObject;_x000D_ _x000D_ import model.Docent;_x000D_ import model.PrIS;_x000D_ import model.Vak;_x000D_ import server.Conversation;_x000D_ import server.Handler;_x000D_ _x000D_ public class DocentController implements Handler {_x000D_ private PrIS informatieSysteem;_x000D_ _x000D_ /**_x000D_ * De DocentController klasse moet alle docent-gerelateerde aanvragen_x000D_ * afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat_x000D_ * dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI_x000D_ * een nieuwe methode schrijven._x000D_ * _x000D_ * @param infoSys - het toegangspunt tot het domeinmodel_x000D_ */_x000D_ public DocentController(PrIS infoSys) {_x000D_ informatieSysteem = infoSys;_x000D_ }_x000D_ _x000D_ public void handle(Conversation conversation) {_x000D_ if (conversation.getRequestedURI().startsWith("/docent/mijnvakken")) {_x000D_ mijnVakken(conversation);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode haalt<SUF>*/_x000D_ private void mijnVakken(Conversation conversation) {_x000D_ JsonObject jsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();_x000D_ String gebruikersnaam = jsonObjectIn.getString("username");_x000D_ _x000D_ Docent docent = informatieSysteem.getDocent(gebruikersnaam); // Docent-object ophalen!_x000D_ ArrayList<Vak> vakken = docent.getVakken(); // Vakken van de docent ophalen!_x000D_ _x000D_ JsonArrayBuilder jab = Json.createArrayBuilder(); // En uiteindelijk gaat er een JSON-array met..._x000D_ _x000D_ for (Vak v : vakken) {_x000D_ jab.add(Json.createObjectBuilder() // daarin voor elk vak een JSON-object..._x000D_ .add("vakcode", v.getVakCode())_x000D_ .add("vaknaam", v.getVakNaam()));_x000D_ }_x000D_ _x000D_ conversation.sendJSONMessage(jab.build().toString()); // terug naar de Polymer-GUI!_x000D_ }_x000D_ }_x000D_
True
False
1,490
254
29534_4
package activemq;_x000D_ _x000D_ import algoritmes.ConcurrentMergeSort;_x000D_ import helper.CustomUtilities;_x000D_ import org.apache.activemq.ActiveMQConnectionFactory;_x000D_ _x000D_ import javax.jms.*;_x000D_ import java.util.ArrayList;_x000D_ import java.util.List;_x000D_ _x000D_ import static helper.Config.ACTIVEMQ_URL;_x000D_ _x000D_ /**_x000D_ * Parallel Computing_x000D_ * AUTHOR: R. Lobato & C. Verra_x000D_ */_x000D_ public class Consumer {_x000D_ private static String subject = "resultaat";_x000D_ _x000D_ public static void main(String[] args) throws JMSException {_x000D_ ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);_x000D_ Connection connection = connectionFactory.createConnection();_x000D_ connection.start();_x000D_ _x000D_ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);_x000D_ Destination destination = session.createQueue(subject);_x000D_ MessageConsumer consumer = session.createConsumer(destination);_x000D_ _x000D_ int count = 0;_x000D_ _x000D_ // Lijst van Integers_x000D_ List<Integer> list = new ArrayList<>();_x000D_ _x000D_ while (true) {_x000D_ _x000D_ Message message = consumer.receive();_x000D_ if (message instanceof TextMessage) {_x000D_ count++;_x000D_ TextMessage textMessage = (TextMessage) message;_x000D_ _x000D_ // String aan integers opslaan_x000D_ String str = textMessage.getText();_x000D_ // String aan integers opsplitten_x000D_ String[] integerStrings = str.split(" ");_x000D_ _x000D_ // Parse String Integers naar ints_x000D_ for (String integerString : integerStrings) {_x000D_ int j = Integer.parseInt(integerString);_x000D_ // Voeg toe aan list_x000D_ list.add(j);_x000D_ }_x000D_ _x000D_ // Als het aantal lijsten gelijk is aan het aantal producers_x000D_ if (count == Producer.NODES) {_x000D_ int[] array = list.stream().mapToInt(i -> i).toArray();_x000D_ // Sorteer lijsten individueel_x000D_ ConcurrentMergeSort concurrentMergeSort = new ConcurrentMergeSort(array);_x000D_ concurrentMergeSort.sort();_x000D_ _x000D_ if (CustomUtilities.isArraySorted(array))_x000D_ break;_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ connection.close();_x000D_ }_x000D_ }
Buggyy/Parallel-Computing
src/activemq/Consumer.java
603
// Parse String Integers naar ints_x000D_
line_comment
nl
package activemq;_x000D_ _x000D_ import algoritmes.ConcurrentMergeSort;_x000D_ import helper.CustomUtilities;_x000D_ import org.apache.activemq.ActiveMQConnectionFactory;_x000D_ _x000D_ import javax.jms.*;_x000D_ import java.util.ArrayList;_x000D_ import java.util.List;_x000D_ _x000D_ import static helper.Config.ACTIVEMQ_URL;_x000D_ _x000D_ /**_x000D_ * Parallel Computing_x000D_ * AUTHOR: R. Lobato & C. Verra_x000D_ */_x000D_ public class Consumer {_x000D_ private static String subject = "resultaat";_x000D_ _x000D_ public static void main(String[] args) throws JMSException {_x000D_ ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);_x000D_ Connection connection = connectionFactory.createConnection();_x000D_ connection.start();_x000D_ _x000D_ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);_x000D_ Destination destination = session.createQueue(subject);_x000D_ MessageConsumer consumer = session.createConsumer(destination);_x000D_ _x000D_ int count = 0;_x000D_ _x000D_ // Lijst van Integers_x000D_ List<Integer> list = new ArrayList<>();_x000D_ _x000D_ while (true) {_x000D_ _x000D_ Message message = consumer.receive();_x000D_ if (message instanceof TextMessage) {_x000D_ count++;_x000D_ TextMessage textMessage = (TextMessage) message;_x000D_ _x000D_ // String aan integers opslaan_x000D_ String str = textMessage.getText();_x000D_ // String aan integers opsplitten_x000D_ String[] integerStrings = str.split(" ");_x000D_ _x000D_ // Parse String<SUF> for (String integerString : integerStrings) {_x000D_ int j = Integer.parseInt(integerString);_x000D_ // Voeg toe aan list_x000D_ list.add(j);_x000D_ }_x000D_ _x000D_ // Als het aantal lijsten gelijk is aan het aantal producers_x000D_ if (count == Producer.NODES) {_x000D_ int[] array = list.stream().mapToInt(i -> i).toArray();_x000D_ // Sorteer lijsten individueel_x000D_ ConcurrentMergeSort concurrentMergeSort = new ConcurrentMergeSort(array);_x000D_ concurrentMergeSort.sort();_x000D_ _x000D_ if (CustomUtilities.isArraySorted(array))_x000D_ break;_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ connection.close();_x000D_ }_x000D_ }
True
False
1,491
3,057
36150_0
package be.ibizz.hackathon.repository; import java.io.Reader; import org.ektorp.CouchDbConnector; import org.ektorp.dataload.DataLoader; import org.ektorp.support.CouchDbRepositorySupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import be.ibizz.hackathon.util.loader.CustomDataLoader; /** * Deze abstracte klasse gebruiken we voor alle onderliggende repository classes. Een repository is simpleweg een * klasse die we gebruiken om data te lezen/schrijven. In dit geval dus naar Cloudant. * * De datafiles die hier meegegeven worden zijn de JSON bestanden die je vindt onder src/main/resources/database. * Bij de start van de applicatie wordt deze json data ingeladen in cloudant om snel van start te kunnen gaan. */ public abstract class AbstractCloudantRepository<T> extends CouchDbRepositorySupport<T> implements DataLoader { private static final Logger LOGGER = LoggerFactory.getLogger(AccountRepository.class); private String[] dataFiles; protected AbstractCloudantRepository(Class<T> type, CouchDbConnector db, String... dataFiles) { super(type, db); this.dataFiles = dataFiles; initStandardDesignDocument(); } @Override public void loadInitialData(Reader in) { new CustomDataLoader(db).load(in, type); } @Override public void allDataLoaded() { for(String dataFile : dataFiles) { LOGGER.info("Uploaded '{}'", dataFile); } } @Override public String[] getDataLocations() { return dataFiles; } }
ibizz/hackathon-ucll
app/AB InBev/src/main/java/be/ibizz/hackathon/repository/AbstractCloudantRepository.java
461
/** * Deze abstracte klasse gebruiken we voor alle onderliggende repository classes. Een repository is simpleweg een * klasse die we gebruiken om data te lezen/schrijven. In dit geval dus naar Cloudant. * * De datafiles die hier meegegeven worden zijn de JSON bestanden die je vindt onder src/main/resources/database. * Bij de start van de applicatie wordt deze json data ingeladen in cloudant om snel van start te kunnen gaan. */
block_comment
nl
package be.ibizz.hackathon.repository; import java.io.Reader; import org.ektorp.CouchDbConnector; import org.ektorp.dataload.DataLoader; import org.ektorp.support.CouchDbRepositorySupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import be.ibizz.hackathon.util.loader.CustomDataLoader; /** * Deze abstracte klasse<SUF>*/ public abstract class AbstractCloudantRepository<T> extends CouchDbRepositorySupport<T> implements DataLoader { private static final Logger LOGGER = LoggerFactory.getLogger(AccountRepository.class); private String[] dataFiles; protected AbstractCloudantRepository(Class<T> type, CouchDbConnector db, String... dataFiles) { super(type, db); this.dataFiles = dataFiles; initStandardDesignDocument(); } @Override public void loadInitialData(Reader in) { new CustomDataLoader(db).load(in, type); } @Override public void allDataLoaded() { for(String dataFile : dataFiles) { LOGGER.info("Uploaded '{}'", dataFile); } } @Override public String[] getDataLocations() { return dataFiles; } }
True
False
1,493
3,163
186809_11
package com.nhlstenden.JabberPoint.Slides; import com.nhlstenden.JabberPoint.Styles.Style; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.image.ImageObserver; import java.util.Vector; /** <p>Een slide. Deze klasse heeft tekenfunctionaliteit.</p> * @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman * @version 1.1 2002/12/17 Gert Florijn * @version 1.2 2003/11/19 Sylvia Stuurman * @version 1.3 2004/08/17 Sylvia Stuurman * @version 1.4 2007/07/16 Sylvia Stuurman * @version 1.5 2010/03/03 Sylvia Stuurman * @version 1.6 2014/05/16 Sylvia Stuurman */ public class Slide { public final static int WIDTH = 1200; public final static int HEIGHT = 800; // De titel wordt apart bewaard private String title; // De slide-items worden in een Vector bewaard private Vector<SlideItem> items; public Slide() { this.items = new Vector<SlideItem>(); } // Voeg een SlideItem toe public void append(SlideItem anItem) { this.items.addElement(anItem); } // Geef de titel van de slide public String getTitle() { return this.title; } // Verander de titel van de slide public void setTitle(String newTitle) { this.title = newTitle; } public Vector<SlideItem> getItems() { return this.items; } public void setItems(Vector<SlideItem> items) { this.items = items; } // Maak een TextItem van String, en voeg het TextItem toe public void appendTextItem(int level, String message) { this.append(new TextItem(level, message)); } // Geef het betreffende SlideItem public SlideItem getSlideItem(int number) { return (SlideItem) this.items.elementAt(number); } // Geef alle SlideItems in een Vector public Vector<SlideItem> getSlideItems() { return this.items; } // Geef de afmeting van de Slide public int getSize() { return this.items.size(); } // Teken de slide public void draw(Graphics graphics, Rectangle area, ImageObserver view) { float scale = this.getScale(area); int y = area.y; // De titel wordt apart behandeld SlideItem slideItem = new TextItem(0, this.getTitle()); Style style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; for (int number = 0; number < this.getSize(); number++) { slideItem = (SlideItem) this.getSlideItems().elementAt(number); style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; } } // Geef de schaal om de slide te kunnen tekenen private float getScale(Rectangle area) { return Math.min(((float) area.width) / ((float) WIDTH), ((float) area.height) / ((float) HEIGHT)); } }
jariolyslager/SoftwareQuality
src/main/java/com/nhlstenden/JabberPoint/Slides/Slide.java
1,010
// De titel wordt apart behandeld
line_comment
nl
package com.nhlstenden.JabberPoint.Slides; import com.nhlstenden.JabberPoint.Styles.Style; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.image.ImageObserver; import java.util.Vector; /** <p>Een slide. Deze klasse heeft tekenfunctionaliteit.</p> * @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman * @version 1.1 2002/12/17 Gert Florijn * @version 1.2 2003/11/19 Sylvia Stuurman * @version 1.3 2004/08/17 Sylvia Stuurman * @version 1.4 2007/07/16 Sylvia Stuurman * @version 1.5 2010/03/03 Sylvia Stuurman * @version 1.6 2014/05/16 Sylvia Stuurman */ public class Slide { public final static int WIDTH = 1200; public final static int HEIGHT = 800; // De titel wordt apart bewaard private String title; // De slide-items worden in een Vector bewaard private Vector<SlideItem> items; public Slide() { this.items = new Vector<SlideItem>(); } // Voeg een SlideItem toe public void append(SlideItem anItem) { this.items.addElement(anItem); } // Geef de titel van de slide public String getTitle() { return this.title; } // Verander de titel van de slide public void setTitle(String newTitle) { this.title = newTitle; } public Vector<SlideItem> getItems() { return this.items; } public void setItems(Vector<SlideItem> items) { this.items = items; } // Maak een TextItem van String, en voeg het TextItem toe public void appendTextItem(int level, String message) { this.append(new TextItem(level, message)); } // Geef het betreffende SlideItem public SlideItem getSlideItem(int number) { return (SlideItem) this.items.elementAt(number); } // Geef alle SlideItems in een Vector public Vector<SlideItem> getSlideItems() { return this.items; } // Geef de afmeting van de Slide public int getSize() { return this.items.size(); } // Teken de slide public void draw(Graphics graphics, Rectangle area, ImageObserver view) { float scale = this.getScale(area); int y = area.y; // De titel<SUF> SlideItem slideItem = new TextItem(0, this.getTitle()); Style style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; for (int number = 0; number < this.getSize(); number++) { slideItem = (SlideItem) this.getSlideItems().elementAt(number); style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; } } // Geef de schaal om de slide te kunnen tekenen private float getScale(Rectangle area) { return Math.min(((float) area.width) / ((float) WIDTH), ((float) area.height) / ((float) HEIGHT)); } }
True
False
1,495
4,444
75609_1
package nl.topicus.onderwijs.uwlr.shared.webservice.interceptors; import nl.topicus.onderwijs.generated.uwlr.v2_2.UwlrServiceInterfaceV2; import nl.topicus.onderwijs.uwlr.shared.webservice.SoapFault; import org.apache.cxf.binding.soap.SoapMessage; import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; import org.apache.cxf.phase.Phase; /** * Interceptor die uitgaande berichten van de {@link UwlrServiceInterfaceV2} implementatie afvangt * en kijkt of er een {@link Exception} in het bericht verpakt zit. Als dit het geval is wordt de * {@link Exception} vervangen door een {@link SoapFault}, die voldoet aan de foutberichten uit de * UWLR afspraak. */ public class FaultInterceptor extends AbstractSoapInterceptor { public FaultInterceptor() { super(Phase.PRE_LOGICAL); } @Override public void handleMessage(final SoapMessage message) { // Kijk of in de message een Exception verpakt zit Object exception = message.getContent(Exception.class); // Als er een exception is die niet van het type SoapFault is, dan moet deze // vertaald worden naar een SoapFault. if (exception != null && (!(message.getContent(Exception.class) instanceof SoapFault))) message.setContent( Exception.class, SoapFault.createSoapFault(((Exception) exception).getCause())); } }
takirchjunger/uwlr-client-server
src/main/java/nl/topicus/onderwijs/uwlr/shared/webservice/interceptors/FaultInterceptor.java
431
// Kijk of in de message een Exception verpakt zit
line_comment
nl
package nl.topicus.onderwijs.uwlr.shared.webservice.interceptors; import nl.topicus.onderwijs.generated.uwlr.v2_2.UwlrServiceInterfaceV2; import nl.topicus.onderwijs.uwlr.shared.webservice.SoapFault; import org.apache.cxf.binding.soap.SoapMessage; import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; import org.apache.cxf.phase.Phase; /** * Interceptor die uitgaande berichten van de {@link UwlrServiceInterfaceV2} implementatie afvangt * en kijkt of er een {@link Exception} in het bericht verpakt zit. Als dit het geval is wordt de * {@link Exception} vervangen door een {@link SoapFault}, die voldoet aan de foutberichten uit de * UWLR afspraak. */ public class FaultInterceptor extends AbstractSoapInterceptor { public FaultInterceptor() { super(Phase.PRE_LOGICAL); } @Override public void handleMessage(final SoapMessage message) { // Kijk of<SUF> Object exception = message.getContent(Exception.class); // Als er een exception is die niet van het type SoapFault is, dan moet deze // vertaald worden naar een SoapFault. if (exception != null && (!(message.getContent(Exception.class) instanceof SoapFault))) message.setContent( Exception.class, SoapFault.createSoapFault(((Exception) exception).getCause())); } }
True
False
1,497
4,585
7319_3
package be.thomaswinters.similarreplacer; import be.thomaswinters.LambdaExceptionUtil; import be.thomaswinters.markov.model.data.bags.Bag; import be.thomaswinters.markov.model.data.bags.WriteableBag; import be.thomaswinters.markov.model.data.bags.impl.ExclusionBag; import be.thomaswinters.markov.model.data.bags.impl.MutableBag; import be.thomaswinters.random.Picker; import be.thomaswinters.replacement.Replacer; import be.thomaswinters.replacement.Replacers; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.JLanguageTool; import org.languagetool.language.Dutch; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; public class SimilarWordReplacer { /*-********************************************-* * STATIC TOOLS *-********************************************-*/ private static final JLanguageTool langTool = new JLanguageTool(new Dutch()); protected static final Random RANDOM = new Random(); /*-********************************************-*/ /*-********************************************-* * INSTANCE VARIABLES *-********************************************-*/ private Map<Set<String>, WriteableBag<String>> mappings = new HashMap<>(); /*-********************************************-*/ /*-********************************************-* * TAGS & TOKEN FILTERING *-********************************************-*/ protected Set<String> getTags(AnalyzedTokenReadings token) { return token.getReadings().stream().filter(e -> !e.hasNoTag()).map(e -> e.getPOSTag()) .filter(e -> e != null && !e.equals("SENT_END") && !e.equals("PARA_END")).collect(Collectors.toSet()); } private static final Set<String> REPLACEMENT_TOKEN_BLACKLIST = new HashSet<>(Arrays.asList( // Lidwoorden "de", "het", "een", // Algemene onderwerpen "ik", "jij", "je", "u", "wij", "we", "jullie", "hij", "zij", "ze", // Algemene persoonlijke voornaamwoorden "hen", "hem", "haar", "mijn", "uw", "jouw", "onze", "ons", // Algemene werkwoorden "ben", "bent", "is", "was", "waren", "geweest", "heb", "hebt", "heeft", "hebben", "gehad", "word", "wordt", "worden", "geworden", "werd", "werden", "laat", "laten", "liet", "lieten", "gelaten", "ga", "gaat", "gaan", "gegaan", "ging", "gingen", "moet", "moeten", "moest", "moesten", "gemoeten", "mag", "mogen", "mocht", "mochten", "gemogen", "zal", "zullen", "zult", "zou", "zouden", "kan", "kunnen", "gekunt", "gekunnen", "hoef", "hoeft", "hoeven", "hoefde", "hoefden", "gehoeven", // Veelgebruikte woorden "niet", "iets", "dan", "voort", "erna", "welke", "maar", "van", "voor", "met", "binnenkort", "in", "en", "teveel", "om", "alles", "elke", "al", "echt", "waar", "waarom", "hoe", "o.a.", "beetje", "enkel", "goed", "best", "werkende", "meer", "voor", "zit", "echt", "uit", "even", "wel")); private static final Set<String> REPLACEMENT_TAG_BLACKLIST = new HashSet<>( Arrays.asList("AVwaar", "AVwr", "DTh", "DTd", "DTe", "DTp", "PRte", "PRnaar", "PRvan", "PN2", "PRVoor", "PRmet", "PRop", "PRin", "PRom", "PRaan", "AVdr", "CJo")); private List<AnalyzedTokenReadings> filterTokens(List<AnalyzedTokenReadings> tokens) { return tokens.stream().filter(e -> e.getToken().trim().length() > 0).filter(e -> !e.getReadings().isEmpty()) .filter(token -> !getTags(token).isEmpty()) .filter(token -> getTags(token).stream().allMatch(tag -> !REPLACEMENT_TAG_BLACKLIST.contains(tag))) .filter(token -> !REPLACEMENT_TOKEN_BLACKLIST.contains(token.getToken().toLowerCase())) .collect(Collectors.toList()); } /*-********************************************-*/ /*-********************************************-* * PROCESSING KNOWLEDGE INPUT *-********************************************-*/ public void process(String line) throws IOException { List<AnalyzedSentence> answers = langTool.analyzeText(line); for (AnalyzedSentence analyzedSentence : answers) { List<AnalyzedTokenReadings> tokens = filterTokens(Arrays.asList(analyzedSentence.getTokens())); for (AnalyzedTokenReadings token : tokens) { if (token.getToken().trim().length() > 0) { Set<String> tags = getTags(token); // Add if valid if (tags != null && tags.size() > 0) { if (!mappings.containsKey(tags)) { mappings.put(tags, new MutableBag<String>()); } mappings.get(tags).add(token.getToken()); } } } } } public void process(List<String> lines) { lines.forEach(LambdaExceptionUtil.rethrowConsumer(this::process)); } /*-********************************************-*/ /*-********************************************-* * REPLACEABLE CALCULATION *-********************************************-*/ public int getReplaceableSize(Set<String> tags) { if (!mappings.containsKey(tags)) { return 0; } return mappings.get(tags).size(); } public List<AnalyzedTokenReadings> getReplaceableTokens(String line) { List<AnalyzedSentence> answers; try { answers = langTool.analyzeText(line); } catch (IOException e1) { throw new RuntimeException(e1); } List<AnalyzedTokenReadings> tokens = new ArrayList<>(); for (AnalyzedSentence analyzedSentence : answers) { tokens.addAll(Arrays.asList(analyzedSentence.getTokens())); } tokens = filterTokens(tokens).stream().filter(e -> getReplaceableSize(getTags(e)) > 1) .collect(Collectors.toList()); return tokens; } public Optional<Replacer> createReplacer(AnalyzedTokenReadings token, Bag<String> replacePossibilities) { // Check if there is another possibility than to replace with itself if (replacePossibilities.isEmpty() || (replacePossibilities.getAmountOfUniqueElements() == 1 && replacePossibilities.get(0).toLowerCase().equals(token.getToken().toLowerCase()))) { return Optional.empty(); } Bag<String> bag = new ExclusionBag<String>(replacePossibilities, Arrays.asList(token.getToken())); String replacement = pickReplacement(token.getToken(), bag); Replacer replacer = new Replacer(token.getToken(), replacement, false, true); return Optional.of(replacer); } public String pickReplacement(String replacement, Bag<String> bag) { return bag.get(RANDOM.nextInt(bag.getAmountOfElements())); } public List<Replacer> calculatePossibleReplacements(String line) { Set<AnalyzedTokenReadings> tokens = new LinkedHashSet<>(getReplaceableTokens(line)); List<Replacer> replacers = new ArrayList<>(); for (AnalyzedTokenReadings token : tokens) { Bag<String> replacePossibilities = mappings.get(getTags(token)); createReplacer(token, replacePossibilities).ifPresent(replacer -> replacers.add(replacer)); // System.out.println((createReplacer(token, replacePossibilities).isPresent()) + " mapping of " + token // + "\n=>" + replacePossibilities); } return replacers; } /*-********************************************-*/ public String replaceSomething(String line, int amountOfReplacements) { List<Replacer> replacers = calculatePossibleReplacements(line); Set<Replacer> chosenReplacers = new LinkedHashSet<>( Picker.pickRandomUniqueIndices(Math.min(replacers.size(), amountOfReplacements), replacers.size()) .stream().map(idx -> replacers.get(idx)).collect(Collectors.toList())); return (new Replacers(chosenReplacers)).replace(line); } }
twinters/torfs-bot
src/main/java/be/thomaswinters/similarreplacer/SimilarWordReplacer.java
2,514
// Algemene persoonlijke voornaamwoorden
line_comment
nl
package be.thomaswinters.similarreplacer; import be.thomaswinters.LambdaExceptionUtil; import be.thomaswinters.markov.model.data.bags.Bag; import be.thomaswinters.markov.model.data.bags.WriteableBag; import be.thomaswinters.markov.model.data.bags.impl.ExclusionBag; import be.thomaswinters.markov.model.data.bags.impl.MutableBag; import be.thomaswinters.random.Picker; import be.thomaswinters.replacement.Replacer; import be.thomaswinters.replacement.Replacers; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.JLanguageTool; import org.languagetool.language.Dutch; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; public class SimilarWordReplacer { /*-********************************************-* * STATIC TOOLS *-********************************************-*/ private static final JLanguageTool langTool = new JLanguageTool(new Dutch()); protected static final Random RANDOM = new Random(); /*-********************************************-*/ /*-********************************************-* * INSTANCE VARIABLES *-********************************************-*/ private Map<Set<String>, WriteableBag<String>> mappings = new HashMap<>(); /*-********************************************-*/ /*-********************************************-* * TAGS & TOKEN FILTERING *-********************************************-*/ protected Set<String> getTags(AnalyzedTokenReadings token) { return token.getReadings().stream().filter(e -> !e.hasNoTag()).map(e -> e.getPOSTag()) .filter(e -> e != null && !e.equals("SENT_END") && !e.equals("PARA_END")).collect(Collectors.toSet()); } private static final Set<String> REPLACEMENT_TOKEN_BLACKLIST = new HashSet<>(Arrays.asList( // Lidwoorden "de", "het", "een", // Algemene onderwerpen "ik", "jij", "je", "u", "wij", "we", "jullie", "hij", "zij", "ze", // Algemene persoonlijke<SUF> "hen", "hem", "haar", "mijn", "uw", "jouw", "onze", "ons", // Algemene werkwoorden "ben", "bent", "is", "was", "waren", "geweest", "heb", "hebt", "heeft", "hebben", "gehad", "word", "wordt", "worden", "geworden", "werd", "werden", "laat", "laten", "liet", "lieten", "gelaten", "ga", "gaat", "gaan", "gegaan", "ging", "gingen", "moet", "moeten", "moest", "moesten", "gemoeten", "mag", "mogen", "mocht", "mochten", "gemogen", "zal", "zullen", "zult", "zou", "zouden", "kan", "kunnen", "gekunt", "gekunnen", "hoef", "hoeft", "hoeven", "hoefde", "hoefden", "gehoeven", // Veelgebruikte woorden "niet", "iets", "dan", "voort", "erna", "welke", "maar", "van", "voor", "met", "binnenkort", "in", "en", "teveel", "om", "alles", "elke", "al", "echt", "waar", "waarom", "hoe", "o.a.", "beetje", "enkel", "goed", "best", "werkende", "meer", "voor", "zit", "echt", "uit", "even", "wel")); private static final Set<String> REPLACEMENT_TAG_BLACKLIST = new HashSet<>( Arrays.asList("AVwaar", "AVwr", "DTh", "DTd", "DTe", "DTp", "PRte", "PRnaar", "PRvan", "PN2", "PRVoor", "PRmet", "PRop", "PRin", "PRom", "PRaan", "AVdr", "CJo")); private List<AnalyzedTokenReadings> filterTokens(List<AnalyzedTokenReadings> tokens) { return tokens.stream().filter(e -> e.getToken().trim().length() > 0).filter(e -> !e.getReadings().isEmpty()) .filter(token -> !getTags(token).isEmpty()) .filter(token -> getTags(token).stream().allMatch(tag -> !REPLACEMENT_TAG_BLACKLIST.contains(tag))) .filter(token -> !REPLACEMENT_TOKEN_BLACKLIST.contains(token.getToken().toLowerCase())) .collect(Collectors.toList()); } /*-********************************************-*/ /*-********************************************-* * PROCESSING KNOWLEDGE INPUT *-********************************************-*/ public void process(String line) throws IOException { List<AnalyzedSentence> answers = langTool.analyzeText(line); for (AnalyzedSentence analyzedSentence : answers) { List<AnalyzedTokenReadings> tokens = filterTokens(Arrays.asList(analyzedSentence.getTokens())); for (AnalyzedTokenReadings token : tokens) { if (token.getToken().trim().length() > 0) { Set<String> tags = getTags(token); // Add if valid if (tags != null && tags.size() > 0) { if (!mappings.containsKey(tags)) { mappings.put(tags, new MutableBag<String>()); } mappings.get(tags).add(token.getToken()); } } } } } public void process(List<String> lines) { lines.forEach(LambdaExceptionUtil.rethrowConsumer(this::process)); } /*-********************************************-*/ /*-********************************************-* * REPLACEABLE CALCULATION *-********************************************-*/ public int getReplaceableSize(Set<String> tags) { if (!mappings.containsKey(tags)) { return 0; } return mappings.get(tags).size(); } public List<AnalyzedTokenReadings> getReplaceableTokens(String line) { List<AnalyzedSentence> answers; try { answers = langTool.analyzeText(line); } catch (IOException e1) { throw new RuntimeException(e1); } List<AnalyzedTokenReadings> tokens = new ArrayList<>(); for (AnalyzedSentence analyzedSentence : answers) { tokens.addAll(Arrays.asList(analyzedSentence.getTokens())); } tokens = filterTokens(tokens).stream().filter(e -> getReplaceableSize(getTags(e)) > 1) .collect(Collectors.toList()); return tokens; } public Optional<Replacer> createReplacer(AnalyzedTokenReadings token, Bag<String> replacePossibilities) { // Check if there is another possibility than to replace with itself if (replacePossibilities.isEmpty() || (replacePossibilities.getAmountOfUniqueElements() == 1 && replacePossibilities.get(0).toLowerCase().equals(token.getToken().toLowerCase()))) { return Optional.empty(); } Bag<String> bag = new ExclusionBag<String>(replacePossibilities, Arrays.asList(token.getToken())); String replacement = pickReplacement(token.getToken(), bag); Replacer replacer = new Replacer(token.getToken(), replacement, false, true); return Optional.of(replacer); } public String pickReplacement(String replacement, Bag<String> bag) { return bag.get(RANDOM.nextInt(bag.getAmountOfElements())); } public List<Replacer> calculatePossibleReplacements(String line) { Set<AnalyzedTokenReadings> tokens = new LinkedHashSet<>(getReplaceableTokens(line)); List<Replacer> replacers = new ArrayList<>(); for (AnalyzedTokenReadings token : tokens) { Bag<String> replacePossibilities = mappings.get(getTags(token)); createReplacer(token, replacePossibilities).ifPresent(replacer -> replacers.add(replacer)); // System.out.println((createReplacer(token, replacePossibilities).isPresent()) + " mapping of " + token // + "\n=>" + replacePossibilities); } return replacers; } /*-********************************************-*/ public String replaceSomething(String line, int amountOfReplacements) { List<Replacer> replacers = calculatePossibleReplacements(line); Set<Replacer> chosenReplacers = new LinkedHashSet<>( Picker.pickRandomUniqueIndices(Math.min(replacers.size(), amountOfReplacements), replacers.size()) .stream().map(idx -> replacers.get(idx)).collect(Collectors.toList())); return (new Replacers(chosenReplacers)).replace(line); } }
True
False
1,498
588
14678_12
package nl.nijmegen.mule.agelimits;_x000D_ _x000D_ import java.time.LocalDate;_x000D_ import org.mule.api.MuleMessage;_x000D_ import org.mule.api.transformer.TransformerException;_x000D_ import org.mule.api.transport.PropertyScope;_x000D_ import org.mule.transformer.AbstractMessageTransformer;_x000D_ import org.apache.commons.logging.Log;_x000D_ import org.apache.commons.logging.LogFactory;_x000D_ _x000D_ public class calculateAgeLimits extends AbstractMessageTransformer{_x000D_ private static Log logger = LogFactory.getLog("nl.Nijmegen.brp.irma-api.calculateagelimits");_x000D_ _x000D_ _x000D_ @Override_x000D_ public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {_x000D_ _x000D_ //Zet geboortedatum_x000D_ //String bDay = "20000000";_x000D_ //String bDay = message.getInvocationProperty("sv_geboortedatum");_x000D_ String bDay = message.getProperty("sv_geboortedatum", PropertyScope.INVOCATION);_x000D_ //Code uit elkaar halen op jaar, maand en dag _x000D_ int lengteBDay = bDay.length();_x000D_ if (lengteBDay !=8) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");_x000D_ _x000D_ } _x000D_ //Code uit elkaar halen op jaar, maand en dag_x000D_ String bYear = (bDay.substring(0,4));_x000D_ String bMonth1= bDay.substring(bDay.length() - 4);_x000D_ String bMonth2 = (bMonth1.substring(0,2));_x000D_ String bDag = bDay.substring(bDay.length() - 2);_x000D_ _x000D_ _x000D_ //omzetten naar een int._x000D_ int bYearInt = Integer.parseInt(bYear);_x000D_ int bMonthInt = Integer.parseInt(bMonth2);_x000D_ int bDagInt = Integer.parseInt(bDag);_x000D_ logger.debug("jaar: " + bYearInt);_x000D_ logger.debug("maand: " + bMonthInt);_x000D_ logger.debug("dag: " + bDagInt);_x000D_ _x000D_ if (bYearInt ==0 || bYearInt <1850) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");_x000D_ }_x000D_ if (bMonthInt >12) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd."); _x000D_ }_x000D_ if (bDagInt >31) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd."); _x000D_ }_x000D_ _x000D_ //als maand null is dan 1 juli invullen_x000D_ if (bMonthInt == 0) {_x000D_ bMonthInt = 1;_x000D_ bMonthInt = 7;}_x000D_ //als dag null is, dan waarde op 1 zetten en vervolgens naar laatste dag van de maand_x000D_ if (bDagInt == 00) {_x000D_ _x000D_ LocalDate noDay = LocalDate.of(bYearInt,bMonthInt,1);_x000D_ LocalDate end = noDay.withDayOfMonth(noDay.lengthOfMonth());_x000D_ int dayOfMonth = end.getDayOfMonth();_x000D_ bDagInt = dayOfMonth;_x000D_ }_x000D_ if (bMonthInt == 2 & bDagInt == 29) {_x000D_ bDagInt=28;_x000D_ }_x000D_ _x000D_ String resultString = "";_x000D_ _x000D_ //geboortedag bepalen_x000D_ LocalDate currentTime = LocalDate.now();_x000D_ LocalDate birthday = LocalDate.of(bYearInt,bMonthInt,bDagInt);_x000D_ logger.debug("Huidige datum: " + currentTime);_x000D_ logger.debug("Geboortedatum: " + birthday);_x000D_ _x000D_ _x000D_ //array maken met alle jaren erin _x000D_ int[] jaar = new int[] {12,16,18,21,65};_x000D_ for (int i=0; i<jaar.length; i++)_x000D_ {_x000D_ //door array lopen_x000D_ //in de array current date bepalen_x000D_ //jaren van currentdate afhalen_x000D_ LocalDate date1 = LocalDate.now().minusYears(jaar[i]);_x000D_ _x000D_ String resultValue;_x000D_ String resultLabel;_x000D_ //vergelijken geboortedatum en currentdate_x000D_ if(date1.isBefore(birthday)) {_x000D_ resultValue = "No";_x000D_ }_x000D_ else {_x000D_ resultValue = "Yes";_x000D_ _x000D_ }_x000D_ //string met "isOver+jaar":'ja/nee'" vullen en concateren over loop heen_x000D_ resultLabel = "\"" +"over" + jaar[i]; _x000D_ resultString = resultString + resultLabel + "\"" +":"+ "\"" + resultValue + "\"" + ",";_x000D_ }_x000D_ //resultString teruggeven_x000D_ resultString = "{" + resultString.substring(0, resultString.length()-1) +"}";_x000D_ resultString = "{"+ "\""+"ageLimits"+"\""+": " + resultString +"}";_x000D_ logger.debug("resultString: " + resultString);_x000D_ return resultString;_x000D_ _x000D_ }_x000D_ _x000D_ };_x000D_ _x000D_ _x000D_ _x000D_
GemeenteNijmegen/irma-brp-opladen
src/api-source/calculateAgeLimits.java
1,510
//string met "isOver+jaar":'ja/nee'" vullen en concateren over loop heen_x000D_
line_comment
nl
package nl.nijmegen.mule.agelimits;_x000D_ _x000D_ import java.time.LocalDate;_x000D_ import org.mule.api.MuleMessage;_x000D_ import org.mule.api.transformer.TransformerException;_x000D_ import org.mule.api.transport.PropertyScope;_x000D_ import org.mule.transformer.AbstractMessageTransformer;_x000D_ import org.apache.commons.logging.Log;_x000D_ import org.apache.commons.logging.LogFactory;_x000D_ _x000D_ public class calculateAgeLimits extends AbstractMessageTransformer{_x000D_ private static Log logger = LogFactory.getLog("nl.Nijmegen.brp.irma-api.calculateagelimits");_x000D_ _x000D_ _x000D_ @Override_x000D_ public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {_x000D_ _x000D_ //Zet geboortedatum_x000D_ //String bDay = "20000000";_x000D_ //String bDay = message.getInvocationProperty("sv_geboortedatum");_x000D_ String bDay = message.getProperty("sv_geboortedatum", PropertyScope.INVOCATION);_x000D_ //Code uit elkaar halen op jaar, maand en dag _x000D_ int lengteBDay = bDay.length();_x000D_ if (lengteBDay !=8) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");_x000D_ _x000D_ } _x000D_ //Code uit elkaar halen op jaar, maand en dag_x000D_ String bYear = (bDay.substring(0,4));_x000D_ String bMonth1= bDay.substring(bDay.length() - 4);_x000D_ String bMonth2 = (bMonth1.substring(0,2));_x000D_ String bDag = bDay.substring(bDay.length() - 2);_x000D_ _x000D_ _x000D_ //omzetten naar een int._x000D_ int bYearInt = Integer.parseInt(bYear);_x000D_ int bMonthInt = Integer.parseInt(bMonth2);_x000D_ int bDagInt = Integer.parseInt(bDag);_x000D_ logger.debug("jaar: " + bYearInt);_x000D_ logger.debug("maand: " + bMonthInt);_x000D_ logger.debug("dag: " + bDagInt);_x000D_ _x000D_ if (bYearInt ==0 || bYearInt <1850) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");_x000D_ }_x000D_ if (bMonthInt >12) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd."); _x000D_ }_x000D_ if (bDagInt >31) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd."); _x000D_ }_x000D_ _x000D_ //als maand null is dan 1 juli invullen_x000D_ if (bMonthInt == 0) {_x000D_ bMonthInt = 1;_x000D_ bMonthInt = 7;}_x000D_ //als dag null is, dan waarde op 1 zetten en vervolgens naar laatste dag van de maand_x000D_ if (bDagInt == 00) {_x000D_ _x000D_ LocalDate noDay = LocalDate.of(bYearInt,bMonthInt,1);_x000D_ LocalDate end = noDay.withDayOfMonth(noDay.lengthOfMonth());_x000D_ int dayOfMonth = end.getDayOfMonth();_x000D_ bDagInt = dayOfMonth;_x000D_ }_x000D_ if (bMonthInt == 2 & bDagInt == 29) {_x000D_ bDagInt=28;_x000D_ }_x000D_ _x000D_ String resultString = "";_x000D_ _x000D_ //geboortedag bepalen_x000D_ LocalDate currentTime = LocalDate.now();_x000D_ LocalDate birthday = LocalDate.of(bYearInt,bMonthInt,bDagInt);_x000D_ logger.debug("Huidige datum: " + currentTime);_x000D_ logger.debug("Geboortedatum: " + birthday);_x000D_ _x000D_ _x000D_ //array maken met alle jaren erin _x000D_ int[] jaar = new int[] {12,16,18,21,65};_x000D_ for (int i=0; i<jaar.length; i++)_x000D_ {_x000D_ //door array lopen_x000D_ //in de array current date bepalen_x000D_ //jaren van currentdate afhalen_x000D_ LocalDate date1 = LocalDate.now().minusYears(jaar[i]);_x000D_ _x000D_ String resultValue;_x000D_ String resultLabel;_x000D_ //vergelijken geboortedatum en currentdate_x000D_ if(date1.isBefore(birthday)) {_x000D_ resultValue = "No";_x000D_ }_x000D_ else {_x000D_ resultValue = "Yes";_x000D_ _x000D_ }_x000D_ //string met<SUF> resultLabel = "\"" +"over" + jaar[i]; _x000D_ resultString = resultString + resultLabel + "\"" +":"+ "\"" + resultValue + "\"" + ",";_x000D_ }_x000D_ //resultString teruggeven_x000D_ resultString = "{" + resultString.substring(0, resultString.length()-1) +"}";_x000D_ resultString = "{"+ "\""+"ageLimits"+"\""+": " + resultString +"}";_x000D_ logger.debug("resultString: " + resultString);_x000D_ return resultString;_x000D_ _x000D_ }_x000D_ _x000D_ };_x000D_ _x000D_ _x000D_ _x000D_
True
False
1,506
790
66559_1
package com.example.jacco.tictactoe; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Switch; import android.widget.Toast; import java.util.Random; import java.util.concurrent.TimeUnit; public class MainActivity extends AppCompatActivity { // variables Game game; int row; int column; String[] names = {"t1","t2","t3","t4","t5","t6","t7","t8","t9"}; int[] buttons = {R.id.t1, R.id.t2, R.id.t3, R.id.t4, R.id.t5, R.id.t6, R.id.t7, R.id.t8, R.id.t9}; int[][] coordinates = {{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}}; boolean AIOn; int randTile; // saving state buttons @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { game =(Game) savedInstanceState.getSerializable("Game"); for (int i=0; i<names.length; i++){ // kan niet meer winnen na draaaien en X begint altijd na draaien Tile tile = game.drawTile(i/3, i%3); Button button = findViewById(buttons[i]); if (tile == Tile.CROSS) { button.setText("X"); } else if (tile == Tile.CIRCLE) { button.setText("O"); } } } else { game = new Game(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("Game",game); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); Game game =(Game) savedInstanceState.getSerializable("Game"); for (int i=0; i<names.length; i++){ // kan niet meer winnen na draaaien en X begint altijd na draaien Tile tile = game.drawTile(i/3, i%3); Button button = findViewById(buttons[i]); if (tile == Tile.CROSS) { button.setText("X"); } else if (tile == Tile.CIRCLE) { button.setText("O"); } } } public void tileClicked(View view) { // find clicked button int id = view.getId(); int length = buttons.length; for (int i=0; i<length; i++) { if (id == buttons[i]) { row = coordinates[i][0]; column = coordinates[i][1]; } } // find out what to draw Tile tile = game.draw(row, column); // print on board Button button = (Button) view; switch(tile) { case CROSS: button.setText("X"); break; case CIRCLE: button.setText("O"); break; case INVALID: // popup message from: // https://developer.android.com/guide/topics/ui/notifiers/toasts.html#Positioning Context context = getApplicationContext(); CharSequence text = "Invalid move!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); break; // check if AI has to play // if (AIOn && game.process() != GameState.PLAYER_ONE) { // // check if there's a good play // // if (game.prevent()<9) { // randTile = game.prevent(); // } else { // // find a random blank tile and find out what to draw // Tile tileTest; // do { // Random rand = new Random(); // randTile = rand.nextInt(9); // tileTest = game.test(coordinates[randTile][0], coordinates[randTile][1]); // } // while (tileTest == Tile.INVALID || row == coordinates[randTile][0] || column == coordinates[randTile][1]); // } // // game.draw(coordinates[randTile][0],coordinates[randTile][1]); // // // print on board // // Button button2 = findViewById(buttons[randTile]); // button2.setText("O"); // } } // find out who won and print message if (game.process() == GameState.DRAW) { Context context = getApplicationContext(); CharSequence text = "It's a draw! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else if (game.process() == GameState.PLAYER_ONE) { Context context = getApplicationContext(); CharSequence text = "Player one wins! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else if (game.process() == GameState.PLAYER_TWO) { Context context = getApplicationContext(); CharSequence text = "Player two wins! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } public void resetClicked(View view) { // clear all buttons and start new game for (int i : buttons) { Button button = findViewById(i); button.setText(""); } game = new Game(); } public void switchCheck(View view) { Switch aSwitch = findViewById(R.id.switch1); if (aSwitch.isChecked()) { AIOn = true; // clear all buttons and start new game for (int i : buttons) { Button button = findViewById(i); button.setText(""); } game = new Game(); } else { AIOn = false; } } }
JaccovanWijk/TicTacToe
app/src/main/java/com/example/jacco/tictactoe/MainActivity.java
1,795
// kan niet meer winnen na draaaien en X begint altijd na draaien
line_comment
nl
package com.example.jacco.tictactoe; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Switch; import android.widget.Toast; import java.util.Random; import java.util.concurrent.TimeUnit; public class MainActivity extends AppCompatActivity { // variables Game game; int row; int column; String[] names = {"t1","t2","t3","t4","t5","t6","t7","t8","t9"}; int[] buttons = {R.id.t1, R.id.t2, R.id.t3, R.id.t4, R.id.t5, R.id.t6, R.id.t7, R.id.t8, R.id.t9}; int[][] coordinates = {{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}}; boolean AIOn; int randTile; // saving state buttons @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { game =(Game) savedInstanceState.getSerializable("Game"); for (int i=0; i<names.length; i++){ // kan niet<SUF> Tile tile = game.drawTile(i/3, i%3); Button button = findViewById(buttons[i]); if (tile == Tile.CROSS) { button.setText("X"); } else if (tile == Tile.CIRCLE) { button.setText("O"); } } } else { game = new Game(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("Game",game); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); Game game =(Game) savedInstanceState.getSerializable("Game"); for (int i=0; i<names.length; i++){ // kan niet meer winnen na draaaien en X begint altijd na draaien Tile tile = game.drawTile(i/3, i%3); Button button = findViewById(buttons[i]); if (tile == Tile.CROSS) { button.setText("X"); } else if (tile == Tile.CIRCLE) { button.setText("O"); } } } public void tileClicked(View view) { // find clicked button int id = view.getId(); int length = buttons.length; for (int i=0; i<length; i++) { if (id == buttons[i]) { row = coordinates[i][0]; column = coordinates[i][1]; } } // find out what to draw Tile tile = game.draw(row, column); // print on board Button button = (Button) view; switch(tile) { case CROSS: button.setText("X"); break; case CIRCLE: button.setText("O"); break; case INVALID: // popup message from: // https://developer.android.com/guide/topics/ui/notifiers/toasts.html#Positioning Context context = getApplicationContext(); CharSequence text = "Invalid move!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); break; // check if AI has to play // if (AIOn && game.process() != GameState.PLAYER_ONE) { // // check if there's a good play // // if (game.prevent()<9) { // randTile = game.prevent(); // } else { // // find a random blank tile and find out what to draw // Tile tileTest; // do { // Random rand = new Random(); // randTile = rand.nextInt(9); // tileTest = game.test(coordinates[randTile][0], coordinates[randTile][1]); // } // while (tileTest == Tile.INVALID || row == coordinates[randTile][0] || column == coordinates[randTile][1]); // } // // game.draw(coordinates[randTile][0],coordinates[randTile][1]); // // // print on board // // Button button2 = findViewById(buttons[randTile]); // button2.setText("O"); // } } // find out who won and print message if (game.process() == GameState.DRAW) { Context context = getApplicationContext(); CharSequence text = "It's a draw! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else if (game.process() == GameState.PLAYER_ONE) { Context context = getApplicationContext(); CharSequence text = "Player one wins! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else if (game.process() == GameState.PLAYER_TWO) { Context context = getApplicationContext(); CharSequence text = "Player two wins! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } public void resetClicked(View view) { // clear all buttons and start new game for (int i : buttons) { Button button = findViewById(i); button.setText(""); } game = new Game(); } public void switchCheck(View view) { Switch aSwitch = findViewById(R.id.switch1); if (aSwitch.isChecked()) { AIOn = true; // clear all buttons and start new game for (int i : buttons) { Button button = findViewById(i); button.setText(""); } game = new Game(); } else { AIOn = false; } } }
True
False
1,507
1,466
31979_1
package Interfaces; public interface Event { /** * Deze functie voert het event uit. * @return Object - Het resultaat van het event. */ public Object Exucute(); /** * Dit event geeft het resultaat van het event terug. * @return Object - Het resultaat van het event. */ public Object GetResult(); }
RikkertTheDeveloper/Java-Structure-Template
Interfaces/Event.java
96
/** * Dit event geeft het resultaat van het event terug. * @return Object - Het resultaat van het event. */
block_comment
nl
package Interfaces; public interface Event { /** * Deze functie voert het event uit. * @return Object - Het resultaat van het event. */ public Object Exucute(); /** * Dit event geeft<SUF>*/ public Object GetResult(); }
True
False
1,520
4,732
30175_34
/**_x000D_ * KAR Geo Tool - applicatie voor het registreren van KAR meldpunten_x000D_ *_x000D_ * Copyright (C) 2009-2013 B3Partners B.V._x000D_ *_x000D_ * This program is free software: you can redistribute it and/or modify_x000D_ * it under the terms of the GNU Affero General Public License as_x000D_ * published by the Free Software Foundation, either version 3 of the_x000D_ * License, or (at your option) any later version._x000D_ *_x000D_ * This program is distributed in the hope that it will be useful,_x000D_ * but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_ * GNU Affero General Public License for more details._x000D_ *_x000D_ * You should have received a copy of the GNU Affero General Public License_x000D_ * along with this program. If not, see <http://www.gnu.org/licenses/>._x000D_ */_x000D_ _x000D_ package nl.b3p.kar.hibernate;_x000D_ _x000D_ import javax.persistence.*;_x000D_ import java.io.UnsupportedEncodingException;_x000D_ import java.security.NoSuchAlgorithmException;_x000D_ import java.security.Principal;_x000D_ import java.util.ArrayList;_x000D_ import java.util.HashSet;_x000D_ import java.util.Iterator;_x000D_ import java.util.List;_x000D_ import java.util.Map;_x000D_ import java.util.Map.Entry;_x000D_ import java.util.Set;_x000D_ import java.util.SortedMap;_x000D_ import java.util.TreeMap;_x000D_ import javax.persistence.EntityManager;_x000D_ import javax.servlet.http.HttpServletRequest;_x000D_ import nl.b3p.kar.SecurityRealm;_x000D_ import org.hibernate.annotations.Sort;_x000D_ import org.hibernate.annotations.SortType;_x000D_ import org.json.JSONException;_x000D_ import org.json.JSONObject;_x000D_ import org.stripesstuff.stripersist.Stripersist;_x000D_ _x000D_ /**_x000D_ * Klasse voor definitie van een gebruiker_x000D_ *_x000D_ * @author Chris_x000D_ */_x000D_ @Entity_x000D_ public class Gebruiker implements Principal {_x000D_ @Id_x000D_ @GeneratedValue(strategy= GenerationType.IDENTITY)_x000D_ private Integer id;_x000D_ _x000D_ @Column(unique=true, nullable=false)_x000D_ private String username;_x000D_ private String passwordsalt;_x000D_ private String passwordhash;_x000D_ private String fullname;_x000D_ private String email;_x000D_ private String phone;_x000D_ private String position;_x000D_ _x000D_ /**_x000D_ * JSON string met profielinstellingen._x000D_ */_x000D_ @Column(columnDefinition="text")_x000D_ private String profile;_x000D_ _x000D_ @ManyToMany_x000D_ @JoinTable(name = "gebruiker_roles", joinColumns=@JoinColumn(name="gebruiker"), inverseJoinColumns=@JoinColumn(name="role"))_x000D_ private Set<Role> roles = new HashSet();_x000D_ _x000D_ @OneToMany(mappedBy="gebruiker")_x000D_ @MapKeyJoinColumn(name="data_owner")_x000D_ @Sort(type=SortType.NATURAL)_x000D_ private SortedMap<DataOwner, GebruikerDataOwnerRights> dataOwnerRights = new TreeMap<DataOwner, GebruikerDataOwnerRights>();_x000D_ _x000D_ @OneToMany(mappedBy="gebruiker")_x000D_ private List<GebruikerVRIRights> vriRights = new ArrayList();_x000D_ _x000D_ /**_x000D_ * Verandert het wachtwoord_x000D_ *_x000D_ * @param request nodig voor bepaling random salt_x000D_ * @param pw het wachtwoord_x000D_ * @throws NoSuchAlgorithmException The error_x000D_ * @throws UnsupportedEncodingException The error_x000D_ */_x000D_ public void changePassword(HttpServletRequest request, String pw) throws NoSuchAlgorithmException, UnsupportedEncodingException {_x000D_ String salt = SecurityRealm.generateHexSalt(request);_x000D_ String hash = SecurityRealm.getHexSha1(salt, pw);_x000D_ setPasswordsalt(salt);_x000D_ setPasswordhash(hash);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zoekt de huidige gebruiker_x000D_ *_x000D_ * @param request waarin gebruiker is te vinden_x000D_ * @return getter de gebruiker_x000D_ * @throws Exception The error_x000D_ */_x000D_ public static Gebruiker getNonTransientPrincipal(HttpServletRequest request) throws Exception {_x000D_ Gebruiker g = (Gebruiker)request.getUserPrincipal();_x000D_ if(g == null) {_x000D_ return null;_x000D_ }_x000D_ return Stripersist.getEntityManager().find(Gebruiker.class, g.getId());_x000D_ }_x000D_ _x000D_ /**_x000D_ * Haalt id van gebruiker op_x000D_ *_x000D_ * @return getter id_x000D_ */_x000D_ public Integer getId() {_x000D_ return id;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param id setter_x000D_ */_x000D_ public void setId(Integer id) {_x000D_ this.id = id;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Haalt gebruikersnaam op_x000D_ *_x000D_ * @return getter username_x000D_ */_x000D_ public String getUsername() {_x000D_ return username;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param username setter_x000D_ */_x000D_ public void setUsername(String username) {_x000D_ this.username = username;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter passwordsalt_x000D_ */_x000D_ public String getPasswordsalt() {_x000D_ return passwordsalt;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param passwordSalt setter_x000D_ */_x000D_ public void setPasswordsalt(String passwordSalt) {_x000D_ this.passwordsalt = passwordSalt;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter passwordhash_x000D_ */_x000D_ public String getPasswordhash() {_x000D_ return passwordhash;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param passwordhash setter_x000D_ */_x000D_ public void setPasswordhash(String passwordhash) {_x000D_ this.passwordhash = passwordhash;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Principal implementatie_x000D_ */_x000D_ public String getName() {_x000D_ return getUsername();_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter fullname_x000D_ */_x000D_ public String getFullname() {_x000D_ return fullname;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param fullname setter_x000D_ */_x000D_ public void setFullname(String fullname) {_x000D_ this.fullname = fullname;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter email_x000D_ */_x000D_ public String getEmail() {_x000D_ return email;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param email setter_x000D_ */_x000D_ public void setEmail(String email) {_x000D_ this.email = email;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter phone_x000D_ */_x000D_ public String getPhone() {_x000D_ return phone;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param phone setter_x000D_ */_x000D_ public void setPhone(String phone) {_x000D_ this.phone = phone;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter position_x000D_ */_x000D_ public String getPosition() {_x000D_ return position;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param position setter_x000D_ */_x000D_ public void setPosition(String position) {_x000D_ this.position = position;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter roles_x000D_ */_x000D_ public Set<Role> getRoles() {_x000D_ return roles;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param roles setter_x000D_ */_x000D_ public void setRoles(Set<Role> roles) {_x000D_ this.roles = roles;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter profile_x000D_ */_x000D_ public String getProfile() {_x000D_ return profile;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param profile setter_x000D_ */_x000D_ public void setProfile(String profile) {_x000D_ this.profile = profile;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter is gebruiker beheerder?_x000D_ */_x000D_ public boolean isBeheerder() {_x000D_ return isInRole(Role.BEHEERDER);_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter_x000D_ */_x000D_ public boolean isVervoerder(){_x000D_ return isInRole(Role.VERVOERDER);_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param roleName roleName_x000D_ * @return getter heeft gebruiker de gevraagde rol?_x000D_ */_x000D_ public boolean isInRole(String roleName) {_x000D_ for(Iterator it = getRoles().iterator(); it.hasNext();) {_x000D_ Role r = (Role)it.next();_x000D_ if(r.getRole().equals(roleName)) {_x000D_ return true;_x000D_ }_x000D_ }_x000D_ return false;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter dataOwnerRights_x000D_ */_x000D_ public Map<DataOwner, GebruikerDataOwnerRights> getDataOwnerRights() {_x000D_ return dataOwnerRights;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param dataOwnerRights setter_x000D_ */_x000D_ public void setDataOwnerRights(SortedMap<DataOwner, GebruikerDataOwnerRights> dataOwnerRights) {_x000D_ this.dataOwnerRights = dataOwnerRights;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter_x000D_ */_x000D_ public List<GebruikerVRIRights> getVriRights() {_x000D_ return vriRights;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param vriRights setter_x000D_ */_x000D_ public void setVriRights(List<GebruikerVRIRights> vriRights) {_x000D_ this.vriRights = vriRights;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Lijst van van data owners die gebruiker met gebruiker role mag lezen (bij_x000D_ * beheerder/vervoerder worden NIET alle data owners teruggegeven). Een_x000D_ * dataOwnerRights record betekent altijd lezen of schrijven, nooit kan_x000D_ * editable en readable beide false zijn._x000D_ * @return getter _x000D_ */_x000D_ public Set<DataOwner> getReadableDataOwners() {_x000D_ return dataOwnerRights.keySet();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Lijst van van data owners die gebruiker met gebruiker role mag bewerken (bij_x000D_ * beheerder role worden NIET alle data owners teruggegeven)._x000D_ * @return getter _x000D_ */_x000D_ public Set<DataOwner> getEditableDataOwners() {_x000D_ HashSet<DataOwner> dataOwners = new HashSet<DataOwner>();_x000D_ for (Entry<DataOwner, GebruikerDataOwnerRights> entry : dataOwnerRights.entrySet()) {_x000D_ if(entry.getValue().isEditable()) {_x000D_ dataOwners.add(entry.getValue().getDataOwner());_x000D_ }_x000D_ }_x000D_ return dataOwners;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Gebruiker kan RoadsideEquipment editen als:_x000D_ * - Gebruiker beheerder is, of_x000D_ * - Gebruiker DataOwner kan editen, of_x000D_ * - Gebruiker VRI kan editen._x000D_ *_x000D_ * Vervoerders kunnen nooit editen, ook al staan in de database DataOwner/VRI_x000D_ * rechten (zou GUI niet mogelijk moeten maken)._x000D_ * @param rseq rseq_x000D_ * @return getter _x000D_ */_x000D_ public boolean canEdit(RoadsideEquipment rseq) {_x000D_ if(isBeheerder()) {_x000D_ return true;_x000D_ }_x000D_ _x000D_ if(isVervoerder()) {_x000D_ return false;_x000D_ }_x000D_ _x000D_ DataOwner d = rseq.getDataOwner();_x000D_ if(d != null) {_x000D_ GebruikerDataOwnerRights r = dataOwnerRights.get(d);_x000D_ if(r != null && r.isEditable()) {_x000D_ return true;_x000D_ }_x000D_ }_x000D_ _x000D_ Long rseqId = rseq.getId();_x000D_ if(rseqId != null) {_x000D_ for(GebruikerVRIRights gebruikerVRIRights : vriRights) {_x000D_ if(gebruikerVRIRights.isEditable()) {_x000D_ if(gebruikerVRIRights.getRoadsideEquipment().getId().equals(rseqId)) {_x000D_ return true;_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ return false;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Gebruiker kan RoadsideEquipment lezen als:_x000D_ * - Gebruiker is beheerder, of_x000D_ * - Gebruiker is vervoerder, of_x000D_ * - Gebruiker heeft GebruikerDataOwnerRights record voor DAO van RSEQ, of_x000D_ * - Gebruiker heeft GebruikerVRIRights record voor RSEQ._x000D_ *_x000D_ * Een DataOwner recht of VRI recht bij een gebruiker betekent altijd mimimaal_x000D_ * leesrecht. Readable=false en editable=false bij rights records zouden niet_x000D_ * in db moeten kunnen staan. Hier wordt gebruik van gemaakt bij zoekacties._x000D_ * @param rseq rseq_x000D_ * @return getter _x000D_ */_x000D_ public boolean canRead(RoadsideEquipment rseq) {_x000D_ if(isBeheerder() || isVervoerder()) {_x000D_ return true;_x000D_ }_x000D_ _x000D_ DataOwner d = rseq.getDataOwner();_x000D_ if(d != null) {_x000D_ GebruikerDataOwnerRights r = dataOwnerRights.get(d);_x000D_ if(r != null) {_x000D_ // Geen test op isEditable() of isReadable() nodig, een van beide_x000D_ // is voldoende maar zouden nooit met allebei false in database_x000D_ // moeten staan_x000D_ return true;_x000D_ }_x000D_ }_x000D_ _x000D_ Long rseqId = rseq.getId();_x000D_ if(rseqId != null) {_x000D_ for(GebruikerVRIRights gebruikerVRIRights: vriRights) {_x000D_ // Geen test op isEditable() of isReadable() nodig, een van beide_x000D_ // is voldoende maar zouden nooit met allebei false in database_x000D_ // moeten staan_x000D_ if(gebruikerVRIRights.getRoadsideEquipment().getId().equals(rseqId)) {_x000D_ return true;_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ return false;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zet de rechten mbt de DataOwner_x000D_ * @param dao het dataowner object_x000D_ * @param editable mag geedit worden_x000D_ * @param readable mag gelezen worden_x000D_ * @throws Exception The error_x000D_ */_x000D_ public void setDataOwnerRight(DataOwner dao, Boolean editable, Boolean readable) throws Exception {_x000D_ EntityManager em = Stripersist.getEntityManager();_x000D_ GebruikerDataOwnerRights dor = getDataOwnerRights().get(dao);_x000D_ if(dor == null) {_x000D_ dor = new GebruikerDataOwnerRights();_x000D_ dor.setDataOwner(dao);_x000D_ dor.setGebruiker(this);_x000D_ em.persist(dor);_x000D_ getDataOwnerRights().put(dao, dor);_x000D_ }_x000D_ if(editable != null) {_x000D_ dor.setEditable(editable);_x000D_ }_x000D_ if(readable != null) {_x000D_ dor.setReadable(readable);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter_x000D_ * @throws JSONException The error_x000D_ */_x000D_ public JSONObject toJSON() throws JSONException{_x000D_ JSONObject obj = new JSONObject();_x000D_ obj.put("id", id);_x000D_ obj.put("username", username);_x000D_ obj.put("fullname", fullname);_x000D_ obj.put("mail", email);_x000D_ obj.put("phone", phone);_x000D_ return obj;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public String toString(){_x000D_ return username + " (" +fullname + ")";_x000D_ }_x000D_ }_x000D_
wscherphof/kargeotool
src/main/java/nl/b3p/kar/hibernate/Gebruiker.java
4,161
/**_x000D_ * Lijst van van data owners die gebruiker met gebruiker role mag bewerken (bij_x000D_ * beheerder role worden NIET alle data owners teruggegeven)._x000D_ * @return getter _x000D_ */
block_comment
nl
/**_x000D_ * KAR Geo Tool - applicatie voor het registreren van KAR meldpunten_x000D_ *_x000D_ * Copyright (C) 2009-2013 B3Partners B.V._x000D_ *_x000D_ * This program is free software: you can redistribute it and/or modify_x000D_ * it under the terms of the GNU Affero General Public License as_x000D_ * published by the Free Software Foundation, either version 3 of the_x000D_ * License, or (at your option) any later version._x000D_ *_x000D_ * This program is distributed in the hope that it will be useful,_x000D_ * but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_ * GNU Affero General Public License for more details._x000D_ *_x000D_ * You should have received a copy of the GNU Affero General Public License_x000D_ * along with this program. If not, see <http://www.gnu.org/licenses/>._x000D_ */_x000D_ _x000D_ package nl.b3p.kar.hibernate;_x000D_ _x000D_ import javax.persistence.*;_x000D_ import java.io.UnsupportedEncodingException;_x000D_ import java.security.NoSuchAlgorithmException;_x000D_ import java.security.Principal;_x000D_ import java.util.ArrayList;_x000D_ import java.util.HashSet;_x000D_ import java.util.Iterator;_x000D_ import java.util.List;_x000D_ import java.util.Map;_x000D_ import java.util.Map.Entry;_x000D_ import java.util.Set;_x000D_ import java.util.SortedMap;_x000D_ import java.util.TreeMap;_x000D_ import javax.persistence.EntityManager;_x000D_ import javax.servlet.http.HttpServletRequest;_x000D_ import nl.b3p.kar.SecurityRealm;_x000D_ import org.hibernate.annotations.Sort;_x000D_ import org.hibernate.annotations.SortType;_x000D_ import org.json.JSONException;_x000D_ import org.json.JSONObject;_x000D_ import org.stripesstuff.stripersist.Stripersist;_x000D_ _x000D_ /**_x000D_ * Klasse voor definitie van een gebruiker_x000D_ *_x000D_ * @author Chris_x000D_ */_x000D_ @Entity_x000D_ public class Gebruiker implements Principal {_x000D_ @Id_x000D_ @GeneratedValue(strategy= GenerationType.IDENTITY)_x000D_ private Integer id;_x000D_ _x000D_ @Column(unique=true, nullable=false)_x000D_ private String username;_x000D_ private String passwordsalt;_x000D_ private String passwordhash;_x000D_ private String fullname;_x000D_ private String email;_x000D_ private String phone;_x000D_ private String position;_x000D_ _x000D_ /**_x000D_ * JSON string met profielinstellingen._x000D_ */_x000D_ @Column(columnDefinition="text")_x000D_ private String profile;_x000D_ _x000D_ @ManyToMany_x000D_ @JoinTable(name = "gebruiker_roles", joinColumns=@JoinColumn(name="gebruiker"), inverseJoinColumns=@JoinColumn(name="role"))_x000D_ private Set<Role> roles = new HashSet();_x000D_ _x000D_ @OneToMany(mappedBy="gebruiker")_x000D_ @MapKeyJoinColumn(name="data_owner")_x000D_ @Sort(type=SortType.NATURAL)_x000D_ private SortedMap<DataOwner, GebruikerDataOwnerRights> dataOwnerRights = new TreeMap<DataOwner, GebruikerDataOwnerRights>();_x000D_ _x000D_ @OneToMany(mappedBy="gebruiker")_x000D_ private List<GebruikerVRIRights> vriRights = new ArrayList();_x000D_ _x000D_ /**_x000D_ * Verandert het wachtwoord_x000D_ *_x000D_ * @param request nodig voor bepaling random salt_x000D_ * @param pw het wachtwoord_x000D_ * @throws NoSuchAlgorithmException The error_x000D_ * @throws UnsupportedEncodingException The error_x000D_ */_x000D_ public void changePassword(HttpServletRequest request, String pw) throws NoSuchAlgorithmException, UnsupportedEncodingException {_x000D_ String salt = SecurityRealm.generateHexSalt(request);_x000D_ String hash = SecurityRealm.getHexSha1(salt, pw);_x000D_ setPasswordsalt(salt);_x000D_ setPasswordhash(hash);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zoekt de huidige gebruiker_x000D_ *_x000D_ * @param request waarin gebruiker is te vinden_x000D_ * @return getter de gebruiker_x000D_ * @throws Exception The error_x000D_ */_x000D_ public static Gebruiker getNonTransientPrincipal(HttpServletRequest request) throws Exception {_x000D_ Gebruiker g = (Gebruiker)request.getUserPrincipal();_x000D_ if(g == null) {_x000D_ return null;_x000D_ }_x000D_ return Stripersist.getEntityManager().find(Gebruiker.class, g.getId());_x000D_ }_x000D_ _x000D_ /**_x000D_ * Haalt id van gebruiker op_x000D_ *_x000D_ * @return getter id_x000D_ */_x000D_ public Integer getId() {_x000D_ return id;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param id setter_x000D_ */_x000D_ public void setId(Integer id) {_x000D_ this.id = id;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Haalt gebruikersnaam op_x000D_ *_x000D_ * @return getter username_x000D_ */_x000D_ public String getUsername() {_x000D_ return username;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param username setter_x000D_ */_x000D_ public void setUsername(String username) {_x000D_ this.username = username;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter passwordsalt_x000D_ */_x000D_ public String getPasswordsalt() {_x000D_ return passwordsalt;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param passwordSalt setter_x000D_ */_x000D_ public void setPasswordsalt(String passwordSalt) {_x000D_ this.passwordsalt = passwordSalt;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter passwordhash_x000D_ */_x000D_ public String getPasswordhash() {_x000D_ return passwordhash;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param passwordhash setter_x000D_ */_x000D_ public void setPasswordhash(String passwordhash) {_x000D_ this.passwordhash = passwordhash;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Principal implementatie_x000D_ */_x000D_ public String getName() {_x000D_ return getUsername();_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter fullname_x000D_ */_x000D_ public String getFullname() {_x000D_ return fullname;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param fullname setter_x000D_ */_x000D_ public void setFullname(String fullname) {_x000D_ this.fullname = fullname;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter email_x000D_ */_x000D_ public String getEmail() {_x000D_ return email;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param email setter_x000D_ */_x000D_ public void setEmail(String email) {_x000D_ this.email = email;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter phone_x000D_ */_x000D_ public String getPhone() {_x000D_ return phone;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param phone setter_x000D_ */_x000D_ public void setPhone(String phone) {_x000D_ this.phone = phone;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter position_x000D_ */_x000D_ public String getPosition() {_x000D_ return position;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param position setter_x000D_ */_x000D_ public void setPosition(String position) {_x000D_ this.position = position;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter roles_x000D_ */_x000D_ public Set<Role> getRoles() {_x000D_ return roles;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param roles setter_x000D_ */_x000D_ public void setRoles(Set<Role> roles) {_x000D_ this.roles = roles;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter profile_x000D_ */_x000D_ public String getProfile() {_x000D_ return profile;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param profile setter_x000D_ */_x000D_ public void setProfile(String profile) {_x000D_ this.profile = profile;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter is gebruiker beheerder?_x000D_ */_x000D_ public boolean isBeheerder() {_x000D_ return isInRole(Role.BEHEERDER);_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter_x000D_ */_x000D_ public boolean isVervoerder(){_x000D_ return isInRole(Role.VERVOERDER);_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param roleName roleName_x000D_ * @return getter heeft gebruiker de gevraagde rol?_x000D_ */_x000D_ public boolean isInRole(String roleName) {_x000D_ for(Iterator it = getRoles().iterator(); it.hasNext();) {_x000D_ Role r = (Role)it.next();_x000D_ if(r.getRole().equals(roleName)) {_x000D_ return true;_x000D_ }_x000D_ }_x000D_ return false;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter dataOwnerRights_x000D_ */_x000D_ public Map<DataOwner, GebruikerDataOwnerRights> getDataOwnerRights() {_x000D_ return dataOwnerRights;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param dataOwnerRights setter_x000D_ */_x000D_ public void setDataOwnerRights(SortedMap<DataOwner, GebruikerDataOwnerRights> dataOwnerRights) {_x000D_ this.dataOwnerRights = dataOwnerRights;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter_x000D_ */_x000D_ public List<GebruikerVRIRights> getVriRights() {_x000D_ return vriRights;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param vriRights setter_x000D_ */_x000D_ public void setVriRights(List<GebruikerVRIRights> vriRights) {_x000D_ this.vriRights = vriRights;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Lijst van van data owners die gebruiker met gebruiker role mag lezen (bij_x000D_ * beheerder/vervoerder worden NIET alle data owners teruggegeven). Een_x000D_ * dataOwnerRights record betekent altijd lezen of schrijven, nooit kan_x000D_ * editable en readable beide false zijn._x000D_ * @return getter _x000D_ */_x000D_ public Set<DataOwner> getReadableDataOwners() {_x000D_ return dataOwnerRights.keySet();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Lijst van van<SUF>*/_x000D_ public Set<DataOwner> getEditableDataOwners() {_x000D_ HashSet<DataOwner> dataOwners = new HashSet<DataOwner>();_x000D_ for (Entry<DataOwner, GebruikerDataOwnerRights> entry : dataOwnerRights.entrySet()) {_x000D_ if(entry.getValue().isEditable()) {_x000D_ dataOwners.add(entry.getValue().getDataOwner());_x000D_ }_x000D_ }_x000D_ return dataOwners;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Gebruiker kan RoadsideEquipment editen als:_x000D_ * - Gebruiker beheerder is, of_x000D_ * - Gebruiker DataOwner kan editen, of_x000D_ * - Gebruiker VRI kan editen._x000D_ *_x000D_ * Vervoerders kunnen nooit editen, ook al staan in de database DataOwner/VRI_x000D_ * rechten (zou GUI niet mogelijk moeten maken)._x000D_ * @param rseq rseq_x000D_ * @return getter _x000D_ */_x000D_ public boolean canEdit(RoadsideEquipment rseq) {_x000D_ if(isBeheerder()) {_x000D_ return true;_x000D_ }_x000D_ _x000D_ if(isVervoerder()) {_x000D_ return false;_x000D_ }_x000D_ _x000D_ DataOwner d = rseq.getDataOwner();_x000D_ if(d != null) {_x000D_ GebruikerDataOwnerRights r = dataOwnerRights.get(d);_x000D_ if(r != null && r.isEditable()) {_x000D_ return true;_x000D_ }_x000D_ }_x000D_ _x000D_ Long rseqId = rseq.getId();_x000D_ if(rseqId != null) {_x000D_ for(GebruikerVRIRights gebruikerVRIRights : vriRights) {_x000D_ if(gebruikerVRIRights.isEditable()) {_x000D_ if(gebruikerVRIRights.getRoadsideEquipment().getId().equals(rseqId)) {_x000D_ return true;_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ return false;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Gebruiker kan RoadsideEquipment lezen als:_x000D_ * - Gebruiker is beheerder, of_x000D_ * - Gebruiker is vervoerder, of_x000D_ * - Gebruiker heeft GebruikerDataOwnerRights record voor DAO van RSEQ, of_x000D_ * - Gebruiker heeft GebruikerVRIRights record voor RSEQ._x000D_ *_x000D_ * Een DataOwner recht of VRI recht bij een gebruiker betekent altijd mimimaal_x000D_ * leesrecht. Readable=false en editable=false bij rights records zouden niet_x000D_ * in db moeten kunnen staan. Hier wordt gebruik van gemaakt bij zoekacties._x000D_ * @param rseq rseq_x000D_ * @return getter _x000D_ */_x000D_ public boolean canRead(RoadsideEquipment rseq) {_x000D_ if(isBeheerder() || isVervoerder()) {_x000D_ return true;_x000D_ }_x000D_ _x000D_ DataOwner d = rseq.getDataOwner();_x000D_ if(d != null) {_x000D_ GebruikerDataOwnerRights r = dataOwnerRights.get(d);_x000D_ if(r != null) {_x000D_ // Geen test op isEditable() of isReadable() nodig, een van beide_x000D_ // is voldoende maar zouden nooit met allebei false in database_x000D_ // moeten staan_x000D_ return true;_x000D_ }_x000D_ }_x000D_ _x000D_ Long rseqId = rseq.getId();_x000D_ if(rseqId != null) {_x000D_ for(GebruikerVRIRights gebruikerVRIRights: vriRights) {_x000D_ // Geen test op isEditable() of isReadable() nodig, een van beide_x000D_ // is voldoende maar zouden nooit met allebei false in database_x000D_ // moeten staan_x000D_ if(gebruikerVRIRights.getRoadsideEquipment().getId().equals(rseqId)) {_x000D_ return true;_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ return false;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zet de rechten mbt de DataOwner_x000D_ * @param dao het dataowner object_x000D_ * @param editable mag geedit worden_x000D_ * @param readable mag gelezen worden_x000D_ * @throws Exception The error_x000D_ */_x000D_ public void setDataOwnerRight(DataOwner dao, Boolean editable, Boolean readable) throws Exception {_x000D_ EntityManager em = Stripersist.getEntityManager();_x000D_ GebruikerDataOwnerRights dor = getDataOwnerRights().get(dao);_x000D_ if(dor == null) {_x000D_ dor = new GebruikerDataOwnerRights();_x000D_ dor.setDataOwner(dao);_x000D_ dor.setGebruiker(this);_x000D_ em.persist(dor);_x000D_ getDataOwnerRights().put(dao, dor);_x000D_ }_x000D_ if(editable != null) {_x000D_ dor.setEditable(editable);_x000D_ }_x000D_ if(readable != null) {_x000D_ dor.setReadable(readable);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return getter_x000D_ * @throws JSONException The error_x000D_ */_x000D_ public JSONObject toJSON() throws JSONException{_x000D_ JSONObject obj = new JSONObject();_x000D_ obj.put("id", id);_x000D_ obj.put("username", username);_x000D_ obj.put("fullname", fullname);_x000D_ obj.put("mail", email);_x000D_ obj.put("phone", phone);_x000D_ return obj;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public String toString(){_x000D_ return username + " (" +fullname + ")";_x000D_ }_x000D_ }_x000D_
True
False
1,521
2,606
1602_2
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
dylandreimerink/magazijnrobot
src/asrsSystem/DrawPanel.java
1,864
// afstandx en y staat voor de afstand tussen magazijncoordinaten,
line_comment
nl
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en<SUF> //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
True
False
1,523
2,345
34523_8
package imageProcessing; import generalStatPurpose.gpFrequencyDistributionStatFunctions; public class cmcProcKMeans { class kMeanItem { int value; int cluster; kMeanItem(int i) { value=i; cluster=-1; } } private kMeanItem[] kmset=null; private int aantalClusters=-1; private int[] centroids; // in feite MEAN private gpFrequencyDistributionStatFunctions pstat=null; //------------------------------------------------------------ cmcProcKMeans() //------------------------------------------------------------ { pstat = new gpFrequencyDistributionStatFunctions(); } //------------------------------------------------------------ public void populateSingleDimensionSet(int iaantal , int[] iset) //------------------------------------------------------------ { int aantal = iset.length; kmset = new kMeanItem[aantal]; for(int i=0;i<aantal;i++) kmset[i] = new kMeanItem(iset[i]); // aantalClusters=iaantal; centroids = new int[aantalClusters]; /* centroids[0] = 0; centroids[1] = pstat.getMode( iset ); for(int i=2;i<aantalClusters;i++) { int per = centroids[1] / (aantalClusters - 1); centroids[i] = centroids[i-1] - per; } */ // SEED - dit werkt best for(int i=0;i<aantalClusters;i++) { centroids[i] = (i+1) *10; } sho(); } //------------------------------------------------------------ private void sho() //------------------------------------------------------------ { String sLijn = "CENTROIDS : "; for(int i=0;i<aantalClusters;i++) { sLijn += "\n (" + i + ") " + centroids[i] + " "; sLijn += " OBS="+getNumberOfElementsPerCentroidViaIdx(i); } //System.out.println(sLijn); } //------------------------------------------------------------ public void doit() //------------------------------------------------------------ { startIteratie(); for(int i=0;i<10;i++) { if( itereer() == false) break; } } //------------------------------------------------------------ private void startIteratie() //------------------------------------------------------------ { int[] prevCentroids = new int[aantalClusters]; int[] afstand = new int[aantalClusters]; for(int i=0;i<aantalClusters;i++) prevCentroids[i] = centroids[i]; // loop doorheen alle waarden en alloceer for(int i=0;i<kmset.length;i++) { for(int j=0;j<aantalClusters;j++) { afstand[j] = centroids[j] - kmset[i].value; if( afstand[j] < 0 ) afstand[j] = 0 - afstand[j]; } // zoek kleinste afstand int idx=0; int min=afstand[idx]; for(int j=1;j<aantalClusters;j++) { if( afstand[j] < min ) { min = afstand[j]; idx=j; } } kmset[i].cluster = idx; // nu de MEAN op die cluster aanpassen -> andere centroid int som=0; int nn=0; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[i].value; nn++; } centroids[idx] = som/nn; } sho(); } //------------------------------------------------------------ private boolean itereer() //------------------------------------------------------------ { boolean swap=false; int[] afstand = new int[aantalClusters]; // for(int i=0;i<kmset.length;i++) { for(int j=0;j<aantalClusters;j++) { afstand[j] = centroids[j] - kmset[i].value; if( afstand[j] < 0 ) afstand[j] = 0 - afstand[j]; } // zoek kleinste afstand int idx=0; int min=afstand[idx]; for(int j=1;j<aantalClusters;j++) { if( afstand[j] < min ) { min = afstand[j]; idx=j; } } if( idx != kmset[i].cluster ) { swap=true; int oldidx = kmset[i].cluster; kmset[i].cluster = idx; // nu de MEAN op die cluster aanpassen -> andere centroid int som=0; int nn=0; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[z].value; nn++; } centroids[idx] = som/nn; // de mean op de vrorgere cluster aanpassen som=0; nn=0; idx = oldidx; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[z].value; nn++; } } } sho(); return swap; } //------------------------------------------------------------ public int[] getClusters() //------------------------------------------------------------ { int[] clusterlist = new int[kmset.length]; for(int i=0;i<kmset.length;i++ ) clusterlist[i] = kmset[i].cluster; return clusterlist; } //------------------------------------------------------------ public int getClusterViaIdx(int idx) //------------------------------------------------------------ { if( (idx >= kmset.length) || (idx<0) ) return -1; return kmset[idx].cluster; } //------------------------------------------------------------ public int getCentroidValueViaIdx(int idx) //------------------------------------------------------------ { if( (idx >= centroids.length) || (idx<0) ) return -1; return centroids[idx]; } //------------------------------------------------------------ public int getNumberOfElementsPerCentroidViaIdx(int idx) //------------------------------------------------------------ { int teller=0; if( (idx >= centroids.length) || (idx<0) ) return -1; for(int j=0;j<kmset.length;j++) { if( kmset[j].cluster == idx) teller++; } return teller; } }
cbrtekstraktor/cbrTekStraktor
src/imageProcessing/cmcProcKMeans.java
2,016
// de mean op de vrorgere cluster aanpassen
line_comment
nl
package imageProcessing; import generalStatPurpose.gpFrequencyDistributionStatFunctions; public class cmcProcKMeans { class kMeanItem { int value; int cluster; kMeanItem(int i) { value=i; cluster=-1; } } private kMeanItem[] kmset=null; private int aantalClusters=-1; private int[] centroids; // in feite MEAN private gpFrequencyDistributionStatFunctions pstat=null; //------------------------------------------------------------ cmcProcKMeans() //------------------------------------------------------------ { pstat = new gpFrequencyDistributionStatFunctions(); } //------------------------------------------------------------ public void populateSingleDimensionSet(int iaantal , int[] iset) //------------------------------------------------------------ { int aantal = iset.length; kmset = new kMeanItem[aantal]; for(int i=0;i<aantal;i++) kmset[i] = new kMeanItem(iset[i]); // aantalClusters=iaantal; centroids = new int[aantalClusters]; /* centroids[0] = 0; centroids[1] = pstat.getMode( iset ); for(int i=2;i<aantalClusters;i++) { int per = centroids[1] / (aantalClusters - 1); centroids[i] = centroids[i-1] - per; } */ // SEED - dit werkt best for(int i=0;i<aantalClusters;i++) { centroids[i] = (i+1) *10; } sho(); } //------------------------------------------------------------ private void sho() //------------------------------------------------------------ { String sLijn = "CENTROIDS : "; for(int i=0;i<aantalClusters;i++) { sLijn += "\n (" + i + ") " + centroids[i] + " "; sLijn += " OBS="+getNumberOfElementsPerCentroidViaIdx(i); } //System.out.println(sLijn); } //------------------------------------------------------------ public void doit() //------------------------------------------------------------ { startIteratie(); for(int i=0;i<10;i++) { if( itereer() == false) break; } } //------------------------------------------------------------ private void startIteratie() //------------------------------------------------------------ { int[] prevCentroids = new int[aantalClusters]; int[] afstand = new int[aantalClusters]; for(int i=0;i<aantalClusters;i++) prevCentroids[i] = centroids[i]; // loop doorheen alle waarden en alloceer for(int i=0;i<kmset.length;i++) { for(int j=0;j<aantalClusters;j++) { afstand[j] = centroids[j] - kmset[i].value; if( afstand[j] < 0 ) afstand[j] = 0 - afstand[j]; } // zoek kleinste afstand int idx=0; int min=afstand[idx]; for(int j=1;j<aantalClusters;j++) { if( afstand[j] < min ) { min = afstand[j]; idx=j; } } kmset[i].cluster = idx; // nu de MEAN op die cluster aanpassen -> andere centroid int som=0; int nn=0; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[i].value; nn++; } centroids[idx] = som/nn; } sho(); } //------------------------------------------------------------ private boolean itereer() //------------------------------------------------------------ { boolean swap=false; int[] afstand = new int[aantalClusters]; // for(int i=0;i<kmset.length;i++) { for(int j=0;j<aantalClusters;j++) { afstand[j] = centroids[j] - kmset[i].value; if( afstand[j] < 0 ) afstand[j] = 0 - afstand[j]; } // zoek kleinste afstand int idx=0; int min=afstand[idx]; for(int j=1;j<aantalClusters;j++) { if( afstand[j] < min ) { min = afstand[j]; idx=j; } } if( idx != kmset[i].cluster ) { swap=true; int oldidx = kmset[i].cluster; kmset[i].cluster = idx; // nu de MEAN op die cluster aanpassen -> andere centroid int som=0; int nn=0; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[z].value; nn++; } centroids[idx] = som/nn; // de mean<SUF> som=0; nn=0; idx = oldidx; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[z].value; nn++; } } } sho(); return swap; } //------------------------------------------------------------ public int[] getClusters() //------------------------------------------------------------ { int[] clusterlist = new int[kmset.length]; for(int i=0;i<kmset.length;i++ ) clusterlist[i] = kmset[i].cluster; return clusterlist; } //------------------------------------------------------------ public int getClusterViaIdx(int idx) //------------------------------------------------------------ { if( (idx >= kmset.length) || (idx<0) ) return -1; return kmset[idx].cluster; } //------------------------------------------------------------ public int getCentroidValueViaIdx(int idx) //------------------------------------------------------------ { if( (idx >= centroids.length) || (idx<0) ) return -1; return centroids[idx]; } //------------------------------------------------------------ public int getNumberOfElementsPerCentroidViaIdx(int idx) //------------------------------------------------------------ { int teller=0; if( (idx >= centroids.length) || (idx<0) ) return -1; for(int j=0;j<kmset.length;j++) { if( kmset[j].cluster == idx) teller++; } return teller; } }
True
False
1,527
4,518
43907_0
package nl.timgoes.transactionservice.transactionservice.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class TransactionServiceConfig { @LoadBalanced //Moet gebeuren voor euruka anders werkt het niet @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } }
timgoes1997/CapitaSelectaJEA6SpringBoot
transaction-service/src/main/java/nl/timgoes/transactionservice/transactionservice/config/TransactionServiceConfig.java
130
//Moet gebeuren voor euruka anders werkt het niet
line_comment
nl
package nl.timgoes.transactionservice.transactionservice.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class TransactionServiceConfig { @LoadBalanced //Moet gebeuren<SUF> @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } }
True
False
1,532
968
22405_2
package hamhamdash.states; import hamhamdash.*; /** * * @author Serhan Uygur */ public class StatePause extends State { private String toDrawImage = ""; // Pause Screens // [ Main Screen Name ][ Sub Screens ][ Pages ] private String[][][] pauseScreens = { // Item 0, zonder submenu's { {"pause_res_game"}, {""}, {""} }, // Item 1, met submenu's { {"pause_help"}, {"game_goal", "game_controls", "game_objects", "game_back"}, {"2", "2", "8", "0"} }, // Item 2, zonder submenu's { {"pause_exit_title"}, {""}, {""} }, // Item 3, zonder submenu's { {"pause_exit_windows"}, {""}, {""} } }; // Counters for the screens private int currentMainScreen = 0; private int currentSubScreen = 0; private int currentPage = 0; // Checkers for sub or not private boolean inSub = false; private boolean arePages = false; public StatePause() { super("pauze"); toDrawImage = pauseScreens[0][0][0]; game.stopTimer(); started = true; } @Override public void start() { } @Override public void doFrame() { if(started) { if(game.getKey(Game.KeyEsc)) { game.clearKey(Game.KeyEsc); if(inSub) //Go back to previous menu { inSub = false; toDrawImage = pauseScreens[1][0][0]; currentSubScreen = 0; } else //Exit pause state { game.recoverState(); game.startTimer(); game.repaint(); // game.removeGameState("Pause"); } } //navigate between options else if(game.getKey(Game.KeyUp)) // Moves selection up { game.clearKey(Game.KeyUp); currentPage = 1; prevScreen(pauseScreens); } else if(game.getKey(Game.KeyDown)) // Moves selection down { game.clearKey(Game.KeyDown); currentPage = 1; nextScreen(pauseScreens); } else if(game.getKey(Game.KeyEnter)) // Confirm selection { game.clearKey(Game.KeyEnter); if(toDrawImage.equals(pauseScreens[0][0][0])) { game.recoverState(); // game.removeGameState("Pause"); } else if(toDrawImage.equals(pauseScreens[1][0][0])) // Help item has subs { inSub = true; toDrawImage = pauseScreens[1][1][0] + 1; // select 1st sub page } else if(toDrawImage.equals(pauseScreens[2][0][0])) { game.setCurrentState("Title"); } else if(toDrawImage.equals(pauseScreens[3][0][0])) { game.exitEngine("Thank you for playing!"); } if(toDrawImage.equals(pauseScreens[1][1][3] + 1)) { inSub = false; toDrawImage = pauseScreens[1][0][0]; currentSubScreen = 0; } } //Cycle through pages else if(game.getKey(Game.KeyRight) && inSub) //Go page forward { game.clearKey(Game.KeyRight); nextPage(pauseScreens); } else if(game.getKey(Game.KeyLeft) && inSub) //Go back a page { game.clearKey(Game.KeyLeft); prevPage(pauseScreens); } } } @Override public void paintFrame() { if(started) { game.drawImage(game.viewWidth() / 2 - (256 / 2), game.viewHeight() / 2 - (250 / 2), toDrawImage, false); } } public void nextScreen(String[][][] screens) { String toDrawImage = ""; if(!inSub) { if(currentMainScreen < screens.length - 1) // -1 because we start with 0 { currentMainScreen++; } toDrawImage = screens[currentMainScreen][0][0]; } else { if(currentSubScreen < screens[currentMainScreen].length) { currentSubScreen++; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1; } this.toDrawImage = toDrawImage; } public void prevScreen(String[][][] screens) { String toDrawImage = ""; if(!inSub) { if(currentMainScreen > 0) { currentMainScreen--; } toDrawImage = screens[currentMainScreen][0][0]; } else { if(currentSubScreen > 0) { currentSubScreen--; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1; } this.toDrawImage = toDrawImage; } public void nextPage(String[][][] screens) { String toDrawImage = ""; if(currentPage < Integer.parseInt(screens[currentMainScreen][2][currentSubScreen])) { currentPage++; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage; this.toDrawImage = toDrawImage; } public void prevPage(String[][][] screens) { String toDrawImage = ""; if(currentPage > 1) { currentPage--; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage; this.toDrawImage = toDrawImage; } }
Lenrocexe/HamHamDash
src/hamhamdash/states/StatePause.java
1,709
// Item 0, zonder submenu's
line_comment
nl
package hamhamdash.states; import hamhamdash.*; /** * * @author Serhan Uygur */ public class StatePause extends State { private String toDrawImage = ""; // Pause Screens // [ Main Screen Name ][ Sub Screens ][ Pages ] private String[][][] pauseScreens = { // Item 0,<SUF> { {"pause_res_game"}, {""}, {""} }, // Item 1, met submenu's { {"pause_help"}, {"game_goal", "game_controls", "game_objects", "game_back"}, {"2", "2", "8", "0"} }, // Item 2, zonder submenu's { {"pause_exit_title"}, {""}, {""} }, // Item 3, zonder submenu's { {"pause_exit_windows"}, {""}, {""} } }; // Counters for the screens private int currentMainScreen = 0; private int currentSubScreen = 0; private int currentPage = 0; // Checkers for sub or not private boolean inSub = false; private boolean arePages = false; public StatePause() { super("pauze"); toDrawImage = pauseScreens[0][0][0]; game.stopTimer(); started = true; } @Override public void start() { } @Override public void doFrame() { if(started) { if(game.getKey(Game.KeyEsc)) { game.clearKey(Game.KeyEsc); if(inSub) //Go back to previous menu { inSub = false; toDrawImage = pauseScreens[1][0][0]; currentSubScreen = 0; } else //Exit pause state { game.recoverState(); game.startTimer(); game.repaint(); // game.removeGameState("Pause"); } } //navigate between options else if(game.getKey(Game.KeyUp)) // Moves selection up { game.clearKey(Game.KeyUp); currentPage = 1; prevScreen(pauseScreens); } else if(game.getKey(Game.KeyDown)) // Moves selection down { game.clearKey(Game.KeyDown); currentPage = 1; nextScreen(pauseScreens); } else if(game.getKey(Game.KeyEnter)) // Confirm selection { game.clearKey(Game.KeyEnter); if(toDrawImage.equals(pauseScreens[0][0][0])) { game.recoverState(); // game.removeGameState("Pause"); } else if(toDrawImage.equals(pauseScreens[1][0][0])) // Help item has subs { inSub = true; toDrawImage = pauseScreens[1][1][0] + 1; // select 1st sub page } else if(toDrawImage.equals(pauseScreens[2][0][0])) { game.setCurrentState("Title"); } else if(toDrawImage.equals(pauseScreens[3][0][0])) { game.exitEngine("Thank you for playing!"); } if(toDrawImage.equals(pauseScreens[1][1][3] + 1)) { inSub = false; toDrawImage = pauseScreens[1][0][0]; currentSubScreen = 0; } } //Cycle through pages else if(game.getKey(Game.KeyRight) && inSub) //Go page forward { game.clearKey(Game.KeyRight); nextPage(pauseScreens); } else if(game.getKey(Game.KeyLeft) && inSub) //Go back a page { game.clearKey(Game.KeyLeft); prevPage(pauseScreens); } } } @Override public void paintFrame() { if(started) { game.drawImage(game.viewWidth() / 2 - (256 / 2), game.viewHeight() / 2 - (250 / 2), toDrawImage, false); } } public void nextScreen(String[][][] screens) { String toDrawImage = ""; if(!inSub) { if(currentMainScreen < screens.length - 1) // -1 because we start with 0 { currentMainScreen++; } toDrawImage = screens[currentMainScreen][0][0]; } else { if(currentSubScreen < screens[currentMainScreen].length) { currentSubScreen++; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1; } this.toDrawImage = toDrawImage; } public void prevScreen(String[][][] screens) { String toDrawImage = ""; if(!inSub) { if(currentMainScreen > 0) { currentMainScreen--; } toDrawImage = screens[currentMainScreen][0][0]; } else { if(currentSubScreen > 0) { currentSubScreen--; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1; } this.toDrawImage = toDrawImage; } public void nextPage(String[][][] screens) { String toDrawImage = ""; if(currentPage < Integer.parseInt(screens[currentMainScreen][2][currentSubScreen])) { currentPage++; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage; this.toDrawImage = toDrawImage; } public void prevPage(String[][][] screens) { String toDrawImage = ""; if(currentPage > 1) { currentPage--; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage; this.toDrawImage = toDrawImage; } }
True
False
1,535
1,281
68362_0
package be.pxl.ja; import be.pxl.ja.command.*; import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class GameEngine { private static final Random RANDOM = new Random(); public static Detective detective; private Scanner scanner; public static boolean murderSolved; public static Envelope<Part> envelope; private HelpCommand helpCommand = new HelpCommand(); private SuspectsCommand suspectsCommand = new SuspectsCommand(); private RoomsCommand roomsCommand = new RoomsCommand(); private WeaponsCommand weaponsCommand = new WeaponsCommand(); private ClueCommand clueCommand = new ClueCommand(); private GoToCommand goToCommand = new GoToCommand(); private DescribeCommand describeCommand = new DescribeCommand(); private UnlockCommand unlockCommand = new UnlockCommand(); private AccuseCommand accuseCommand = new AccuseCommand(); public static List<Room> rooms; public static List<Weapon> weapons; public static List<Suspect> suspects; public static Mansion mansion; public static List<Part> parts; public static List<Anagram> anagrams; public static List<CrackTheCode> crackTheCodes; public GameEngine(Scanner scanner) { this.scanner = scanner; } public void initialize(String playerName) throws FileNotFoundException { murderSolved = false; File file = new File("src/main/resources/cluedo.txt"); File anagram = new File("src/main/resources/anagrams.txt"); File crackTheCode = new File("src/main/resources/crackthecode.txt"); scanner = new Scanner(file); rooms = new ArrayList<>(); weapons = new ArrayList<>(); suspects = new ArrayList<>(); parts = new ArrayList<>(); String objectType = null; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if ("#ROOMS".equals(line) || "#WEAPONS".equals(line) || "#SUSPECTS".equals(line)) { objectType = line; } else { if ("#ROOMS".equals(objectType)) { Room room = new Room(line); if (!rooms.contains(room)) { rooms.add(room); parts.add(room); } } else if ("#WEAPONS".equals(objectType)) { Weapon weapon = new Weapon(line); if (!weapons.contains(weapon)) { weapons.add(weapon); parts.add(weapon); } } else if ("#SUSPECTS".equals(objectType)) { String[] params = line.split(";"); String name = params[0].substring(params[0].indexOf(" ")).strip(); String title = params[0].substring(0, params[0].indexOf(" ")); Suspect suspect = new Suspect(name); suspect.setAge(Integer.parseInt(params[1])); suspect.setNationality(params[2]); suspect.setOccupation(params[2]); suspect.setTitle(title); if (!suspects.contains(suspect)) { suspects.add(suspect); parts.add(suspect); } } } } detective = new Detective(playerName); Room crimeScene = rooms.stream() .skip(RANDOM.nextInt(rooms.size())) .findFirst() .orElseThrow(() -> new CluedoException("No rooms found from game file")); crimeScene.setCrimeScene(true); Weapon murderWeapon = weapons.stream() .skip(RANDOM.nextInt(weapons.size())) .findFirst() .orElseThrow(() -> new CluedoException("No weapons found from game file")); Suspect murderer = suspects.stream() .skip(RANDOM.nextInt(suspects.size())) .findFirst() .orElseThrow(() -> new CluedoException("No suspects found from game file")); envelope = new Envelope<>(); envelope.addSecret(crimeScene); envelope.addSecret(murderWeapon); envelope.addSecret(murderer); // overige wapens en suspects verdelen over de kamers List<Weapon> roomWeapons = new ArrayList<>(); for (Weapon weapon : weapons){ if (!weapon.equals(murderWeapon)){ roomWeapons.add(weapon); } } List<Suspect> roomSuspects = new ArrayList<>(); for (Suspect suspect : suspects){ if (!suspect.equals(murderer)){ roomSuspects.add(suspect); } } for (Room room : rooms) { if (roomWeapons.size() != 0){ Weapon weapon = roomWeapons.get(RANDOM.nextInt(roomWeapons.size())); roomWeapons.remove(weapon); room.setWeapon(weapon); } if (roomSuspects.size() != 0){ Suspect suspect = roomSuspects.get(RANDOM.nextInt(roomSuspects.size())); roomSuspects.remove(suspect); room.setSuspect(suspect); } } mansion = new Mansion(new ArrayList<>(rooms)); detective.moveTo(mansion.getHall()); anagrams = new ArrayList<>(); scanner = new Scanner(anagram); while(scanner.hasNextLine()){ String line = scanner.nextLine(); String[] anagramPieces = line.split(";"); Anagram anagramConstruct = new Anagram(anagramPieces[0], anagramPieces[1], anagramPieces[2]); anagrams.add(anagramConstruct); } crackTheCodes = new ArrayList<>(); scanner = new Scanner(crackTheCode); int counter = 0; while(scanner.hasNextLine()){ String line = scanner.nextLine(); String[] questions = new String[5]; String answer; if ("#".equals(line.substring(0, 1))){ counter = 0; } else if (line.contains("ANSWER")){ String[] crackTheCodePieces = line.split(":"); answer = crackTheCodePieces[1].strip(); CrackTheCode crackTheCodeConstruct = new CrackTheCode(questions, answer); crackTheCodes.add(crackTheCodeConstruct); } else { questions[counter] = line; counter++; } } //--------------------------------------------------- scanner.close(); // einde van init, alle code voor deze lijn } public void start() { System.out.println("Who murdered Dr. Black? Where did the crime took place, and which weapon was used?"); System.out.println("Type 'help' for information..."); } public void executeCommand(String command) { if ("suspects".equals(command)){ suspectsCommand.execute(command); } else if ("rooms".equals(command)){ roomsCommand.execute(command); } else if ("weapons".equals(command)){ weaponsCommand.execute(command); } else if ("describe".equals(command)){ describeCommand.execute(command); } else if ("unlock".equals(command)){ unlockCommand.execute(command); } else if (command.contains("clue")){ //voorlopig clueCommand.execute(command.substring(5)); } else if ("help".equals(command)){ helpCommand.execute(command); } else if (command.contains("accuse")){ //voorlopig accuseCommand.execute(command.substring(7)); } else if (command.contains("goto")){ goToCommand.execute(command.substring(5)); } } public void printLocation() { System.out.println("You are in the " + detective.getCurrentRoom().getName()); } public boolean isMurderSolved() { return murderSolved; } }
PXLJavaAdvanced/java-adv-pe-cluedo-team-goud
src/main/java/be/pxl/ja/GameEngine.java
2,220
// overige wapens en suspects verdelen over de kamers
line_comment
nl
package be.pxl.ja; import be.pxl.ja.command.*; import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class GameEngine { private static final Random RANDOM = new Random(); public static Detective detective; private Scanner scanner; public static boolean murderSolved; public static Envelope<Part> envelope; private HelpCommand helpCommand = new HelpCommand(); private SuspectsCommand suspectsCommand = new SuspectsCommand(); private RoomsCommand roomsCommand = new RoomsCommand(); private WeaponsCommand weaponsCommand = new WeaponsCommand(); private ClueCommand clueCommand = new ClueCommand(); private GoToCommand goToCommand = new GoToCommand(); private DescribeCommand describeCommand = new DescribeCommand(); private UnlockCommand unlockCommand = new UnlockCommand(); private AccuseCommand accuseCommand = new AccuseCommand(); public static List<Room> rooms; public static List<Weapon> weapons; public static List<Suspect> suspects; public static Mansion mansion; public static List<Part> parts; public static List<Anagram> anagrams; public static List<CrackTheCode> crackTheCodes; public GameEngine(Scanner scanner) { this.scanner = scanner; } public void initialize(String playerName) throws FileNotFoundException { murderSolved = false; File file = new File("src/main/resources/cluedo.txt"); File anagram = new File("src/main/resources/anagrams.txt"); File crackTheCode = new File("src/main/resources/crackthecode.txt"); scanner = new Scanner(file); rooms = new ArrayList<>(); weapons = new ArrayList<>(); suspects = new ArrayList<>(); parts = new ArrayList<>(); String objectType = null; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if ("#ROOMS".equals(line) || "#WEAPONS".equals(line) || "#SUSPECTS".equals(line)) { objectType = line; } else { if ("#ROOMS".equals(objectType)) { Room room = new Room(line); if (!rooms.contains(room)) { rooms.add(room); parts.add(room); } } else if ("#WEAPONS".equals(objectType)) { Weapon weapon = new Weapon(line); if (!weapons.contains(weapon)) { weapons.add(weapon); parts.add(weapon); } } else if ("#SUSPECTS".equals(objectType)) { String[] params = line.split(";"); String name = params[0].substring(params[0].indexOf(" ")).strip(); String title = params[0].substring(0, params[0].indexOf(" ")); Suspect suspect = new Suspect(name); suspect.setAge(Integer.parseInt(params[1])); suspect.setNationality(params[2]); suspect.setOccupation(params[2]); suspect.setTitle(title); if (!suspects.contains(suspect)) { suspects.add(suspect); parts.add(suspect); } } } } detective = new Detective(playerName); Room crimeScene = rooms.stream() .skip(RANDOM.nextInt(rooms.size())) .findFirst() .orElseThrow(() -> new CluedoException("No rooms found from game file")); crimeScene.setCrimeScene(true); Weapon murderWeapon = weapons.stream() .skip(RANDOM.nextInt(weapons.size())) .findFirst() .orElseThrow(() -> new CluedoException("No weapons found from game file")); Suspect murderer = suspects.stream() .skip(RANDOM.nextInt(suspects.size())) .findFirst() .orElseThrow(() -> new CluedoException("No suspects found from game file")); envelope = new Envelope<>(); envelope.addSecret(crimeScene); envelope.addSecret(murderWeapon); envelope.addSecret(murderer); // overige wapens<SUF> List<Weapon> roomWeapons = new ArrayList<>(); for (Weapon weapon : weapons){ if (!weapon.equals(murderWeapon)){ roomWeapons.add(weapon); } } List<Suspect> roomSuspects = new ArrayList<>(); for (Suspect suspect : suspects){ if (!suspect.equals(murderer)){ roomSuspects.add(suspect); } } for (Room room : rooms) { if (roomWeapons.size() != 0){ Weapon weapon = roomWeapons.get(RANDOM.nextInt(roomWeapons.size())); roomWeapons.remove(weapon); room.setWeapon(weapon); } if (roomSuspects.size() != 0){ Suspect suspect = roomSuspects.get(RANDOM.nextInt(roomSuspects.size())); roomSuspects.remove(suspect); room.setSuspect(suspect); } } mansion = new Mansion(new ArrayList<>(rooms)); detective.moveTo(mansion.getHall()); anagrams = new ArrayList<>(); scanner = new Scanner(anagram); while(scanner.hasNextLine()){ String line = scanner.nextLine(); String[] anagramPieces = line.split(";"); Anagram anagramConstruct = new Anagram(anagramPieces[0], anagramPieces[1], anagramPieces[2]); anagrams.add(anagramConstruct); } crackTheCodes = new ArrayList<>(); scanner = new Scanner(crackTheCode); int counter = 0; while(scanner.hasNextLine()){ String line = scanner.nextLine(); String[] questions = new String[5]; String answer; if ("#".equals(line.substring(0, 1))){ counter = 0; } else if (line.contains("ANSWER")){ String[] crackTheCodePieces = line.split(":"); answer = crackTheCodePieces[1].strip(); CrackTheCode crackTheCodeConstruct = new CrackTheCode(questions, answer); crackTheCodes.add(crackTheCodeConstruct); } else { questions[counter] = line; counter++; } } //--------------------------------------------------- scanner.close(); // einde van init, alle code voor deze lijn } public void start() { System.out.println("Who murdered Dr. Black? Where did the crime took place, and which weapon was used?"); System.out.println("Type 'help' for information..."); } public void executeCommand(String command) { if ("suspects".equals(command)){ suspectsCommand.execute(command); } else if ("rooms".equals(command)){ roomsCommand.execute(command); } else if ("weapons".equals(command)){ weaponsCommand.execute(command); } else if ("describe".equals(command)){ describeCommand.execute(command); } else if ("unlock".equals(command)){ unlockCommand.execute(command); } else if (command.contains("clue")){ //voorlopig clueCommand.execute(command.substring(5)); } else if ("help".equals(command)){ helpCommand.execute(command); } else if (command.contains("accuse")){ //voorlopig accuseCommand.execute(command.substring(7)); } else if (command.contains("goto")){ goToCommand.execute(command.substring(5)); } } public void printLocation() { System.out.println("You are in the " + detective.getCurrentRoom().getName()); } public boolean isMurderSolved() { return murderSolved; } }
True
False
1,537
755
34147_17
/*_x000D_ * Copyright (C) 2016 Dienst voor het kadaster en de openbare registers_x000D_ * _x000D_ * This file is part of Imvertor._x000D_ *_x000D_ * Imvertor is free software: you can redistribute it and/or modify_x000D_ * it under the terms of the GNU General Public License as published by_x000D_ * the Free Software Foundation, either version 3 of the License, or_x000D_ * (at your option) any later version._x000D_ *_x000D_ * Imvertor is distributed in the hope that it will be useful,_x000D_ * but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_ * GNU General Public License for more details._x000D_ *_x000D_ * You should have received a copy of the GNU General Public License_x000D_ * along with Imvertor. If not, see <http://www.gnu.org/licenses/>._x000D_ *_x000D_ */_x000D_ _x000D_ package nl.imvertor.common.file;_x000D_ _x000D_ import java.io.File;_x000D_ import java.io.FileOutputStream;_x000D_ import java.util.HashMap;_x000D_ import java.util.Iterator;_x000D_ import java.util.List;_x000D_ import java.util.Vector;_x000D_ _x000D_ import javax.xml.namespace.QName;_x000D_ import javax.xml.parsers.DocumentBuilder;_x000D_ import javax.xml.parsers.DocumentBuilderFactory;_x000D_ import javax.xml.xpath.XPath;_x000D_ import javax.xml.xpath.XPathConstants;_x000D_ import javax.xml.xpath.XPathExpression;_x000D_ _x000D_ import org.apache.commons.lang3.StringUtils;_x000D_ import org.apache.log4j.Logger;_x000D_ import org.custommonkey.xmlunit.DetailedDiff;_x000D_ import org.custommonkey.xmlunit.Difference;_x000D_ import org.custommonkey.xmlunit.XMLTestCase;_x000D_ import org.custommonkey.xmlunit.XMLUnit;_x000D_ import org.w3c.dom.Document;_x000D_ import org.w3c.dom.NodeList;_x000D_ import org.w3c.dom.bootstrap.DOMImplementationRegistry;_x000D_ import org.w3c.dom.ls.DOMImplementationLS;_x000D_ import org.w3c.dom.ls.LSOutput;_x000D_ import org.w3c.dom.ls.LSSerializer;_x000D_ import org.xml.sax.ErrorHandler;_x000D_ import org.xml.sax.InputSource;_x000D_ import org.xml.sax.SAXException;_x000D_ import org.xml.sax.SAXParseException;_x000D_ _x000D_ import net.sf.saxon.xpath.XPathFactoryImpl;_x000D_ import nl.imvertor.common.Configurator;_x000D_ import nl.imvertor.common.Transformer;_x000D_ import nl.imvertor.common.xsl.extensions.ImvertorCompareXML;_x000D_ _x000D_ /**_x000D_ * An XmlFile represents an XmlFile on the file system._x000D_ * _x000D_ * The XmlFile is an AnyFile and therefore does not access the chain environment._x000D_ * _x000D_ * @author arjan_x000D_ *_x000D_ */_x000D_ public class XmlFile extends AnyFile implements ErrorHandler {_x000D_ _x000D_ private static final long serialVersionUID = -4351737187940152153L;_x000D_ _x000D_ protected static final Logger logger = Logger.getLogger(XmlFile.class);_x000D_ _x000D_ static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";_x000D_ static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";_x000D_ _x000D_ protected static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";_x000D_ protected static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";_x000D_ protected static final String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";_x000D_ protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";_x000D_ protected static final String EXTERNAL_PARAMETER_ENTITIES_ID = "http://xml.org/sax/features/external-parameter-entities";_x000D_ protected static final String EXTERNAL_GENERAL_ENTITIES_ID = "http://xml.org/sax/features/external-general-entities";_x000D_ protected static final String IGNORE_DTD_FEATURE_ID = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; // http://www.isocra.com/2006/05/making-xerces-ignore-a-dtd/_x000D_ _x000D_ protected static final String LEXICAL_HANDLER_PROPERTY_ID = "http://xml.org/sax/properties/lexical-handler";_x000D_ protected static final String DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser";_x000D_ _x000D_ protected static final int WFCODE_OKAY = 0;_x000D_ protected static final int WFCODE_WARNING = 1;_x000D_ protected static final int WFCODE_ERROR = 2;_x000D_ protected static final int WFCODE_FATAL = 3;_x000D_ _x000D_ // parameters die de verwerking van het XML file bepalen_x000D_ _x000D_ public boolean namespace = true; // namespace aware?_x000D_ public boolean validate = false; // valideren?_x000D_ public boolean xinclude = true; // herken xinclude statements?_x000D_ public boolean schema = false; // zoek naar schema bij valideren?_x000D_ public boolean schemacheck = false; // schema ook checken?_x000D_ public boolean dtd = false; // zoek naar dtd bij valideren?_x000D_ public boolean auto = false; // automagically determine how to parse this file?_x000D_ public boolean external = false; // externe entiteiten ophalen?_x000D_ public boolean inquiry = false; // zoek alleen maar naar informatie over dit file?_x000D_ _x000D_ private Document dom = null;_x000D_ _x000D_ private int wfcode = WFCODE_OKAY; // a code indicating the Wellformedness of the XML file._x000D_ _x000D_ private Vector<String> messages = new Vector<String>();_x000D_ _x000D_ public static void main(String[] args) {_x000D_ _x000D_ //XmlFile file = new XmlFile("D:\\projects\\arjan\\Java development\\CommonHandlers\\sandbox\\EHcache\\config\\ehcache.xml");_x000D_ XmlFile file = new XmlFile("D:\\projects\\validprojects\\Kadaster-Imvertor\\Imvertor-OS-work\\default\\comply\\template\\xl\\worksheets\\sheet1.xml");_x000D_ System.out.println(file.isValid());_x000D_ file.getMessages();_x000D_ _x000D_ }_x000D_ _x000D_ public XmlFile(String pathname) {_x000D_ super(pathname);_x000D_ }_x000D_ public XmlFile(File file) {_x000D_ super(file.getAbsolutePath());_x000D_ }_x000D_ public XmlFile(File folder, String filename) {_x000D_ super(folder,filename);_x000D_ }_x000D_ _x000D_ public String getFileType() {_x000D_ return "XML";_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Lees een file in naar een DOM Document._x000D_ * _x000D_ * @param file_x000D_ * @return_x000D_ * @throws Exception_x000D_ */_x000D_ public Document toDocument() throws Exception {_x000D_ Document d = buildDom();_x000D_ return d;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zet een Document weg als file. Transformeer middels het XSLT file. Als_x000D_ * XSLT file is "", identity transform._x000D_ * _x000D_ * @param doc_x000D_ * @param xsltfile_x000D_ * @param parms_x000D_ * @throws Exception_x000D_ */_x000D_ public void fromDocument(Document doc) throws Exception {_x000D_ DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); _x000D_ DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("XML 3.0 LS 3.0");_x000D_ if (impl == null) {_x000D_ System.out.println("No DOMImplementation found !");_x000D_ System.exit(0);_x000D_ }_x000D_ LSSerializer serializer = impl.createLSSerializer();_x000D_ LSOutput output = impl.createLSOutput();_x000D_ output.setEncoding("UTF-8");_x000D_ output.setByteStream(new FileOutputStream(this));_x000D_ serializer.write(doc, output);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Build a DOM Document representation of this XML file. _x000D_ * _x000D_ * @return_x000D_ * @throws Exception_x000D_ */_x000D_ private Document buildDom() throws Exception {_x000D_ return this.buildDom(this);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Build a DOM Document representation of some external XML file. _x000D_ * _x000D_ * @return_x000D_ * @throws Exception_x000D_ */_x000D_ private Document buildDom(File file) throws Exception {_x000D_ _x000D_ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();_x000D_ InputSource in = new InputSource(file.getAbsolutePath());_x000D_ _x000D_ docFactory.setValidating(validate);_x000D_ docFactory.setXIncludeAware(xinclude);_x000D_ docFactory.setFeature(VALIDATION_FEATURE_ID, validate);_x000D_ docFactory.setFeature(NAMESPACES_FEATURE_ID, namespace);_x000D_ docFactory.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schema);_x000D_ docFactory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemacheck);_x000D_ docFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_ID, external);_x000D_ docFactory.setFeature(EXTERNAL_PARAMETER_ENTITIES_ID, external);_x000D_ _x000D_ DocumentBuilder db = docFactory.newDocumentBuilder();_x000D_ return db.parse(in);_x000D_ }_x000D_ _x000D_ public Document getDom() throws Exception {_x000D_ if (dom == null) _x000D_ return buildDom(this);_x000D_ else _x000D_ return dom;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Benader de inhoud dmv. een Xpath expressie. Geef het laatste item die aan het criterium voldoet af als String._x000D_ * _x000D_ * @param outfile_x000D_ * @param xslFilePath_x000D_ * @throws Exception_x000D_ */_x000D_ public String xpath(String expression, HashMap<String, String> parms) throws Exception {_x000D_ return (String) xpathToObject(expression, parms, XPathConstants.STRING);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Benader de inhoud dmv. een Xpath expressie. _x000D_ * _x000D_ * @param outfile_x000D_ * @param xslFilePath_x000D_ * @throws Exception_x000D_ */_x000D_ public Object xpathToObject(String expression, HashMap<String, String> parms, QName returnType) throws Exception {_x000D_ if (dom == null) dom = this.buildDom();_x000D_ XPathFactoryImpl xpf = new XPathFactoryImpl();_x000D_ XPath xpe = xpf.newXPath();_x000D_ XPathExpression find = xpe.compile(expression);_x000D_ return find.evaluate(dom, returnType);_x000D_ }_x000D_ _x000D_ public String xpath(String expression) throws Exception {_x000D_ return xpath(expression,new HashMap<String,String>());_x000D_ }_x000D_ _x000D_ /** _x000D_ * Transform the XML file to a canonical form_x000D_ * _x000D_ * @param outfile_x000D_ * @param xslFile_x000D_ * @param parms_x000D_ * @throws Exception_x000D_ */_x000D_ public void fileToCanonicalFile(XmlFile outfile) throws Exception {_x000D_ logger.debug("Canonizing " + this.getCanonicalPath());_x000D_ if (dom == null) dom = this.buildDom();_x000D_ outfile.fromDocument(dom);_x000D_ }_x000D_ _x000D_ public boolean isWellFormed() {_x000D_ messages.removeAllElements();_x000D_ try {_x000D_ wfcode = WFCODE_OKAY;_x000D_ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();_x000D_ factory.setValidating(false);_x000D_ factory.setNamespaceAware(true);_x000D_ factory.setXIncludeAware(true);_x000D_ _x000D_ DocumentBuilder builder = factory.newDocumentBuilder();_x000D_ _x000D_ builder.setErrorHandler(this); _x000D_ builder.parse(new InputSource(this.getCanonicalPath()));_x000D_ _x000D_ } catch (Exception e) {_x000D_ wfcode = WFCODE_FATAL;_x000D_ }_x000D_ return wfcode < WFCODE_ERROR;_x000D_ }_x000D_ _x000D_ public boolean isValid() {_x000D_ messages.removeAllElements();_x000D_ try {_x000D_ wfcode = WFCODE_OKAY;_x000D_ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();_x000D_ factory.setValidating(true);_x000D_ factory.setNamespaceAware(true);_x000D_ factory.setXIncludeAware(true);_x000D_ factory.setAttribute(_x000D_ "http://java.sun.com/xml/jaxp/properties/schemaLanguage",_x000D_ "http://www.w3.org/2001/XMLSchema");_x000D_ _x000D_ DocumentBuilder builder = factory.newDocumentBuilder();_x000D_ _x000D_ builder.setErrorHandler(this); _x000D_ builder.parse(new InputSource(this.getCanonicalPath()));_x000D_ } catch (Exception e) {_x000D_ wfcode = WFCODE_FATAL;_x000D_ }_x000D_ return wfcode < WFCODE_ERROR;_x000D_ }_x000D_ _x000D_ public Vector<String> getMessages() {_x000D_ return messages;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Compare this control file to the passed test file, store result in file. Return true if files are the same._x000D_ * _x000D_ * Difference types are listed as constants in _x000D_ * <a href="http://xmlunit.sourceforge.net/api/org/custommonkey/xmlunit/DifferenceConstants.html">here</a>_x000D_ * _x000D_ * @param controlXmlPath_x000D_ * @param testXmlPath_x000D_ * @param resultPath_x000D_ * @return_x000D_ * @throws Exception_x000D_ */_x000D_ public boolean xmlUnitCompareXML(XmlFile testXmlFile, XmlFile resultFile) throws Exception {_x000D_ XmlFile controlXmlFile = this;_x000D_ _x000D_ XMLUnit.setCompareUnmatched(false);_x000D_ XMLTestCase testcase = new Case(this.getName());_x000D_ _x000D_ DetailedDiff myDiff = new DetailedDiff(testcase.compareXML(controlXmlFile.getContent(), testXmlFile.getContent()));_x000D_ _x000D_ @SuppressWarnings("unchecked")_x000D_ List<Difference> allDifferences = myDiff.getAllDifferences();_x000D_ Iterator<Difference> it = allDifferences.iterator();_x000D_ String analysis = "<diffs>";_x000D_ while (it.hasNext()) {_x000D_ Difference d = it.next();_x000D_ analysis += "<diff"_x000D_ + " desc=\"" + safe(d.getDescription()) + "\""_x000D_ + ">";_x000D_ analysis += "<ctrl"_x000D_ + " path=\"" + d.getControlNodeDetail().getXpathLocation() + "\""_x000D_ + " value=\"" + safe(d.getControlNodeDetail().getValue()) + "\""_x000D_ + "/>";_x000D_ analysis += "<test"_x000D_ + " path=\"" + d.getTestNodeDetail().getXpathLocation() + "\""_x000D_ + " value=\"" + safe(d.getTestNodeDetail().getValue()) + "\""_x000D_ + "/>";_x000D_ analysis += "</diff>";_x000D_ }_x000D_ analysis += "</diffs>";_x000D_ resultFile.setContent(analysis);_x000D_ return (allDifferences.size() == 0) ? true: false;_x000D_ }_x000D_ _x000D_ /** _x000D_ * Replace special characters in XML string._x000D_ * _x000D_ * @param s_x000D_ * @return_x000D_ */_x000D_ private String safe(String s) {_x000D_ s = StringUtils.replace(s,"&","&amp;");_x000D_ s = StringUtils.replace(s,"<","&lt;");_x000D_ s = StringUtils.replace(s,">","&gt;");_x000D_ s = StringUtils.replace(s,"\"","&quot;");_x000D_ return s;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Introduce the XmlFile class as a valid JUnit TestCase class._x000D_ * _x000D_ * @author arjan_x000D_ *_x000D_ */_x000D_ private class Case extends XMLTestCase {_x000D_ _x000D_ public Case(String name) {_x000D_ super(name);_x000D_ }_x000D_ _x000D_ } _x000D_ _x000D_ @Override_x000D_ public void error(SAXParseException exception) throws SAXException {_x000D_ messages.add(exception.getMessage());_x000D_ wfcode = WFCODE_ERROR;_x000D_ }_x000D_ @Override_x000D_ public void fatalError(SAXParseException exception) throws SAXException {_x000D_ messages.add(exception.getMessage());_x000D_ wfcode = WFCODE_FATAL;_x000D_ }_x000D_ @Override_x000D_ public void warning(SAXParseException exception) throws SAXException {_x000D_ messages.add(exception.getMessage());_x000D_ wfcode = WFCODE_WARNING;_x000D_ }_x000D_ _x000D_ public static String xmlescape(String s) {_x000D_ s = s.replace("&", "&amp;");_x000D_ s = s.replace("<", "&lt;");_x000D_ return s;_x000D_ }_x000D_ _x000D_ /**_x000D_ * See IM-147 Documentatie release ondersteunen._x000D_ * _x000D_ * This method compares the current XML file to any other XML file. Results are written to a listing XML file._x000D_ * _x000D_ * This XML file is the control XML file, and is compared to test XML file._x000D_ * _x000D_ * @return_x000D_ * @throws Exception_x000D_ */_x000D_ public boolean compare(XmlFile testXmlFile, Configurator configurator) throws Exception {_x000D_ _x000D_ String compareLabel = configurator.getParm("system", "compare-label");_x000D_ _x000D_ // create a transformer_x000D_ Transformer transformer = new Transformer();_x000D_ transformer.setExtensionFunction(new ImvertorCompareXML());_x000D_ _x000D_ Boolean valid = true;_x000D_ _x000D_ //TODO Duplicate, redundant?_x000D_ XmlFile ctrlNameFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_NAME_FILE")); // imvertor.20.docrelease.1.1.compare-control-name.xml_x000D_ XmlFile testNameFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_NAME_FILE")); // imvertor.20.docrelease.1.2.compare-test-name.xml_x000D_ XmlFile infoConfig = new XmlFile(configurator.getParm("properties","IMVERTOR_COMPARE_CONFIG")); // Imvert-compare-config.xml_x000D_ _x000D_ // This transformer will pass regular XML parameters to the stylesheet. _x000D_ // This is because the compare core code is not part of the Imvertor framework, but developed separately._x000D_ // We therefore do not use the XMLConfiguration approach here._x000D_ transformer.setXslParm("identify-construct-by-function", "name"); // the name of the construct is the only identifier_x000D_ //TODO name of id??_x000D_ _x000D_ transformer.setXslParm("info-config", infoConfig.toURI().toString()); _x000D_ transformer.setXslParm("info-ctrlpath", this.getCanonicalPath()); _x000D_ transformer.setXslParm("info-testpath", "(test path)"); _x000D_ _x000D_ transformer.setXslParm("compare-label", compareLabel);_x000D_ _x000D_ // determine temporary files_x000D_ XmlFile controlModelFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_MODEL_FILE")); // imvertor.20.docrelease.1.1.compare-control-model.xml_x000D_ XmlFile testModelFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_MODEL_FILE")); // imvertor.20.docrelease.1.2.compare-test-model.xml_x000D_ XmlFile controlSimpleFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_SIMPLE_FILE")); // imvertor.20.docrelease.1.1.compare-control-simple.xml_x000D_ XmlFile testSimpleFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_SIMPLE_FILE")); // imvertor.20.docrelease.1.2.compare-test-simple.xml_x000D_ _x000D_ XmlFile diffXml = new XmlFile(configurator.getParm("properties","WORK_COMPARE_DIFF_FILE")); // imvertor.20.docrelease.2.compare-diff.xml_x000D_ XmlFile listingXml = new XmlFile(configurator.getParm("properties","WORK_COMPARE_LISTING_FILE")); // imvertor.20.docrelease.3.compare-listing.xml_x000D_ _x000D_ XslFile tempXsl = new XslFile(configurator.getParm("properties","COMPARE_GENERATED_XSLPATH"));_x000D_ _x000D_ //clean _x000D_ XslFile cleanerXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_CLEAN_XSLPATH"));_x000D_ XslFile simpleXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_SIMPLE_XSLPATH"));_x000D_ _x000D_ valid = valid && transformer.transform(this,controlModelFile,cleanerXsl);_x000D_ valid = valid && transformer.transform(testXmlFile,testModelFile,cleanerXsl);_x000D_ _x000D_ // simplify_x000D_ transformer.setXslParm("ctrl-name-mapping-filepath", ctrlNameFile.toURI().toString()); // file:/D:/.../Imvertor-OS-work/imvert/imvertor.20.compare-control-name.xml_x000D_ transformer.setXslParm("test-name-mapping-filepath", testNameFile.toURI().toString());_x000D_ _x000D_ transformer.setXslParm("comparison-role", "ctrl");_x000D_ valid = valid && transformer.transform(controlModelFile,controlSimpleFile,simpleXsl);_x000D_ transformer.setXslParm("comparison-role", "test");_x000D_ valid = valid && transformer.transform(testModelFile,testSimpleFile,simpleXsl);_x000D_ _x000D_ // compare _x000D_ XslFile compareXsl = new XslFile(configurator.getParm("properties","COMPARE_GENERATOR_XSLPATH"));_x000D_ _x000D_ transformer.setXslParm("ctrl-filepath", controlSimpleFile.getCanonicalPath());_x000D_ transformer.setXslParm("test-filepath", testSimpleFile.getCanonicalPath());_x000D_ transformer.setXslParm("diff-filepath", diffXml.getCanonicalPath());_x000D_ _x000D_ valid = valid && transformer.transform(controlSimpleFile, tempXsl, compareXsl);_x000D_ _x000D_ // create listing_x000D_ XslFile listingXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_LISTING_XSLPATH"));_x000D_ valid = valid && transformer.transform(controlSimpleFile,listingXml,listingXsl);_x000D_ _x000D_ // get the number of differences found_x000D_ int differences = ((NodeList) listingXml.xpathToObject("/*/*",null,XPathConstants.NODESET)).getLength();_x000D_ configurator.setParm("appinfo", "compare-differences-" + compareLabel, differences);_x000D_ _x000D_ // Build report_x000D_ boolean result = valid && (differences == 0);_x000D_ _x000D_ return result;_x000D_ }_x000D_ }_x000D_
Imvertor/Imvertor
src/nl/imvertor/common/file/XmlFile.java
5,997
/**_x000D_ * Benader de inhoud dmv. een Xpath expressie. Geef het laatste item die aan het criterium voldoet af als String._x000D_ * _x000D_ * @param outfile_x000D_ * @param xslFilePath_x000D_ * @throws Exception_x000D_ */
block_comment
nl
/*_x000D_ * Copyright (C) 2016 Dienst voor het kadaster en de openbare registers_x000D_ * _x000D_ * This file is part of Imvertor._x000D_ *_x000D_ * Imvertor is free software: you can redistribute it and/or modify_x000D_ * it under the terms of the GNU General Public License as published by_x000D_ * the Free Software Foundation, either version 3 of the License, or_x000D_ * (at your option) any later version._x000D_ *_x000D_ * Imvertor is distributed in the hope that it will be useful,_x000D_ * but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_ * GNU General Public License for more details._x000D_ *_x000D_ * You should have received a copy of the GNU General Public License_x000D_ * along with Imvertor. If not, see <http://www.gnu.org/licenses/>._x000D_ *_x000D_ */_x000D_ _x000D_ package nl.imvertor.common.file;_x000D_ _x000D_ import java.io.File;_x000D_ import java.io.FileOutputStream;_x000D_ import java.util.HashMap;_x000D_ import java.util.Iterator;_x000D_ import java.util.List;_x000D_ import java.util.Vector;_x000D_ _x000D_ import javax.xml.namespace.QName;_x000D_ import javax.xml.parsers.DocumentBuilder;_x000D_ import javax.xml.parsers.DocumentBuilderFactory;_x000D_ import javax.xml.xpath.XPath;_x000D_ import javax.xml.xpath.XPathConstants;_x000D_ import javax.xml.xpath.XPathExpression;_x000D_ _x000D_ import org.apache.commons.lang3.StringUtils;_x000D_ import org.apache.log4j.Logger;_x000D_ import org.custommonkey.xmlunit.DetailedDiff;_x000D_ import org.custommonkey.xmlunit.Difference;_x000D_ import org.custommonkey.xmlunit.XMLTestCase;_x000D_ import org.custommonkey.xmlunit.XMLUnit;_x000D_ import org.w3c.dom.Document;_x000D_ import org.w3c.dom.NodeList;_x000D_ import org.w3c.dom.bootstrap.DOMImplementationRegistry;_x000D_ import org.w3c.dom.ls.DOMImplementationLS;_x000D_ import org.w3c.dom.ls.LSOutput;_x000D_ import org.w3c.dom.ls.LSSerializer;_x000D_ import org.xml.sax.ErrorHandler;_x000D_ import org.xml.sax.InputSource;_x000D_ import org.xml.sax.SAXException;_x000D_ import org.xml.sax.SAXParseException;_x000D_ _x000D_ import net.sf.saxon.xpath.XPathFactoryImpl;_x000D_ import nl.imvertor.common.Configurator;_x000D_ import nl.imvertor.common.Transformer;_x000D_ import nl.imvertor.common.xsl.extensions.ImvertorCompareXML;_x000D_ _x000D_ /**_x000D_ * An XmlFile represents an XmlFile on the file system._x000D_ * _x000D_ * The XmlFile is an AnyFile and therefore does not access the chain environment._x000D_ * _x000D_ * @author arjan_x000D_ *_x000D_ */_x000D_ public class XmlFile extends AnyFile implements ErrorHandler {_x000D_ _x000D_ private static final long serialVersionUID = -4351737187940152153L;_x000D_ _x000D_ protected static final Logger logger = Logger.getLogger(XmlFile.class);_x000D_ _x000D_ static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";_x000D_ static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";_x000D_ _x000D_ protected static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";_x000D_ protected static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";_x000D_ protected static final String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";_x000D_ protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";_x000D_ protected static final String EXTERNAL_PARAMETER_ENTITIES_ID = "http://xml.org/sax/features/external-parameter-entities";_x000D_ protected static final String EXTERNAL_GENERAL_ENTITIES_ID = "http://xml.org/sax/features/external-general-entities";_x000D_ protected static final String IGNORE_DTD_FEATURE_ID = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; // http://www.isocra.com/2006/05/making-xerces-ignore-a-dtd/_x000D_ _x000D_ protected static final String LEXICAL_HANDLER_PROPERTY_ID = "http://xml.org/sax/properties/lexical-handler";_x000D_ protected static final String DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser";_x000D_ _x000D_ protected static final int WFCODE_OKAY = 0;_x000D_ protected static final int WFCODE_WARNING = 1;_x000D_ protected static final int WFCODE_ERROR = 2;_x000D_ protected static final int WFCODE_FATAL = 3;_x000D_ _x000D_ // parameters die de verwerking van het XML file bepalen_x000D_ _x000D_ public boolean namespace = true; // namespace aware?_x000D_ public boolean validate = false; // valideren?_x000D_ public boolean xinclude = true; // herken xinclude statements?_x000D_ public boolean schema = false; // zoek naar schema bij valideren?_x000D_ public boolean schemacheck = false; // schema ook checken?_x000D_ public boolean dtd = false; // zoek naar dtd bij valideren?_x000D_ public boolean auto = false; // automagically determine how to parse this file?_x000D_ public boolean external = false; // externe entiteiten ophalen?_x000D_ public boolean inquiry = false; // zoek alleen maar naar informatie over dit file?_x000D_ _x000D_ private Document dom = null;_x000D_ _x000D_ private int wfcode = WFCODE_OKAY; // a code indicating the Wellformedness of the XML file._x000D_ _x000D_ private Vector<String> messages = new Vector<String>();_x000D_ _x000D_ public static void main(String[] args) {_x000D_ _x000D_ //XmlFile file = new XmlFile("D:\\projects\\arjan\\Java development\\CommonHandlers\\sandbox\\EHcache\\config\\ehcache.xml");_x000D_ XmlFile file = new XmlFile("D:\\projects\\validprojects\\Kadaster-Imvertor\\Imvertor-OS-work\\default\\comply\\template\\xl\\worksheets\\sheet1.xml");_x000D_ System.out.println(file.isValid());_x000D_ file.getMessages();_x000D_ _x000D_ }_x000D_ _x000D_ public XmlFile(String pathname) {_x000D_ super(pathname);_x000D_ }_x000D_ public XmlFile(File file) {_x000D_ super(file.getAbsolutePath());_x000D_ }_x000D_ public XmlFile(File folder, String filename) {_x000D_ super(folder,filename);_x000D_ }_x000D_ _x000D_ public String getFileType() {_x000D_ return "XML";_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Lees een file in naar een DOM Document._x000D_ * _x000D_ * @param file_x000D_ * @return_x000D_ * @throws Exception_x000D_ */_x000D_ public Document toDocument() throws Exception {_x000D_ Document d = buildDom();_x000D_ return d;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zet een Document weg als file. Transformeer middels het XSLT file. Als_x000D_ * XSLT file is "", identity transform._x000D_ * _x000D_ * @param doc_x000D_ * @param xsltfile_x000D_ * @param parms_x000D_ * @throws Exception_x000D_ */_x000D_ public void fromDocument(Document doc) throws Exception {_x000D_ DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); _x000D_ DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("XML 3.0 LS 3.0");_x000D_ if (impl == null) {_x000D_ System.out.println("No DOMImplementation found !");_x000D_ System.exit(0);_x000D_ }_x000D_ LSSerializer serializer = impl.createLSSerializer();_x000D_ LSOutput output = impl.createLSOutput();_x000D_ output.setEncoding("UTF-8");_x000D_ output.setByteStream(new FileOutputStream(this));_x000D_ serializer.write(doc, output);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Build a DOM Document representation of this XML file. _x000D_ * _x000D_ * @return_x000D_ * @throws Exception_x000D_ */_x000D_ private Document buildDom() throws Exception {_x000D_ return this.buildDom(this);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Build a DOM Document representation of some external XML file. _x000D_ * _x000D_ * @return_x000D_ * @throws Exception_x000D_ */_x000D_ private Document buildDom(File file) throws Exception {_x000D_ _x000D_ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();_x000D_ InputSource in = new InputSource(file.getAbsolutePath());_x000D_ _x000D_ docFactory.setValidating(validate);_x000D_ docFactory.setXIncludeAware(xinclude);_x000D_ docFactory.setFeature(VALIDATION_FEATURE_ID, validate);_x000D_ docFactory.setFeature(NAMESPACES_FEATURE_ID, namespace);_x000D_ docFactory.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schema);_x000D_ docFactory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemacheck);_x000D_ docFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_ID, external);_x000D_ docFactory.setFeature(EXTERNAL_PARAMETER_ENTITIES_ID, external);_x000D_ _x000D_ DocumentBuilder db = docFactory.newDocumentBuilder();_x000D_ return db.parse(in);_x000D_ }_x000D_ _x000D_ public Document getDom() throws Exception {_x000D_ if (dom == null) _x000D_ return buildDom(this);_x000D_ else _x000D_ return dom;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Benader de inhoud<SUF>*/_x000D_ public String xpath(String expression, HashMap<String, String> parms) throws Exception {_x000D_ return (String) xpathToObject(expression, parms, XPathConstants.STRING);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Benader de inhoud dmv. een Xpath expressie. _x000D_ * _x000D_ * @param outfile_x000D_ * @param xslFilePath_x000D_ * @throws Exception_x000D_ */_x000D_ public Object xpathToObject(String expression, HashMap<String, String> parms, QName returnType) throws Exception {_x000D_ if (dom == null) dom = this.buildDom();_x000D_ XPathFactoryImpl xpf = new XPathFactoryImpl();_x000D_ XPath xpe = xpf.newXPath();_x000D_ XPathExpression find = xpe.compile(expression);_x000D_ return find.evaluate(dom, returnType);_x000D_ }_x000D_ _x000D_ public String xpath(String expression) throws Exception {_x000D_ return xpath(expression,new HashMap<String,String>());_x000D_ }_x000D_ _x000D_ /** _x000D_ * Transform the XML file to a canonical form_x000D_ * _x000D_ * @param outfile_x000D_ * @param xslFile_x000D_ * @param parms_x000D_ * @throws Exception_x000D_ */_x000D_ public void fileToCanonicalFile(XmlFile outfile) throws Exception {_x000D_ logger.debug("Canonizing " + this.getCanonicalPath());_x000D_ if (dom == null) dom = this.buildDom();_x000D_ outfile.fromDocument(dom);_x000D_ }_x000D_ _x000D_ public boolean isWellFormed() {_x000D_ messages.removeAllElements();_x000D_ try {_x000D_ wfcode = WFCODE_OKAY;_x000D_ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();_x000D_ factory.setValidating(false);_x000D_ factory.setNamespaceAware(true);_x000D_ factory.setXIncludeAware(true);_x000D_ _x000D_ DocumentBuilder builder = factory.newDocumentBuilder();_x000D_ _x000D_ builder.setErrorHandler(this); _x000D_ builder.parse(new InputSource(this.getCanonicalPath()));_x000D_ _x000D_ } catch (Exception e) {_x000D_ wfcode = WFCODE_FATAL;_x000D_ }_x000D_ return wfcode < WFCODE_ERROR;_x000D_ }_x000D_ _x000D_ public boolean isValid() {_x000D_ messages.removeAllElements();_x000D_ try {_x000D_ wfcode = WFCODE_OKAY;_x000D_ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();_x000D_ factory.setValidating(true);_x000D_ factory.setNamespaceAware(true);_x000D_ factory.setXIncludeAware(true);_x000D_ factory.setAttribute(_x000D_ "http://java.sun.com/xml/jaxp/properties/schemaLanguage",_x000D_ "http://www.w3.org/2001/XMLSchema");_x000D_ _x000D_ DocumentBuilder builder = factory.newDocumentBuilder();_x000D_ _x000D_ builder.setErrorHandler(this); _x000D_ builder.parse(new InputSource(this.getCanonicalPath()));_x000D_ } catch (Exception e) {_x000D_ wfcode = WFCODE_FATAL;_x000D_ }_x000D_ return wfcode < WFCODE_ERROR;_x000D_ }_x000D_ _x000D_ public Vector<String> getMessages() {_x000D_ return messages;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Compare this control file to the passed test file, store result in file. Return true if files are the same._x000D_ * _x000D_ * Difference types are listed as constants in _x000D_ * <a href="http://xmlunit.sourceforge.net/api/org/custommonkey/xmlunit/DifferenceConstants.html">here</a>_x000D_ * _x000D_ * @param controlXmlPath_x000D_ * @param testXmlPath_x000D_ * @param resultPath_x000D_ * @return_x000D_ * @throws Exception_x000D_ */_x000D_ public boolean xmlUnitCompareXML(XmlFile testXmlFile, XmlFile resultFile) throws Exception {_x000D_ XmlFile controlXmlFile = this;_x000D_ _x000D_ XMLUnit.setCompareUnmatched(false);_x000D_ XMLTestCase testcase = new Case(this.getName());_x000D_ _x000D_ DetailedDiff myDiff = new DetailedDiff(testcase.compareXML(controlXmlFile.getContent(), testXmlFile.getContent()));_x000D_ _x000D_ @SuppressWarnings("unchecked")_x000D_ List<Difference> allDifferences = myDiff.getAllDifferences();_x000D_ Iterator<Difference> it = allDifferences.iterator();_x000D_ String analysis = "<diffs>";_x000D_ while (it.hasNext()) {_x000D_ Difference d = it.next();_x000D_ analysis += "<diff"_x000D_ + " desc=\"" + safe(d.getDescription()) + "\""_x000D_ + ">";_x000D_ analysis += "<ctrl"_x000D_ + " path=\"" + d.getControlNodeDetail().getXpathLocation() + "\""_x000D_ + " value=\"" + safe(d.getControlNodeDetail().getValue()) + "\""_x000D_ + "/>";_x000D_ analysis += "<test"_x000D_ + " path=\"" + d.getTestNodeDetail().getXpathLocation() + "\""_x000D_ + " value=\"" + safe(d.getTestNodeDetail().getValue()) + "\""_x000D_ + "/>";_x000D_ analysis += "</diff>";_x000D_ }_x000D_ analysis += "</diffs>";_x000D_ resultFile.setContent(analysis);_x000D_ return (allDifferences.size() == 0) ? true: false;_x000D_ }_x000D_ _x000D_ /** _x000D_ * Replace special characters in XML string._x000D_ * _x000D_ * @param s_x000D_ * @return_x000D_ */_x000D_ private String safe(String s) {_x000D_ s = StringUtils.replace(s,"&","&amp;");_x000D_ s = StringUtils.replace(s,"<","&lt;");_x000D_ s = StringUtils.replace(s,">","&gt;");_x000D_ s = StringUtils.replace(s,"\"","&quot;");_x000D_ return s;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Introduce the XmlFile class as a valid JUnit TestCase class._x000D_ * _x000D_ * @author arjan_x000D_ *_x000D_ */_x000D_ private class Case extends XMLTestCase {_x000D_ _x000D_ public Case(String name) {_x000D_ super(name);_x000D_ }_x000D_ _x000D_ } _x000D_ _x000D_ @Override_x000D_ public void error(SAXParseException exception) throws SAXException {_x000D_ messages.add(exception.getMessage());_x000D_ wfcode = WFCODE_ERROR;_x000D_ }_x000D_ @Override_x000D_ public void fatalError(SAXParseException exception) throws SAXException {_x000D_ messages.add(exception.getMessage());_x000D_ wfcode = WFCODE_FATAL;_x000D_ }_x000D_ @Override_x000D_ public void warning(SAXParseException exception) throws SAXException {_x000D_ messages.add(exception.getMessage());_x000D_ wfcode = WFCODE_WARNING;_x000D_ }_x000D_ _x000D_ public static String xmlescape(String s) {_x000D_ s = s.replace("&", "&amp;");_x000D_ s = s.replace("<", "&lt;");_x000D_ return s;_x000D_ }_x000D_ _x000D_ /**_x000D_ * See IM-147 Documentatie release ondersteunen._x000D_ * _x000D_ * This method compares the current XML file to any other XML file. Results are written to a listing XML file._x000D_ * _x000D_ * This XML file is the control XML file, and is compared to test XML file._x000D_ * _x000D_ * @return_x000D_ * @throws Exception_x000D_ */_x000D_ public boolean compare(XmlFile testXmlFile, Configurator configurator) throws Exception {_x000D_ _x000D_ String compareLabel = configurator.getParm("system", "compare-label");_x000D_ _x000D_ // create a transformer_x000D_ Transformer transformer = new Transformer();_x000D_ transformer.setExtensionFunction(new ImvertorCompareXML());_x000D_ _x000D_ Boolean valid = true;_x000D_ _x000D_ //TODO Duplicate, redundant?_x000D_ XmlFile ctrlNameFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_NAME_FILE")); // imvertor.20.docrelease.1.1.compare-control-name.xml_x000D_ XmlFile testNameFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_NAME_FILE")); // imvertor.20.docrelease.1.2.compare-test-name.xml_x000D_ XmlFile infoConfig = new XmlFile(configurator.getParm("properties","IMVERTOR_COMPARE_CONFIG")); // Imvert-compare-config.xml_x000D_ _x000D_ // This transformer will pass regular XML parameters to the stylesheet. _x000D_ // This is because the compare core code is not part of the Imvertor framework, but developed separately._x000D_ // We therefore do not use the XMLConfiguration approach here._x000D_ transformer.setXslParm("identify-construct-by-function", "name"); // the name of the construct is the only identifier_x000D_ //TODO name of id??_x000D_ _x000D_ transformer.setXslParm("info-config", infoConfig.toURI().toString()); _x000D_ transformer.setXslParm("info-ctrlpath", this.getCanonicalPath()); _x000D_ transformer.setXslParm("info-testpath", "(test path)"); _x000D_ _x000D_ transformer.setXslParm("compare-label", compareLabel);_x000D_ _x000D_ // determine temporary files_x000D_ XmlFile controlModelFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_MODEL_FILE")); // imvertor.20.docrelease.1.1.compare-control-model.xml_x000D_ XmlFile testModelFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_MODEL_FILE")); // imvertor.20.docrelease.1.2.compare-test-model.xml_x000D_ XmlFile controlSimpleFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_CONTROL_SIMPLE_FILE")); // imvertor.20.docrelease.1.1.compare-control-simple.xml_x000D_ XmlFile testSimpleFile = new XmlFile(configurator.getParm("properties","WORK_COMPARE_TEST_SIMPLE_FILE")); // imvertor.20.docrelease.1.2.compare-test-simple.xml_x000D_ _x000D_ XmlFile diffXml = new XmlFile(configurator.getParm("properties","WORK_COMPARE_DIFF_FILE")); // imvertor.20.docrelease.2.compare-diff.xml_x000D_ XmlFile listingXml = new XmlFile(configurator.getParm("properties","WORK_COMPARE_LISTING_FILE")); // imvertor.20.docrelease.3.compare-listing.xml_x000D_ _x000D_ XslFile tempXsl = new XslFile(configurator.getParm("properties","COMPARE_GENERATED_XSLPATH"));_x000D_ _x000D_ //clean _x000D_ XslFile cleanerXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_CLEAN_XSLPATH"));_x000D_ XslFile simpleXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_SIMPLE_XSLPATH"));_x000D_ _x000D_ valid = valid && transformer.transform(this,controlModelFile,cleanerXsl);_x000D_ valid = valid && transformer.transform(testXmlFile,testModelFile,cleanerXsl);_x000D_ _x000D_ // simplify_x000D_ transformer.setXslParm("ctrl-name-mapping-filepath", ctrlNameFile.toURI().toString()); // file:/D:/.../Imvertor-OS-work/imvert/imvertor.20.compare-control-name.xml_x000D_ transformer.setXslParm("test-name-mapping-filepath", testNameFile.toURI().toString());_x000D_ _x000D_ transformer.setXslParm("comparison-role", "ctrl");_x000D_ valid = valid && transformer.transform(controlModelFile,controlSimpleFile,simpleXsl);_x000D_ transformer.setXslParm("comparison-role", "test");_x000D_ valid = valid && transformer.transform(testModelFile,testSimpleFile,simpleXsl);_x000D_ _x000D_ // compare _x000D_ XslFile compareXsl = new XslFile(configurator.getParm("properties","COMPARE_GENERATOR_XSLPATH"));_x000D_ _x000D_ transformer.setXslParm("ctrl-filepath", controlSimpleFile.getCanonicalPath());_x000D_ transformer.setXslParm("test-filepath", testSimpleFile.getCanonicalPath());_x000D_ transformer.setXslParm("diff-filepath", diffXml.getCanonicalPath());_x000D_ _x000D_ valid = valid && transformer.transform(controlSimpleFile, tempXsl, compareXsl);_x000D_ _x000D_ // create listing_x000D_ XslFile listingXsl = new XslFile(configurator.getParm("properties","IMVERTOR_COMPARE_LISTING_XSLPATH"));_x000D_ valid = valid && transformer.transform(controlSimpleFile,listingXml,listingXsl);_x000D_ _x000D_ // get the number of differences found_x000D_ int differences = ((NodeList) listingXml.xpathToObject("/*/*",null,XPathConstants.NODESET)).getLength();_x000D_ configurator.setParm("appinfo", "compare-differences-" + compareLabel, differences);_x000D_ _x000D_ // Build report_x000D_ boolean result = valid && (differences == 0);_x000D_ _x000D_ return result;_x000D_ }_x000D_ }_x000D_
True
False
1,540
3,273
13783_18
package company.taskMan; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Optional; import company.BranchView; import company.taskMan.project.TaskView; import company.taskMan.task.DelegatingTask; import company.taskMan.task.DelegatingTaskProxy; import company.taskMan.task.OriginalTaskProxy; import company.taskMan.task.Task; /** * The Branch Representative is responsible for communication between branches. * When a branch tries to do something that would impact the consistency of * another branch, their representatives will negotiate the terms and * synchronize the necessary information. * * @author Tim Van Den Broecke, Joran Van de Woestijne, Vincent Van Gestel and * Eli Vangrieken * */ public class BranchRepresentative { private Map<Task,DelegatingTaskProxy> delegationProxies; private Map<Task,OriginalTaskProxy> originalProxies; private LinkedList<DelegationData> buffer; private boolean bufferMode; public BranchRepresentative() { delegationProxies = new HashMap<>(); originalProxies = new HashMap<>(); buffer = new LinkedList<DelegationData>(); bufferMode = false; } /** * Schedules a delegation for task to the branch toBranch. FromBranch * must be this representative's own branch. * If the delegation happens to its own branch, the task will end in * the Unavailable state. * If the representative is in buffer mode, the delegation will be * scheduled for later execution. If it isn't in buffer mode, the * delegation will be executed immediately. * A delegation typically happens in three steps: * 1) A local DelegatingTaskProxy is made and the task-to-delegate * is informed that it is being delegated * Note: If the delegation is to its own branch, the task * will be informed that it is no longer being delegated * 2) The remote branch creates a Delegating Task and links it to * a local OriginalTaskProxy * 3) The two proxies are linked to each other * @param task the task to be delegated * @param fromBranch the branch from where the task is delegated * @param toBranch the branch where the task is delegated to * @throws IllegalArgumentException * | If null arguments are supplied */ public void delegateTask(Task task, Branch fromBranch, Branch toBranch) throws IllegalArgumentException { if(task == null || fromBranch == null || toBranch == null) { throw new IllegalArgumentException("Parameters cannot be null"); } // Delegation came back to the original branch if (toBranch == fromBranch) { delegationProxies.remove(task); task.delegate(false); } else { // Add new delegation to buffer buffer.add(new DelegationData(task, fromBranch, toBranch)); if (!bufferMode) { executeBuffer(); } } } /** * Accepts the delegation of a task from the branch delegatingBranch. It will * use newTask as a delegator that has delProxy as a remote proxy (in the * original branch). It will create a local Original Task Proxy that is linked * with delProxy so that communication is synchronized and ready for use. * @param delProxy the delegatingTaskProxy for the original task * @param newTask the task that is actually delegating for the original task * @param delegatingBranch the branch that is delegating the original task * @throws IllegalArgumentException * | If the supplied parameters are null */ public void delegateAccept(DelegatingTaskProxy delProxy, DelegatingTask newTask, Branch delegatingBranch) throws IllegalArgumentException { if(delProxy == null || newTask == null || delegatingBranch == null) { throw new IllegalArgumentException("Parameters cannot be null"); } OriginalTaskProxy origiProxy = new OriginalTaskProxy(newTask, delegatingBranch); delProxy.link(origiProxy); // origiProxy.link(delProxy); originalProxies.put(newTask, origiProxy); } /** * Executes the delegations that were scheduled for executuion in the buffer. * 1) If a delegating task is being delegated, this method will release the delegation * form this branch and give the delegation to the branch of the original task. That * branch will then schedule the delegation that will result in case 2) * 2) If an already-delegated task is being delegated, this method will reset the * Task to a non-delegated state and its delegatingTaskProxy is removed. The * delegation is then rescheduled and will result in case 3) * 3) If A task hasn't been delegated before, this method will create a new delegatingTaskProxy * for the task and tell the toBranch to accept the delegation. * */ private void executeBuffer(){ // For every delegation ready in the buffer while (!buffer.isEmpty()) { DelegationData deleg = buffer.poll(); // Next delegation to commit (a TO request) Task task = deleg.delegatedTask; // Task to delegate Branch fromBranch = deleg.originalBranch; // Branch to delegate FROM Branch toBranch = deleg.newBranch; // Branch to delegate TO if (originalProxies.containsKey(task)) { // A. this task is already delegating another task OriginalTaskProxy origiProxy = originalProxies.get(task); Branch origiFromBranch = origiProxy.getOriginalBranch().get(); // A.1 Remove previous delegation information originalProxies.remove(task); fromBranch.removeDelegatedTask(task); // A.2 (re-)delegate the original task in its respective delegator origiFromBranch.delegateTask(origiProxy.getOriginalTask(), toBranch); } else if(delegationProxies.containsKey(task)) { // B. The original task is being re-delegated: remove its previous delegation and schedule a new one DelegatingTaskProxy delProxy = delegationProxies.get(task); Task origiTask = delProxy.getTask(); origiTask.delegate(false); delegationProxies.remove(task); buffer.add(new DelegationData(task, fromBranch, toBranch)); } else { // C. The task is delegated for the first time DelegatingTaskProxy delProxy = new DelegatingTaskProxy(task, fromBranch); toBranch.delegateAccept(delProxy); delegationProxies.put(task, delProxy); task.delegate(true); } } } /** * Sets the buffer mode of this representative. If set to false, it will * execute its scheduled delegations. * @param active whether the buffer should be set to active (true) or inactive (false) */ public void setBufferMode(boolean active) { bufferMode = active; if(!bufferMode) { executeBuffer(); } } /** * Returns the BranchView of the Branch that is repsonsible for task, * IF it is being delegated * @param task the task of which to get the responsible branch * @return * | BranchView of the task's responsible branch * | empty Optional otherwise */ public Optional<BranchView> getResponsibleBranch(Task task) { Optional<DelegatingTaskProxy> delProxy = Optional.ofNullable(delegationProxies.get(task)); if(delProxy.isPresent()) { if(delProxy.get().getDelegatingBranch().isPresent()) { return Optional.of(new BranchView(delProxy.get().getDelegatingBranch().get())); } else { return Optional.empty(); } } else { //kijk eens in de buffer Iterator<DelegationData> i = buffer.iterator(); DelegationData d; while(i.hasNext()) { d = i.next(); if(d.delegatedTask == task) { return Optional.of(new BranchView(d.newBranch)); } } return Optional.empty(); } } /** * Returns the TaskView of the Task that is delegating task, * IF it is being delegated * @param t the task of which to get the delegating task * @return * | BranchView of the task's responsible branch * | empty Optional otherwise */ public Optional<TaskView> getDelegatingTask(Task t) { Optional<DelegatingTaskProxy> delProxy = Optional.ofNullable(delegationProxies.get(t)); if(delProxy.isPresent()) { return Optional.of(new TaskView(delProxy.get().getDelegatingTask())); } else { return Optional.empty(); } } private class DelegationData { private Task delegatedTask; private Branch originalBranch, newBranch; private DelegationData(Task task,Branch origBranch, Branch newBranch){ delegatedTask = task; originalBranch = origBranch; this.newBranch = newBranch; } } /** * @return the current Task-Proxy pairings (original) */ protected Map<Task, OriginalTaskProxy> getOriginalProxies() { return originalProxies; } /** * @return the current Task-Proxy pairings (delegating) */ protected Map<Task, DelegatingTaskProxy> getDelegatingProxies() { return delegationProxies; } /** * A method to allow the Branch to offer new task and (original) proxy * pairings to the representative * * @param proxies * | The new task-proxy pairings present in the system */ protected void offerOriginalTaskProxies(Map<Task, OriginalTaskProxy> proxies) { originalProxies = proxies; } /** * A method to allow the Branch to offer new task and (delegating) proxy * pairings to the representative * * @param proxies * | The new task-proxy pairings present in the system */ protected void offerDelegatingTaskProxies( Map<Task, DelegatingTaskProxy> proxies) { delegationProxies = proxies; } }
jorreee/SWOP
src/company/taskMan/BranchRepresentative.java
2,833
//kijk eens in de buffer
line_comment
nl
package company.taskMan; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Optional; import company.BranchView; import company.taskMan.project.TaskView; import company.taskMan.task.DelegatingTask; import company.taskMan.task.DelegatingTaskProxy; import company.taskMan.task.OriginalTaskProxy; import company.taskMan.task.Task; /** * The Branch Representative is responsible for communication between branches. * When a branch tries to do something that would impact the consistency of * another branch, their representatives will negotiate the terms and * synchronize the necessary information. * * @author Tim Van Den Broecke, Joran Van de Woestijne, Vincent Van Gestel and * Eli Vangrieken * */ public class BranchRepresentative { private Map<Task,DelegatingTaskProxy> delegationProxies; private Map<Task,OriginalTaskProxy> originalProxies; private LinkedList<DelegationData> buffer; private boolean bufferMode; public BranchRepresentative() { delegationProxies = new HashMap<>(); originalProxies = new HashMap<>(); buffer = new LinkedList<DelegationData>(); bufferMode = false; } /** * Schedules a delegation for task to the branch toBranch. FromBranch * must be this representative's own branch. * If the delegation happens to its own branch, the task will end in * the Unavailable state. * If the representative is in buffer mode, the delegation will be * scheduled for later execution. If it isn't in buffer mode, the * delegation will be executed immediately. * A delegation typically happens in three steps: * 1) A local DelegatingTaskProxy is made and the task-to-delegate * is informed that it is being delegated * Note: If the delegation is to its own branch, the task * will be informed that it is no longer being delegated * 2) The remote branch creates a Delegating Task and links it to * a local OriginalTaskProxy * 3) The two proxies are linked to each other * @param task the task to be delegated * @param fromBranch the branch from where the task is delegated * @param toBranch the branch where the task is delegated to * @throws IllegalArgumentException * | If null arguments are supplied */ public void delegateTask(Task task, Branch fromBranch, Branch toBranch) throws IllegalArgumentException { if(task == null || fromBranch == null || toBranch == null) { throw new IllegalArgumentException("Parameters cannot be null"); } // Delegation came back to the original branch if (toBranch == fromBranch) { delegationProxies.remove(task); task.delegate(false); } else { // Add new delegation to buffer buffer.add(new DelegationData(task, fromBranch, toBranch)); if (!bufferMode) { executeBuffer(); } } } /** * Accepts the delegation of a task from the branch delegatingBranch. It will * use newTask as a delegator that has delProxy as a remote proxy (in the * original branch). It will create a local Original Task Proxy that is linked * with delProxy so that communication is synchronized and ready for use. * @param delProxy the delegatingTaskProxy for the original task * @param newTask the task that is actually delegating for the original task * @param delegatingBranch the branch that is delegating the original task * @throws IllegalArgumentException * | If the supplied parameters are null */ public void delegateAccept(DelegatingTaskProxy delProxy, DelegatingTask newTask, Branch delegatingBranch) throws IllegalArgumentException { if(delProxy == null || newTask == null || delegatingBranch == null) { throw new IllegalArgumentException("Parameters cannot be null"); } OriginalTaskProxy origiProxy = new OriginalTaskProxy(newTask, delegatingBranch); delProxy.link(origiProxy); // origiProxy.link(delProxy); originalProxies.put(newTask, origiProxy); } /** * Executes the delegations that were scheduled for executuion in the buffer. * 1) If a delegating task is being delegated, this method will release the delegation * form this branch and give the delegation to the branch of the original task. That * branch will then schedule the delegation that will result in case 2) * 2) If an already-delegated task is being delegated, this method will reset the * Task to a non-delegated state and its delegatingTaskProxy is removed. The * delegation is then rescheduled and will result in case 3) * 3) If A task hasn't been delegated before, this method will create a new delegatingTaskProxy * for the task and tell the toBranch to accept the delegation. * */ private void executeBuffer(){ // For every delegation ready in the buffer while (!buffer.isEmpty()) { DelegationData deleg = buffer.poll(); // Next delegation to commit (a TO request) Task task = deleg.delegatedTask; // Task to delegate Branch fromBranch = deleg.originalBranch; // Branch to delegate FROM Branch toBranch = deleg.newBranch; // Branch to delegate TO if (originalProxies.containsKey(task)) { // A. this task is already delegating another task OriginalTaskProxy origiProxy = originalProxies.get(task); Branch origiFromBranch = origiProxy.getOriginalBranch().get(); // A.1 Remove previous delegation information originalProxies.remove(task); fromBranch.removeDelegatedTask(task); // A.2 (re-)delegate the original task in its respective delegator origiFromBranch.delegateTask(origiProxy.getOriginalTask(), toBranch); } else if(delegationProxies.containsKey(task)) { // B. The original task is being re-delegated: remove its previous delegation and schedule a new one DelegatingTaskProxy delProxy = delegationProxies.get(task); Task origiTask = delProxy.getTask(); origiTask.delegate(false); delegationProxies.remove(task); buffer.add(new DelegationData(task, fromBranch, toBranch)); } else { // C. The task is delegated for the first time DelegatingTaskProxy delProxy = new DelegatingTaskProxy(task, fromBranch); toBranch.delegateAccept(delProxy); delegationProxies.put(task, delProxy); task.delegate(true); } } } /** * Sets the buffer mode of this representative. If set to false, it will * execute its scheduled delegations. * @param active whether the buffer should be set to active (true) or inactive (false) */ public void setBufferMode(boolean active) { bufferMode = active; if(!bufferMode) { executeBuffer(); } } /** * Returns the BranchView of the Branch that is repsonsible for task, * IF it is being delegated * @param task the task of which to get the responsible branch * @return * | BranchView of the task's responsible branch * | empty Optional otherwise */ public Optional<BranchView> getResponsibleBranch(Task task) { Optional<DelegatingTaskProxy> delProxy = Optional.ofNullable(delegationProxies.get(task)); if(delProxy.isPresent()) { if(delProxy.get().getDelegatingBranch().isPresent()) { return Optional.of(new BranchView(delProxy.get().getDelegatingBranch().get())); } else { return Optional.empty(); } } else { //kijk eens<SUF> Iterator<DelegationData> i = buffer.iterator(); DelegationData d; while(i.hasNext()) { d = i.next(); if(d.delegatedTask == task) { return Optional.of(new BranchView(d.newBranch)); } } return Optional.empty(); } } /** * Returns the TaskView of the Task that is delegating task, * IF it is being delegated * @param t the task of which to get the delegating task * @return * | BranchView of the task's responsible branch * | empty Optional otherwise */ public Optional<TaskView> getDelegatingTask(Task t) { Optional<DelegatingTaskProxy> delProxy = Optional.ofNullable(delegationProxies.get(t)); if(delProxy.isPresent()) { return Optional.of(new TaskView(delProxy.get().getDelegatingTask())); } else { return Optional.empty(); } } private class DelegationData { private Task delegatedTask; private Branch originalBranch, newBranch; private DelegationData(Task task,Branch origBranch, Branch newBranch){ delegatedTask = task; originalBranch = origBranch; this.newBranch = newBranch; } } /** * @return the current Task-Proxy pairings (original) */ protected Map<Task, OriginalTaskProxy> getOriginalProxies() { return originalProxies; } /** * @return the current Task-Proxy pairings (delegating) */ protected Map<Task, DelegatingTaskProxy> getDelegatingProxies() { return delegationProxies; } /** * A method to allow the Branch to offer new task and (original) proxy * pairings to the representative * * @param proxies * | The new task-proxy pairings present in the system */ protected void offerOriginalTaskProxies(Map<Task, OriginalTaskProxy> proxies) { originalProxies = proxies; } /** * A method to allow the Branch to offer new task and (delegating) proxy * pairings to the representative * * @param proxies * | The new task-proxy pairings present in the system */ protected void offerDelegatingTaskProxies( Map<Task, DelegatingTaskProxy> proxies) { delegationProxies = proxies; } }
True
False
1,542
845
1652_4
package be.pxl.h4.exoef1; /*Extra oefening 1 * * Geef 2 getallen in via het toetsenbord. Maak een afdruk als volgt: * het kleinste getal is ... * Het kwadraat van het kleinste getal is ...*/ import java.util.Scanner; public class H4ExOef1 { public static void main(String[] args) { //Scanner en variabelen aanmaken Scanner keyboard = new Scanner(System.in); int a, b, kleinste_getal, kwadraat_kleinste_getal; //Input vragen van de gebruiker System.out.println("Getal a: "); a = keyboard.nextInt(); System.out.println("Getal b: "); b = keyboard.nextInt(); //Bepalen welk getal het kleinste is if (a > b) { kleinste_getal = b; } else { kleinste_getal = a; } //Kwadraat berekenen en kleinste getal en zijn kwadraat uitrekenen kwadraat_kleinste_getal = kleinste_getal * kleinste_getal; // Opgelost zonder de math klasse - normaal wordt die voor deze berekening gebruikt. System.out.println("Het kleinste getal is " + kleinste_getal); System.out.println("Het kwadraat van het kleinste getal is " + kwadraat_kleinste_getal); keyboard.close(); } }
JoachimVeulemans/PXL-DIGITAL
PXL_DIGITAL_JAAR_1/Programming Basics/Oplossingen Oefeningen/H4/exoef1/H4ExOef1.java
421
//Kwadraat berekenen en kleinste getal en zijn kwadraat uitrekenen
line_comment
nl
package be.pxl.h4.exoef1; /*Extra oefening 1 * * Geef 2 getallen in via het toetsenbord. Maak een afdruk als volgt: * het kleinste getal is ... * Het kwadraat van het kleinste getal is ...*/ import java.util.Scanner; public class H4ExOef1 { public static void main(String[] args) { //Scanner en variabelen aanmaken Scanner keyboard = new Scanner(System.in); int a, b, kleinste_getal, kwadraat_kleinste_getal; //Input vragen van de gebruiker System.out.println("Getal a: "); a = keyboard.nextInt(); System.out.println("Getal b: "); b = keyboard.nextInt(); //Bepalen welk getal het kleinste is if (a > b) { kleinste_getal = b; } else { kleinste_getal = a; } //Kwadraat berekenen<SUF> kwadraat_kleinste_getal = kleinste_getal * kleinste_getal; // Opgelost zonder de math klasse - normaal wordt die voor deze berekening gebruikt. System.out.println("Het kleinste getal is " + kleinste_getal); System.out.println("Het kwadraat van het kleinste getal is " + kwadraat_kleinste_getal); keyboard.close(); } }
True
False
1,546
3,565
18940_13
package SELMA; import java.util.*; import SELMA.SELMATree.SR_Type; import SELMA.SELMATree.SR_Kind; import SELMA.SELMATree.SR_Func; import SELMA.SELMAChecker; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.tree.Tree; /** * Implementatie van een symbol table voor de compiler. */ public class SymbolTable<Entry extends IdEntry> { public int nextAddr = 1; public int funclevel = 0; // Set of global variables along with their type denoters that should become fields public Set<String> globals = new HashSet<String>(); private int currentLevel; private Map<String, Stack<Entry>> entries; int localCount; /** * * @return Address voor een locale variabele */ public int nextAddr(){ return nextAddr; } /** * Constructor. * @ensure this.currentLevel() == -1 */ public SymbolTable() { currentLevel = -1; entries = new HashMap<String, Stack<Entry>>(); } /** * Opens a new scope. * @ensure this.currentLevel() == old.currentLevel()+1 */ public void openScope() { currentLevel++; } /** * Closes the current scope. All identifiers in * the current scope will be removed from the SymbolTable. * @require old.currentLevel() > -1 * @ensure this.currentLevel() == old.currentLevel()-1 */ public void closeScope() { for (Map.Entry<String, Stack<Entry>> entry: entries.entrySet()){ Stack<Entry> stack = entry.getValue(); if ((stack != null) && (!stack.isEmpty()) && (stack.peek().level >= currentLevel)){ Entry e = stack.pop(); localCount = nextAddr > localCount ? nextAddr : localCount; if (isLocal(e)) nextAddr--; } } currentLevel--; } /** Returns the current scope level. */ public int currentLevel() { return currentLevel; } /** Return whether the entry takes up space on the stack */ private boolean isLocal(Entry entry) { return entry instanceof CheckerEntry && ((CheckerEntry) entry).kind != SR_Kind.CONST; } /** * Enters an id together with an entry into this SymbolTable using the * current scope level. The entry's level is set to currentLevel(). * @require String != null && String != "" && entry != null * @ensure this.retrieve(id).getLevel() == currentLevel() * @throws SymbolTableException when there is no valid current scope level, * or when the id is already declared on the current level. */ public void enter(Tree tree, Entry entry) throws SymbolTableException { String id = tree.getText(); if (currentLevel < 0) { throw new SymbolTableException(tree, "Not in a valid scope."); } Stack<Entry> s = entries.get(id); if (s == null) { s = new Stack<Entry>(); entries.put(id, s); } if (s.isEmpty() || s.peek().level != currentLevel) { entry.level = currentLevel; s.push(entry); if (isLocal(entry)) nextAddr++; } else { throw new SymbolTableException(tree, "Entry "+id+" already exists in current scope."); } if (entry instanceof CompilerEntry) { CompilerEntry e = (CompilerEntry) entry; e.isGlobal = funclevel == 0; if (e.isGlobal && e.kind == SR_Kind.VAR && e.func != SR_Func.YES) globals.add(e.getIdentifier(id) + " " + getTypeDenoter(e.type, false)); } } /** * Get the Entry corresponding with id whose level is the highest. * In other words, the method returns the Entry that is defined last. * @return Entry of this id on the highest level * null if this SymbolTable does not contain id */ public Entry retrieve(Tree tree) throws SymbolTableException { String id = tree.getText(); Stack<Entry> s = entries.get(id); if (s==null||s.isEmpty()) { throw new SymbolTableException(tree, "Entry not found: " + id); } return s.peek(); } public void addParamToFunc(Tree func, Tree param, Tree type) { SR_Type selmaType = ((SELMATree) type).getSelmaType(); CheckerEntry function = (CheckerEntry) retrieve(func); function.addParam(param, selmaType); CompilerEntry paramentry = new CompilerEntry(selmaType, SR_Kind.VAR, nextAddr); paramentry.initialized = true; enter(param, (Entry) paramentry); } public String toString(){ String s = ""; for (Map.Entry<String, Stack<Entry>> entry: entries.entrySet()){ Stack<Entry> stack = entry.getValue(); s += String.format("Id=%-10s : %s=%s\n", entry.getKey(), stack, stack.peek().getClass()); //s+=entry.getKey(); //s+=stack.toString(); } return s; } /* Get the locals limit for this stack frame */ public int getLocalsCount() { return nextAddr > localCount ? nextAddr : localCount; } /** * Return the JVM type denoter of the Symbol Table SR_Type * @param type the type to get the denoter for * @param printing whether the denoter is used to format * values using the print() statement * @return The type denoter (String) */ public String getTypeDenoter(SR_Type type, boolean printing) { if (type == SR_Type.INT) { return "I"; } else if (type == SR_Type.BOOL) { if (printing) return "Ljava/lang/String;"; else return "I"; } else if (type == SR_Type.VOID) { return "V"; } else if (type == SR_Type.CHAR) { return "C"; } else { throw new RuntimeException(":( Invalid type: " + type); } } /** * Enter een functie scope. Houdt bij of we in een functie zitten of niet, zodat we weten of variabelen globaal zijn of niet. */ public void enterFuncScope() { openScope(); funclevel++; } /** * Verlaat een functie scope. Houdt bij of we in een functie zitten of niet, zodat we weten of variabelen globaal zijn of niet. */ public void leaveFuncScope() { closeScope(); funclevel--; } } /** Exception class to signal problems with the SymbolTable */ class SymbolTableException extends RuntimeException { //RecognitionException { public static final long serialVersionUID = 24362462L; // for Serializable private String msg; public SymbolTableException(Tree tree, String msg) { super(); this.msg = tree.getText() + " (" + tree.getLine() + ":" + tree.getCharPositionInLine() + ") " + msg; } public String getMessage() { return msg; } }
markflorisson/selma
src/SELMA/SymbolTable.java
2,003
/** * Verlaat een functie scope. Houdt bij of we in een functie zitten of niet, zodat we weten of variabelen globaal zijn of niet. */
block_comment
nl
package SELMA; import java.util.*; import SELMA.SELMATree.SR_Type; import SELMA.SELMATree.SR_Kind; import SELMA.SELMATree.SR_Func; import SELMA.SELMAChecker; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.tree.Tree; /** * Implementatie van een symbol table voor de compiler. */ public class SymbolTable<Entry extends IdEntry> { public int nextAddr = 1; public int funclevel = 0; // Set of global variables along with their type denoters that should become fields public Set<String> globals = new HashSet<String>(); private int currentLevel; private Map<String, Stack<Entry>> entries; int localCount; /** * * @return Address voor een locale variabele */ public int nextAddr(){ return nextAddr; } /** * Constructor. * @ensure this.currentLevel() == -1 */ public SymbolTable() { currentLevel = -1; entries = new HashMap<String, Stack<Entry>>(); } /** * Opens a new scope. * @ensure this.currentLevel() == old.currentLevel()+1 */ public void openScope() { currentLevel++; } /** * Closes the current scope. All identifiers in * the current scope will be removed from the SymbolTable. * @require old.currentLevel() > -1 * @ensure this.currentLevel() == old.currentLevel()-1 */ public void closeScope() { for (Map.Entry<String, Stack<Entry>> entry: entries.entrySet()){ Stack<Entry> stack = entry.getValue(); if ((stack != null) && (!stack.isEmpty()) && (stack.peek().level >= currentLevel)){ Entry e = stack.pop(); localCount = nextAddr > localCount ? nextAddr : localCount; if (isLocal(e)) nextAddr--; } } currentLevel--; } /** Returns the current scope level. */ public int currentLevel() { return currentLevel; } /** Return whether the entry takes up space on the stack */ private boolean isLocal(Entry entry) { return entry instanceof CheckerEntry && ((CheckerEntry) entry).kind != SR_Kind.CONST; } /** * Enters an id together with an entry into this SymbolTable using the * current scope level. The entry's level is set to currentLevel(). * @require String != null && String != "" && entry != null * @ensure this.retrieve(id).getLevel() == currentLevel() * @throws SymbolTableException when there is no valid current scope level, * or when the id is already declared on the current level. */ public void enter(Tree tree, Entry entry) throws SymbolTableException { String id = tree.getText(); if (currentLevel < 0) { throw new SymbolTableException(tree, "Not in a valid scope."); } Stack<Entry> s = entries.get(id); if (s == null) { s = new Stack<Entry>(); entries.put(id, s); } if (s.isEmpty() || s.peek().level != currentLevel) { entry.level = currentLevel; s.push(entry); if (isLocal(entry)) nextAddr++; } else { throw new SymbolTableException(tree, "Entry "+id+" already exists in current scope."); } if (entry instanceof CompilerEntry) { CompilerEntry e = (CompilerEntry) entry; e.isGlobal = funclevel == 0; if (e.isGlobal && e.kind == SR_Kind.VAR && e.func != SR_Func.YES) globals.add(e.getIdentifier(id) + " " + getTypeDenoter(e.type, false)); } } /** * Get the Entry corresponding with id whose level is the highest. * In other words, the method returns the Entry that is defined last. * @return Entry of this id on the highest level * null if this SymbolTable does not contain id */ public Entry retrieve(Tree tree) throws SymbolTableException { String id = tree.getText(); Stack<Entry> s = entries.get(id); if (s==null||s.isEmpty()) { throw new SymbolTableException(tree, "Entry not found: " + id); } return s.peek(); } public void addParamToFunc(Tree func, Tree param, Tree type) { SR_Type selmaType = ((SELMATree) type).getSelmaType(); CheckerEntry function = (CheckerEntry) retrieve(func); function.addParam(param, selmaType); CompilerEntry paramentry = new CompilerEntry(selmaType, SR_Kind.VAR, nextAddr); paramentry.initialized = true; enter(param, (Entry) paramentry); } public String toString(){ String s = ""; for (Map.Entry<String, Stack<Entry>> entry: entries.entrySet()){ Stack<Entry> stack = entry.getValue(); s += String.format("Id=%-10s : %s=%s\n", entry.getKey(), stack, stack.peek().getClass()); //s+=entry.getKey(); //s+=stack.toString(); } return s; } /* Get the locals limit for this stack frame */ public int getLocalsCount() { return nextAddr > localCount ? nextAddr : localCount; } /** * Return the JVM type denoter of the Symbol Table SR_Type * @param type the type to get the denoter for * @param printing whether the denoter is used to format * values using the print() statement * @return The type denoter (String) */ public String getTypeDenoter(SR_Type type, boolean printing) { if (type == SR_Type.INT) { return "I"; } else if (type == SR_Type.BOOL) { if (printing) return "Ljava/lang/String;"; else return "I"; } else if (type == SR_Type.VOID) { return "V"; } else if (type == SR_Type.CHAR) { return "C"; } else { throw new RuntimeException(":( Invalid type: " + type); } } /** * Enter een functie scope. Houdt bij of we in een functie zitten of niet, zodat we weten of variabelen globaal zijn of niet. */ public void enterFuncScope() { openScope(); funclevel++; } /** * Verlaat een functie<SUF>*/ public void leaveFuncScope() { closeScope(); funclevel--; } } /** Exception class to signal problems with the SymbolTable */ class SymbolTableException extends RuntimeException { //RecognitionException { public static final long serialVersionUID = 24362462L; // for Serializable private String msg; public SymbolTableException(Tree tree, String msg) { super(); this.msg = tree.getText() + " (" + tree.getLine() + ":" + tree.getCharPositionInLine() + ") " + msg; } public String getMessage() { return msg; } }
True
False
1,548
3,496
52540_18
package nl.spookystoriesinc.coolgame; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.os.Handler; import android.util.Log; import android.widget.Toast; import nl.spookystoriesinc.model.GameBoard; import nl.spookystoriesinc.model.GameObject; import nl.spookystoriesinc.spookystories.R; import nl.spookystoriesinc.view.GameBoardView; import nl.spookystoriesinc.view.InventoryView; import nl.spookystoriesinc.coolgame.objects.Enemy; import nl.spookystoriesinc.coolgame.objects.Player; /** * The game board for CoolGame. * * @author Paul de Groot */ public class CoolGameBoard extends GameBoard { private static final int GAMEBOARD_WIDTH = 9; private static final int GAMEBOARD_HEIGHT = 7; private Intent gameIsOver; private Timer timer; private MediaPlayer mediaPlayer; Handler handler = new Handler(); private boolean gameOver = false; // The difference between the players position and the clicked tile private int difX; private int difY; // the x where the player is moving to private int newX; private int newY; // The x pos. and y pos. from the player object private int oldX; private int oldY; private MainActivity mainActivity; private GameObject objectAtNewPos; /** * Create a new game board. */ public CoolGameBoard(MainActivity mainActivity, Context context) { super(GAMEBOARD_WIDTH, GAMEBOARD_HEIGHT, context); this.mainActivity = mainActivity; } @Override public void changeRoom(String room){ timer.cancel(); timer.purge(); super.changeRoom(room); init(); } public void reset(){ gameOver = false; this.resetGame(); timer = new Timer(); init(); } public void gameOver(){ gameOver = true; timer.cancel(); timer.purge(); deathSound(); mainActivity.initGameOverState(); } private void deathSound() { mediaPlayer = MediaPlayer.create(mainActivity.getApplicationContext(), R.raw.death); mediaPlayer.start(); } public void init(){ if(getEnemy() == null){ return; } timer = new Timer(); timer.scheduleAtFixedRate(new MoveEnemyTask(), 1500, 1500); } class MoveEnemyTask extends TimerTask{ // The difference between the players position and the clicked tile private int enemyDifX; private int enemyDifY; // the x where the player is moving to private int enemyNewX; private int enemyNewY; // The x pos. and y pos. from the player object private int enemyOldX; private int enemyOldY; @Override public void run() { if(gameOver){ gameOver(); return; } if(getEnemy().getPositionX() == (getPlayer().getPositionX() + 1) && getEnemy().getPositionY() == getPlayer().getPositionY()){ gameOver(); return; } else if(getEnemy().getPositionX() == (getPlayer().getPositionX() - 1) && getEnemy().getPositionY() == getPlayer().getPositionY()){ gameOver(); return; } else if(getEnemy().getPositionY() == (getPlayer().getPositionY() + 1) && getEnemy().getPositionX() == getPlayer().getPositionX()){ gameOver(); return; } else if(getEnemy().getPositionY() == (getPlayer().getPositionY() - 1) && getEnemy().getPositionX() == getPlayer().getPositionX()){ gameOver(); return; } // The x pos. and y pos. from the enemy object enemyOldX = getEnemy().getPositionX(); enemyOldY = getEnemy().getPositionY(); // Calculate the difference between the players position and enemy enemyDifX = getPlayer().getPositionX() - enemyOldX; enemyDifY = getPlayer().getPositionY() - enemyOldY; // links naar beneden if (enemyDifX <= 0 && enemyDifY >= 0) { moveChar(-1 , 1, getEnemy(), enemyDifX, enemyDifY); } // links naar boven else if (enemyDifX <= 0 && enemyDifY <= 0) { moveChar(-1, -1, getEnemy(), enemyDifX, enemyDifY); } // rechts naar boven else if (enemyDifX >= 0 && enemyDifY <= 0) { moveChar(1, -1, getEnemy(), enemyDifX, enemyDifY); } // rechts naar onder! else if(enemyDifX >= 0 && enemyDifY >= 0){ moveChar(1, 1, getEnemy(), enemyDifX, enemyDifY); } else { return; } handler.post(new Runnable(){ @Override public void run() { updateView(); } }); } } /** * */ @Override public void onEmptyTileClicked(int x, int y) { if(gameOver){ timer.cancel(); timer.purge(); return; } // The x pos. and y pos. from the object oldX = getPlayer().getPositionX(); oldY = getPlayer().getPositionY(); // Calculate the difference between the players position and the clicked tile difX = x - oldX; difY = y - oldY; // links naar beneden if (difX <= 0 && difY >= 0) { moveChar(-1, 1, this.getPlayer(), difX, difY); } // links naar boven else if (difX <= 0 && difY <= 0) { moveChar(-1, -1, this.getPlayer(), difX, difY); } // rechts naar boven else if (difX >= 0 && difY <= 0) { moveChar(1, -1, this.getPlayer(), difX, difY); } // rechts naar onder! else if(difX >= 0 && difY >= 0){ moveChar(1, 1, this.getPlayer(), difX, difY); } else { return; } updateView(); } @Override public String getBackgroundImg(int mx, int my) { return null; } /** * A method to remove the - from a number * @param getal the number you want to remove the - from * @return the number */ public int haalMinWeg(int getal) { if(getal >= 0 ){ return getal; } else { return getal * -1; } } /** * * @param x which way you want to move in the x direction * @param y which way you want to move in the y direction * @param obj The object you want to move * @param difX the x difference between the object you want to move and where it has to move * @param difY the x difference between the object you want to move and where it has to move */ public void moveChar(int x, int y, GameObject obj, int difX, int difY){ // The x pos. and y pos. from the object oldX = obj.getPositionX(); oldY = obj.getPositionY(); if (haalMinWeg(difX) >= haalMinWeg(difY)) { newX = oldX + x; newY = oldY; objectAtNewPos = this.getObject(newX, newY); if (objectAtNewPos != null) { newX = oldX; newY = oldY + y; objectAtNewPos = this.getObject(newX, newY); if (objectAtNewPos != null) { newX = oldX; newY = oldY - y; objectAtNewPos = this.getObject(newX, newY); if(objectAtNewPos != null){ return; } else{ if(y > 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.UP_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.UP_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.DOWN_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.DOWN_GHOST_IMAGE); } } this.moveObject(obj, (oldX), (oldY - y)); } } else { if(y > 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.DOWN_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.DOWN_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.UP_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.UP_GHOST_IMAGE); } } this.moveObject(obj, (oldX), (oldY + y)); } } else { if(x >= 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.RIGHT_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.RIGHT_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.LEFT_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.LEFT_GHOST_IMAGE); } } this.moveObject(obj, (oldX + x), oldY); } } else { newX = oldX; newY = oldY + y; objectAtNewPos = this.getObject(newX, newY); if (objectAtNewPos != null) { newX = oldX + x; newY = oldY; objectAtNewPos = this.getObject(newX, newY); if (objectAtNewPos != null) { newX = oldX - x; newY = oldY; objectAtNewPos = this.getObject(newX, newY); if(objectAtNewPos != null){ return; } else{ if(x >= 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.RIGHT_PLAYER_IMAGE); } else{ ((Enemy) getEnemy()).setImageId(Enemy.RIGHT_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.LEFT_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.LEFT_GHOST_IMAGE); } } this.moveObject(obj, (oldX - x), (oldY)); } } else { if(x >= 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.RIGHT_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.RIGHT_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.LEFT_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.LEFT_GHOST_IMAGE); } } this.moveObject(obj, (oldX + x), (oldY)); } } else { if(y >= 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.DOWN_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.DOWN_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.UP_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.UP_GHOST_IMAGE); } } this.moveObject(obj, (oldX), (oldY + y)); } } } }
lmartos/SoulSurviver
src/nl/spookystoriesinc/coolgame/CoolGameBoard.java
3,953
// rechts naar boven
line_comment
nl
package nl.spookystoriesinc.coolgame; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.os.Handler; import android.util.Log; import android.widget.Toast; import nl.spookystoriesinc.model.GameBoard; import nl.spookystoriesinc.model.GameObject; import nl.spookystoriesinc.spookystories.R; import nl.spookystoriesinc.view.GameBoardView; import nl.spookystoriesinc.view.InventoryView; import nl.spookystoriesinc.coolgame.objects.Enemy; import nl.spookystoriesinc.coolgame.objects.Player; /** * The game board for CoolGame. * * @author Paul de Groot */ public class CoolGameBoard extends GameBoard { private static final int GAMEBOARD_WIDTH = 9; private static final int GAMEBOARD_HEIGHT = 7; private Intent gameIsOver; private Timer timer; private MediaPlayer mediaPlayer; Handler handler = new Handler(); private boolean gameOver = false; // The difference between the players position and the clicked tile private int difX; private int difY; // the x where the player is moving to private int newX; private int newY; // The x pos. and y pos. from the player object private int oldX; private int oldY; private MainActivity mainActivity; private GameObject objectAtNewPos; /** * Create a new game board. */ public CoolGameBoard(MainActivity mainActivity, Context context) { super(GAMEBOARD_WIDTH, GAMEBOARD_HEIGHT, context); this.mainActivity = mainActivity; } @Override public void changeRoom(String room){ timer.cancel(); timer.purge(); super.changeRoom(room); init(); } public void reset(){ gameOver = false; this.resetGame(); timer = new Timer(); init(); } public void gameOver(){ gameOver = true; timer.cancel(); timer.purge(); deathSound(); mainActivity.initGameOverState(); } private void deathSound() { mediaPlayer = MediaPlayer.create(mainActivity.getApplicationContext(), R.raw.death); mediaPlayer.start(); } public void init(){ if(getEnemy() == null){ return; } timer = new Timer(); timer.scheduleAtFixedRate(new MoveEnemyTask(), 1500, 1500); } class MoveEnemyTask extends TimerTask{ // The difference between the players position and the clicked tile private int enemyDifX; private int enemyDifY; // the x where the player is moving to private int enemyNewX; private int enemyNewY; // The x pos. and y pos. from the player object private int enemyOldX; private int enemyOldY; @Override public void run() { if(gameOver){ gameOver(); return; } if(getEnemy().getPositionX() == (getPlayer().getPositionX() + 1) && getEnemy().getPositionY() == getPlayer().getPositionY()){ gameOver(); return; } else if(getEnemy().getPositionX() == (getPlayer().getPositionX() - 1) && getEnemy().getPositionY() == getPlayer().getPositionY()){ gameOver(); return; } else if(getEnemy().getPositionY() == (getPlayer().getPositionY() + 1) && getEnemy().getPositionX() == getPlayer().getPositionX()){ gameOver(); return; } else if(getEnemy().getPositionY() == (getPlayer().getPositionY() - 1) && getEnemy().getPositionX() == getPlayer().getPositionX()){ gameOver(); return; } // The x pos. and y pos. from the enemy object enemyOldX = getEnemy().getPositionX(); enemyOldY = getEnemy().getPositionY(); // Calculate the difference between the players position and enemy enemyDifX = getPlayer().getPositionX() - enemyOldX; enemyDifY = getPlayer().getPositionY() - enemyOldY; // links naar beneden if (enemyDifX <= 0 && enemyDifY >= 0) { moveChar(-1 , 1, getEnemy(), enemyDifX, enemyDifY); } // links naar boven else if (enemyDifX <= 0 && enemyDifY <= 0) { moveChar(-1, -1, getEnemy(), enemyDifX, enemyDifY); } // rechts naar boven else if (enemyDifX >= 0 && enemyDifY <= 0) { moveChar(1, -1, getEnemy(), enemyDifX, enemyDifY); } // rechts naar onder! else if(enemyDifX >= 0 && enemyDifY >= 0){ moveChar(1, 1, getEnemy(), enemyDifX, enemyDifY); } else { return; } handler.post(new Runnable(){ @Override public void run() { updateView(); } }); } } /** * */ @Override public void onEmptyTileClicked(int x, int y) { if(gameOver){ timer.cancel(); timer.purge(); return; } // The x pos. and y pos. from the object oldX = getPlayer().getPositionX(); oldY = getPlayer().getPositionY(); // Calculate the difference between the players position and the clicked tile difX = x - oldX; difY = y - oldY; // links naar beneden if (difX <= 0 && difY >= 0) { moveChar(-1, 1, this.getPlayer(), difX, difY); } // links naar boven else if (difX <= 0 && difY <= 0) { moveChar(-1, -1, this.getPlayer(), difX, difY); } // rechts naar<SUF> else if (difX >= 0 && difY <= 0) { moveChar(1, -1, this.getPlayer(), difX, difY); } // rechts naar onder! else if(difX >= 0 && difY >= 0){ moveChar(1, 1, this.getPlayer(), difX, difY); } else { return; } updateView(); } @Override public String getBackgroundImg(int mx, int my) { return null; } /** * A method to remove the - from a number * @param getal the number you want to remove the - from * @return the number */ public int haalMinWeg(int getal) { if(getal >= 0 ){ return getal; } else { return getal * -1; } } /** * * @param x which way you want to move in the x direction * @param y which way you want to move in the y direction * @param obj The object you want to move * @param difX the x difference between the object you want to move and where it has to move * @param difY the x difference between the object you want to move and where it has to move */ public void moveChar(int x, int y, GameObject obj, int difX, int difY){ // The x pos. and y pos. from the object oldX = obj.getPositionX(); oldY = obj.getPositionY(); if (haalMinWeg(difX) >= haalMinWeg(difY)) { newX = oldX + x; newY = oldY; objectAtNewPos = this.getObject(newX, newY); if (objectAtNewPos != null) { newX = oldX; newY = oldY + y; objectAtNewPos = this.getObject(newX, newY); if (objectAtNewPos != null) { newX = oldX; newY = oldY - y; objectAtNewPos = this.getObject(newX, newY); if(objectAtNewPos != null){ return; } else{ if(y > 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.UP_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.UP_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.DOWN_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.DOWN_GHOST_IMAGE); } } this.moveObject(obj, (oldX), (oldY - y)); } } else { if(y > 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.DOWN_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.DOWN_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.UP_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.UP_GHOST_IMAGE); } } this.moveObject(obj, (oldX), (oldY + y)); } } else { if(x >= 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.RIGHT_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.RIGHT_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.LEFT_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.LEFT_GHOST_IMAGE); } } this.moveObject(obj, (oldX + x), oldY); } } else { newX = oldX; newY = oldY + y; objectAtNewPos = this.getObject(newX, newY); if (objectAtNewPos != null) { newX = oldX + x; newY = oldY; objectAtNewPos = this.getObject(newX, newY); if (objectAtNewPos != null) { newX = oldX - x; newY = oldY; objectAtNewPos = this.getObject(newX, newY); if(objectAtNewPos != null){ return; } else{ if(x >= 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.RIGHT_PLAYER_IMAGE); } else{ ((Enemy) getEnemy()).setImageId(Enemy.RIGHT_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.LEFT_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.LEFT_GHOST_IMAGE); } } this.moveObject(obj, (oldX - x), (oldY)); } } else { if(x >= 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.RIGHT_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.RIGHT_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.LEFT_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.LEFT_GHOST_IMAGE); } } this.moveObject(obj, (oldX + x), (oldY)); } } else { if(y >= 0){ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.DOWN_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.DOWN_GHOST_IMAGE); } } else{ if(obj instanceof Player){ ((Player) getPlayer()).setImageId(Player.UP_PLAYER_IMAGE); }else{ ((Enemy) getEnemy()).setImageId(Enemy.UP_GHOST_IMAGE); } } this.moveObject(obj, (oldX), (oldY + y)); } } } }
True
False
1,552
3,391
25495_15
/* * Copyright (C) 2013 Koen Vlaswinkel * * 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 nl.phphulp.app; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import android.widget.Toast; public class ArticleAdapter extends BaseAdapter { private Context context; private ArrayList<Article> items; /** * Dit wordt gebruikt voor een hogere snelheid */ static class ViewHolder { public TextView title; public TextView text; } public ArticleAdapter(Context context, ArrayList<Article> items) { super(); this.context = context; this.items = items; } /** * Hoe groot is onze lijst? * * @return grootte van de lijst */ @Override public int getCount() { return items.size(); } /** * Een item uit de lijst * * @return een object dat het item is */ @Override public Object getItem(int position) { return items.get(position); } /** * Dit is een beetje onzinnig voor onze applicatie * * @return de positie */ @Override public long getItemId(int position) { return position; } /** * Hier maken we de view die zichtbaar is in de lijst * * @param position * @param convertView * @param parent * * @return De view */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { // Zorg ervoor dat we een layout kunnen maken LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Zorg voor een standaard view met 2 regels view = inflater.inflate(android.R.layout.simple_list_item_2, parent, false); // We gaan voor wat snelheid zorgen ViewHolder viewHolder = new ViewHolder(); viewHolder.title = (TextView) view.findViewById(android.R.id.text1); viewHolder.text = (TextView) view.findViewById(android.R.id.text2); // En deze snelheid opslaan view.setTag(viewHolder); } // Hier kunnen we de snelheid weer terugkrijgen ViewHolder holder = (ViewHolder) view.getTag(); // Dit is ons artikel dat we moeten laten zien final Article article = items.get(position); // We gaan op de eerste regel een titel laten zien holder.title.setText(article.getTitle()); // En op de tweede regel wat content holder.text.setText(article.getContent()); // En nu gaan we zorgen dat er een 'Toast' verschijnt als je op het item // klikt view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Hier maken we een 'Toast' Toast.makeText( context, "Je hebt op artikel " + article.getId() + " geklikt met slug " + article.getSlug(), Toast.LENGTH_LONG).show(); } }); return view; } }
koesie10/phphulp-android
Android/src/nl/phphulp/app/ArticleAdapter.java
1,074
// Hier maken we een 'Toast'
line_comment
nl
/* * Copyright (C) 2013 Koen Vlaswinkel * * 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 nl.phphulp.app; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import android.widget.Toast; public class ArticleAdapter extends BaseAdapter { private Context context; private ArrayList<Article> items; /** * Dit wordt gebruikt voor een hogere snelheid */ static class ViewHolder { public TextView title; public TextView text; } public ArticleAdapter(Context context, ArrayList<Article> items) { super(); this.context = context; this.items = items; } /** * Hoe groot is onze lijst? * * @return grootte van de lijst */ @Override public int getCount() { return items.size(); } /** * Een item uit de lijst * * @return een object dat het item is */ @Override public Object getItem(int position) { return items.get(position); } /** * Dit is een beetje onzinnig voor onze applicatie * * @return de positie */ @Override public long getItemId(int position) { return position; } /** * Hier maken we de view die zichtbaar is in de lijst * * @param position * @param convertView * @param parent * * @return De view */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { // Zorg ervoor dat we een layout kunnen maken LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Zorg voor een standaard view met 2 regels view = inflater.inflate(android.R.layout.simple_list_item_2, parent, false); // We gaan voor wat snelheid zorgen ViewHolder viewHolder = new ViewHolder(); viewHolder.title = (TextView) view.findViewById(android.R.id.text1); viewHolder.text = (TextView) view.findViewById(android.R.id.text2); // En deze snelheid opslaan view.setTag(viewHolder); } // Hier kunnen we de snelheid weer terugkrijgen ViewHolder holder = (ViewHolder) view.getTag(); // Dit is ons artikel dat we moeten laten zien final Article article = items.get(position); // We gaan op de eerste regel een titel laten zien holder.title.setText(article.getTitle()); // En op de tweede regel wat content holder.text.setText(article.getContent()); // En nu gaan we zorgen dat er een 'Toast' verschijnt als je op het item // klikt view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Hier maken<SUF> Toast.makeText( context, "Je hebt op artikel " + article.getId() + " geklikt met slug " + article.getSlug(), Toast.LENGTH_LONG).show(); } }); return view; } }
True
False
1,553
476
52687_6
package novi.nl.Les11BESpringbootmodelhuiswerk.models; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.util.List; @Entity @Table(name = "cimodules") public class CIModule { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String type; private Double price; // Een ManyToOne relatie tussen Television en CI-Module // @OneToMany(mappedBy = "cimodule") // private List<Television> televisions; // OneToMany relatie tussen Television en CI-Module @ManyToOne private Television television; //getters & setters........................................ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } // hoort bij ManyToOne public Television getTelevision() { return television; } public void setTelevision(Television television) { this.television = television; } // hoort bij OneToMany // public List<Television> getTelevisions() { // return televisions; // } // // public void setTelevisions(List<Television> televisions) { // this.televisions = televisions; // } }
Ellen-van-Duikeren/BE-spring-boot-model-huiswerk-Les11
src/main/java/novi/nl/Les11BESpringbootmodelhuiswerk/models/CIModule.java
493
// hoort bij OneToMany
line_comment
nl
package novi.nl.Les11BESpringbootmodelhuiswerk.models; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.util.List; @Entity @Table(name = "cimodules") public class CIModule { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String type; private Double price; // Een ManyToOne relatie tussen Television en CI-Module // @OneToMany(mappedBy = "cimodule") // private List<Television> televisions; // OneToMany relatie tussen Television en CI-Module @ManyToOne private Television television; //getters & setters........................................ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } // hoort bij ManyToOne public Television getTelevision() { return television; } public void setTelevision(Television television) { this.television = television; } // hoort bij<SUF> // public List<Television> getTelevisions() { // return televisions; // } // // public void setTelevisions(List<Television> televisions) { // this.televisions = televisions; // } }
True
False
1,555
3,891
121895_20
/** * */ package org.sharks.service.producer; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.sharks.service.dto.EntityDetails; import org.sharks.service.dto.EntityDocument; import org.sharks.service.dto.EntityEntry; import org.sharks.service.dto.FaoLexDocument; import org.sharks.service.dto.GroupEntry; import org.sharks.service.dto.InformationSourceEntry; import org.sharks.service.dto.MeasureEntry; import org.sharks.service.dto.PoAEntry; import org.sharks.service.moniker.dto.FaoLexFiDocument; import org.sharks.storage.domain.CustomSpeciesGrp; import org.sharks.storage.domain.InformationSource; import org.sharks.storage.domain.Measure; import org.sharks.storage.domain.MgmtEntity; import org.sharks.storage.domain.PoA; /** * @author "Federico De Faveri [email protected]" * */ public class EntryProducers { public static <I, O> List<O> convert(Collection<I> input, EntryProducer<I, O> converter) { return input.stream().map(converter).collect(Collectors.toList()); } public static final EntryProducer<EntityDetails, EntityDocument> TO_ENTITY_DOC = new AbstractEntryProducer<EntityDetails, EntityDocument>() { @Override public EntityDocument produce(EntityDetails item) { // private final long id; // private final String acronym; // private final String name; // private final Long type; // private final String logoUrl; // private final String webSite; // private final String factsheetUrl; // private final List<EntityMember> members; // private final List<MeasureEntry> measures; // private final List<EntityDocument> others; // private final String title; // private final Integer year; // private final String type; // private final String url; // private final String symbol; return new EntityDocument(item.getAcronym(), 0, item.getType().toString(), item.getWebSite(), null); } }; public static final EntryProducer<Measure, MeasureEntry> TO_MEASURE_ENTRY = new AbstractEntryProducer<Measure, MeasureEntry>() { @Override public MeasureEntry produce(Measure measure) { String replacedMeasureSourceUrl = null; if (measure.getReplaces() != null) { Measure replaced = measure.getReplaces(); List<InformationSource> replacedSources = replaced.getInformationSources(); replacedMeasureSourceUrl = !replacedSources.isEmpty() ? replacedSources.get(0).getUrl() : null; } return new MeasureEntry(measure.getCode(), measure.getSymbol(), measure.getTitle(), measure.getDocumentType() != null ? measure.getDocumentType().getDescription() : null, measure.getMeasureYear(), measure.getBinding(), measure.getMgmtEntity().getAcronym(), convert(measure.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY), replacedMeasureSourceUrl); } // private String findEntityAcronym(List<InformationSource> sources) { // for (InformationSource source : sources) { // for (MgmtEntity mgmtEntity : source.getMgmtEntities()) { // if (mgmtEntity != null && mgmtEntity.getAcronym() != null) // return mgmtEntity.getAcronym(); // } // } // // return "werkelijk niks"; // return null; // } }; public static final EntryProducer<InformationSource, InformationSourceEntry> TO_INFORMATION_SOURCE_ENTRY = new AbstractEntryProducer<InformationSource, InformationSourceEntry>() { @Override public InformationSourceEntry produce(InformationSource source) { return new InformationSourceEntry(source.getUrl()); } }; public static final EntryProducer<CustomSpeciesGrp, GroupEntry> TO_GROUP_ENTRY = new AbstractEntryProducer<CustomSpeciesGrp, GroupEntry>() { @Override public GroupEntry produce(CustomSpeciesGrp group) { return new GroupEntry(group.getCode(), group.getCustomSpeciesGrp()); } }; public static final EntryProducer<PoA, PoAEntry> TO_POA_ENTRY = new AbstractEntryProducer<PoA, PoAEntry>() { @Override public PoAEntry produce(PoA poa) { return new PoAEntry(poa.getCode(), poa.getTitle(), poa.getPoAYear(), poa.getPoAType() != null ? poa.getPoAType().getDescription() : null, poa.getStatus() != null ? poa.getStatus().getDescription() : null, convert(poa.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY)); } }; public static final EntryProducer<MgmtEntity, EntityEntry> TO_ENTITY_ENTRY = new AbstractEntryProducer<MgmtEntity, EntityEntry>() { @Override public EntityEntry produce(MgmtEntity entity) { return new EntityEntry(entity.getAcronym(), entity.getMgmtEntityName(), entity.getMgmtEntityType().getCode()); } }; public static final EntryProducer<InformationSource, EntityDocument> TO_ENTITY_DOCUMENT = new AbstractEntryProducer<InformationSource, EntityDocument>() { @Override public EntityDocument produce(InformationSource source) { return new EntityDocument(source.getTitle(), source.getInfoSrcYear(), source.getInformationType().getDescription(), source.getUrl(), source.getSymbol()); } }; public static final EntryProducer<FaoLexFiDocument, FaoLexDocument> TO_FAOLEX_DOCUMENT = new AbstractEntryProducer<FaoLexFiDocument, FaoLexDocument>() { @Override public FaoLexDocument produce(FaoLexFiDocument doc) { return new FaoLexDocument(doc.getFaolexId(), doc.getTitle(), doc.getLongTitle(), doc.getDateOfText(), doc.getDateOfOriginalText(), doc.getDateOfConsolidation(), doc.getUri()); } }; public static abstract class AbstractEntryProducer<I, O> implements EntryProducer<I, O> { @Override public O apply(I t) { return produce(t); } } public interface EntryProducer<I, O> extends Function<I, O> { public O produce(I item); } }
openfigis/sharks
sharks-server/sharks-service/src/main/java/org/sharks/service/producer/EntryProducers.java
1,761
// // return "werkelijk niks";
line_comment
nl
/** * */ package org.sharks.service.producer; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.sharks.service.dto.EntityDetails; import org.sharks.service.dto.EntityDocument; import org.sharks.service.dto.EntityEntry; import org.sharks.service.dto.FaoLexDocument; import org.sharks.service.dto.GroupEntry; import org.sharks.service.dto.InformationSourceEntry; import org.sharks.service.dto.MeasureEntry; import org.sharks.service.dto.PoAEntry; import org.sharks.service.moniker.dto.FaoLexFiDocument; import org.sharks.storage.domain.CustomSpeciesGrp; import org.sharks.storage.domain.InformationSource; import org.sharks.storage.domain.Measure; import org.sharks.storage.domain.MgmtEntity; import org.sharks.storage.domain.PoA; /** * @author "Federico De Faveri [email protected]" * */ public class EntryProducers { public static <I, O> List<O> convert(Collection<I> input, EntryProducer<I, O> converter) { return input.stream().map(converter).collect(Collectors.toList()); } public static final EntryProducer<EntityDetails, EntityDocument> TO_ENTITY_DOC = new AbstractEntryProducer<EntityDetails, EntityDocument>() { @Override public EntityDocument produce(EntityDetails item) { // private final long id; // private final String acronym; // private final String name; // private final Long type; // private final String logoUrl; // private final String webSite; // private final String factsheetUrl; // private final List<EntityMember> members; // private final List<MeasureEntry> measures; // private final List<EntityDocument> others; // private final String title; // private final Integer year; // private final String type; // private final String url; // private final String symbol; return new EntityDocument(item.getAcronym(), 0, item.getType().toString(), item.getWebSite(), null); } }; public static final EntryProducer<Measure, MeasureEntry> TO_MEASURE_ENTRY = new AbstractEntryProducer<Measure, MeasureEntry>() { @Override public MeasureEntry produce(Measure measure) { String replacedMeasureSourceUrl = null; if (measure.getReplaces() != null) { Measure replaced = measure.getReplaces(); List<InformationSource> replacedSources = replaced.getInformationSources(); replacedMeasureSourceUrl = !replacedSources.isEmpty() ? replacedSources.get(0).getUrl() : null; } return new MeasureEntry(measure.getCode(), measure.getSymbol(), measure.getTitle(), measure.getDocumentType() != null ? measure.getDocumentType().getDescription() : null, measure.getMeasureYear(), measure.getBinding(), measure.getMgmtEntity().getAcronym(), convert(measure.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY), replacedMeasureSourceUrl); } // private String findEntityAcronym(List<InformationSource> sources) { // for (InformationSource source : sources) { // for (MgmtEntity mgmtEntity : source.getMgmtEntities()) { // if (mgmtEntity != null && mgmtEntity.getAcronym() != null) // return mgmtEntity.getAcronym(); // } // } // // return "werkelijk<SUF> // return null; // } }; public static final EntryProducer<InformationSource, InformationSourceEntry> TO_INFORMATION_SOURCE_ENTRY = new AbstractEntryProducer<InformationSource, InformationSourceEntry>() { @Override public InformationSourceEntry produce(InformationSource source) { return new InformationSourceEntry(source.getUrl()); } }; public static final EntryProducer<CustomSpeciesGrp, GroupEntry> TO_GROUP_ENTRY = new AbstractEntryProducer<CustomSpeciesGrp, GroupEntry>() { @Override public GroupEntry produce(CustomSpeciesGrp group) { return new GroupEntry(group.getCode(), group.getCustomSpeciesGrp()); } }; public static final EntryProducer<PoA, PoAEntry> TO_POA_ENTRY = new AbstractEntryProducer<PoA, PoAEntry>() { @Override public PoAEntry produce(PoA poa) { return new PoAEntry(poa.getCode(), poa.getTitle(), poa.getPoAYear(), poa.getPoAType() != null ? poa.getPoAType().getDescription() : null, poa.getStatus() != null ? poa.getStatus().getDescription() : null, convert(poa.getInformationSources(), TO_INFORMATION_SOURCE_ENTRY)); } }; public static final EntryProducer<MgmtEntity, EntityEntry> TO_ENTITY_ENTRY = new AbstractEntryProducer<MgmtEntity, EntityEntry>() { @Override public EntityEntry produce(MgmtEntity entity) { return new EntityEntry(entity.getAcronym(), entity.getMgmtEntityName(), entity.getMgmtEntityType().getCode()); } }; public static final EntryProducer<InformationSource, EntityDocument> TO_ENTITY_DOCUMENT = new AbstractEntryProducer<InformationSource, EntityDocument>() { @Override public EntityDocument produce(InformationSource source) { return new EntityDocument(source.getTitle(), source.getInfoSrcYear(), source.getInformationType().getDescription(), source.getUrl(), source.getSymbol()); } }; public static final EntryProducer<FaoLexFiDocument, FaoLexDocument> TO_FAOLEX_DOCUMENT = new AbstractEntryProducer<FaoLexFiDocument, FaoLexDocument>() { @Override public FaoLexDocument produce(FaoLexFiDocument doc) { return new FaoLexDocument(doc.getFaolexId(), doc.getTitle(), doc.getLongTitle(), doc.getDateOfText(), doc.getDateOfOriginalText(), doc.getDateOfConsolidation(), doc.getUri()); } }; public static abstract class AbstractEntryProducer<I, O> implements EntryProducer<I, O> { @Override public O apply(I t) { return produce(t); } } public interface EntryProducer<I, O> extends Function<I, O> { public O produce(I item); } }
True
False
1,556
2,549
10808_8
/* Copyright Alexander Drechsel 2012 * Copyright Niels Kamp 2012 * Copyright Kasper Vaessen 2012 * Copyright Niels Visser 2012 * * This file is part of MusicTable. * * MusicTable 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. * * MusicTable 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 MusicTable. If not, see <http://www.gnu.org/licenses/>. */ package playback; import GUI.ParticlePanel; //import GUI.VisualizationPanel; import java.util.ArrayList; import java.util.List; import javax.sound.midi.Instrument; import javax.sound.midi.MidiChannel; /** * * @param <syncronized> */ public class ToneGrid { protected List<List<Boolean>> grid; protected int width; protected int height; protected boolean isActive; protected GridConfiguration gc; public ToneGrid(GridConfiguration gc) { this.height = 10; this.gc = gc; } /** * Wisselt de status van een gegeven noot van actief naar inactief or van inactief naar actief. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void toggleTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, !col.get(note)); } } /** * Wisselt de status van een gegeven noot naar actief of doet niets als de noot al actief is. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void activateTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, true); } } /** * Wisselt de status van een gegeven noot naar inactief of doet niets als de noot al inactief is. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void deactivateTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, false); } } /** * Geeft de lijst van alle noten in de vorm van een lijst van kolomen met daarin de rijen. * @return */ public synchronized List<List<Boolean>> getAllTones() { List<List<Boolean>> result = new ArrayList<List<Boolean>>(); for (int i = 0; i < this.width; i++) { List<Boolean> el = new ArrayList<Boolean>(); result.add(el); for (int j = 0; j < this.height; j++) { el.add(this.grid.get(i).get(j)); } } return result; } /** * Geeft de status van een gegeven noot. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord * @return true==actief;inactief==false */ public boolean getTone(int column, int note) { synchronized (this.grid) { return this.grid.get(column).get(note); } } /** * Delegeert aan gridconfig * @param column * @param vp */ public void playColumnTones(int column, ParticlePanel vp) { List<Integer> tones = this.getColumnTones(column); this.gc.playTones(tones, vp); } public List<Integer> getColumnTones(int x) { List<Boolean> notesArray = this.grid.get(x); List<Integer> notesList = new ArrayList<Integer>(); for(int i=0; i<notesArray.size(); i++) { if(notesArray.get(i)) notesList.add(i); } return notesList; } public void setConfiguration(GridConfiguration gc) { this.gc = gc; } public GridConfiguration getGridConfiguration() { return gc; } public boolean isIsActive() { return isActive; } public void setIsActive(boolean isActive) { this.isActive = isActive; } /** * Tweede gedeelte van de registratie methode. * Registreerd het aantal kolomen en initaliseerd de dubbele lijst van noten die allemaal inactief zijn. * Het grid is na deze methode inactief. * @param w aantal kolomen de ToneGrid heeft */ public void registerCallBack(int w) { this.width = w; this.grid = new ArrayList<List<Boolean>>(); for (int i = 0; i < w; i++) { List<Boolean> el = new ArrayList<Boolean>(); this.grid.add(el); for (int j = 0; j < height; j++) { el.add(false); } } this.isActive = false; } /** * Zet alle noten op inactief. */ public void clear() { for(List<Boolean> l1 : this.grid) { for(int i = 0; i < l1.size(); i++) { l1.set(i, false); } } } }
diddle/UED
code/src/playback/ToneGrid.java
1,665
/** * Tweede gedeelte van de registratie methode. * Registreerd het aantal kolomen en initaliseerd de dubbele lijst van noten die allemaal inactief zijn. * Het grid is na deze methode inactief. * @param w aantal kolomen de ToneGrid heeft */
block_comment
nl
/* Copyright Alexander Drechsel 2012 * Copyright Niels Kamp 2012 * Copyright Kasper Vaessen 2012 * Copyright Niels Visser 2012 * * This file is part of MusicTable. * * MusicTable 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. * * MusicTable 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 MusicTable. If not, see <http://www.gnu.org/licenses/>. */ package playback; import GUI.ParticlePanel; //import GUI.VisualizationPanel; import java.util.ArrayList; import java.util.List; import javax.sound.midi.Instrument; import javax.sound.midi.MidiChannel; /** * * @param <syncronized> */ public class ToneGrid { protected List<List<Boolean>> grid; protected int width; protected int height; protected boolean isActive; protected GridConfiguration gc; public ToneGrid(GridConfiguration gc) { this.height = 10; this.gc = gc; } /** * Wisselt de status van een gegeven noot van actief naar inactief or van inactief naar actief. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void toggleTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, !col.get(note)); } } /** * Wisselt de status van een gegeven noot naar actief of doet niets als de noot al actief is. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void activateTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, true); } } /** * Wisselt de status van een gegeven noot naar inactief of doet niets als de noot al inactief is. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord */ public void deactivateTone(int column, int note) { List<Boolean> col = this.grid.get(column); synchronized (col) { col.set(note, false); } } /** * Geeft de lijst van alle noten in de vorm van een lijst van kolomen met daarin de rijen. * @return */ public synchronized List<List<Boolean>> getAllTones() { List<List<Boolean>> result = new ArrayList<List<Boolean>>(); for (int i = 0; i < this.width; i++) { List<Boolean> el = new ArrayList<Boolean>(); result.add(el); for (int j = 0; j < this.height; j++) { el.add(this.grid.get(i).get(j)); } } return result; } /** * Geeft de status van een gegeven noot. * @param column welke kolom de noot aan behoord * @param note welke rij de noot aan behoord * @return true==actief;inactief==false */ public boolean getTone(int column, int note) { synchronized (this.grid) { return this.grid.get(column).get(note); } } /** * Delegeert aan gridconfig * @param column * @param vp */ public void playColumnTones(int column, ParticlePanel vp) { List<Integer> tones = this.getColumnTones(column); this.gc.playTones(tones, vp); } public List<Integer> getColumnTones(int x) { List<Boolean> notesArray = this.grid.get(x); List<Integer> notesList = new ArrayList<Integer>(); for(int i=0; i<notesArray.size(); i++) { if(notesArray.get(i)) notesList.add(i); } return notesList; } public void setConfiguration(GridConfiguration gc) { this.gc = gc; } public GridConfiguration getGridConfiguration() { return gc; } public boolean isIsActive() { return isActive; } public void setIsActive(boolean isActive) { this.isActive = isActive; } /** * Tweede gedeelte van<SUF>*/ public void registerCallBack(int w) { this.width = w; this.grid = new ArrayList<List<Boolean>>(); for (int i = 0; i < w; i++) { List<Boolean> el = new ArrayList<Boolean>(); this.grid.add(el); for (int j = 0; j < height; j++) { el.add(false); } } this.isActive = false; } /** * Zet alle noten op inactief. */ public void clear() { for(List<Boolean> l1 : this.grid) { for(int i = 0; i < l1.size(); i++) { l1.set(i, false); } } } }
True
False
1,560
551
70437_4
package nl.han.ise.DAO; import nl.han.ise.ConnectionFactory; import redis.clients.jedis.Jedis; import java.sql.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; public class RapportageDAO { private ConnectionFactory connectionFactory; private Jedis jedis; private Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); public RapportageDAO(){ connectionFactory = new ConnectionFactory(); jedis = new Jedis(connectionFactory.getRedisHost()); } //Vraagt de opgevraagde rapportage op via REDIS public String getRapportage(String rapportage){ String rapportageJson = jedis.get(rapportage); jedis.close(); return rapportageJson; } //Leegt de Redis database en vult hem opnieuw in vanuit de SQL database. public void addAndUpdateAllRapportages(){ logger.log(Level.INFO, "redis geupdated op " + DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now())); jedis.flushAll(); List<String> lijstRapportages = lijstRapportagesSql(); for(int i = 0; i <= lijstRapportages.size()-1; i++){ addOrUpdateRapportage(lijstRapportages.get(i)); } jedis.close(); } //Functie om een rapportage toe te voegen of te wijzigen public void addOrUpdateRapportage(String rapportage){ try (Connection connection = connectionFactory.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT (SELECT * FROM "+rapportage+" FOR JSON AUTO) AS Rapportage")) { ResultSet resultSet = statement.executeQuery(); if(resultSet.next()){ if(resultSet.getString("Rapportage") != null){ jedis.set(rapportage, resultSet.getString("Rapportage")); } } } catch (SQLException e) { logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN VAN RAPPORTAGES", e); throw new RuntimeException(e); } } //Functie om een lijst van rapportages op te halen van Jedis. public List<String> lijstRapportagesRedis(){ List<String> rapportageLijst = new ArrayList<>(); Set<String> keys = jedis.keys("RAPPORTAGE_*"); for (String key : keys) { rapportageLijst.add(key); } java.util.Collections.sort(rapportageLijst); jedis.close(); return rapportageLijst; } //Functie om een lijst van rapportages op te halen van SQL. public List<String> lijstRapportagesSql() { List<String> rapportageLijst = new ArrayList<>(); try (Connection connection = connectionFactory.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT name FROM sys.views WHERE name LIKE 'RAPPORTAGE_%'")) { ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { rapportageLijst.add(resultSet.getString("name")); } return rapportageLijst; } catch (SQLException e) { logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN LIJST VAN RAPPORTAGES", e); throw new RuntimeException(e); } } }
GGWPs/Filmcheques_API
filmcheques_API/src/main/java/nl/han/ise/DAO/RapportageDAO.java
1,014
//Functie om een lijst van rapportages op te halen van SQL.
line_comment
nl
package nl.han.ise.DAO; import nl.han.ise.ConnectionFactory; import redis.clients.jedis.Jedis; import java.sql.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; public class RapportageDAO { private ConnectionFactory connectionFactory; private Jedis jedis; private Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); public RapportageDAO(){ connectionFactory = new ConnectionFactory(); jedis = new Jedis(connectionFactory.getRedisHost()); } //Vraagt de opgevraagde rapportage op via REDIS public String getRapportage(String rapportage){ String rapportageJson = jedis.get(rapportage); jedis.close(); return rapportageJson; } //Leegt de Redis database en vult hem opnieuw in vanuit de SQL database. public void addAndUpdateAllRapportages(){ logger.log(Level.INFO, "redis geupdated op " + DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now())); jedis.flushAll(); List<String> lijstRapportages = lijstRapportagesSql(); for(int i = 0; i <= lijstRapportages.size()-1; i++){ addOrUpdateRapportage(lijstRapportages.get(i)); } jedis.close(); } //Functie om een rapportage toe te voegen of te wijzigen public void addOrUpdateRapportage(String rapportage){ try (Connection connection = connectionFactory.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT (SELECT * FROM "+rapportage+" FOR JSON AUTO) AS Rapportage")) { ResultSet resultSet = statement.executeQuery(); if(resultSet.next()){ if(resultSet.getString("Rapportage") != null){ jedis.set(rapportage, resultSet.getString("Rapportage")); } } } catch (SQLException e) { logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN VAN RAPPORTAGES", e); throw new RuntimeException(e); } } //Functie om een lijst van rapportages op te halen van Jedis. public List<String> lijstRapportagesRedis(){ List<String> rapportageLijst = new ArrayList<>(); Set<String> keys = jedis.keys("RAPPORTAGE_*"); for (String key : keys) { rapportageLijst.add(key); } java.util.Collections.sort(rapportageLijst); jedis.close(); return rapportageLijst; } //Functie om<SUF> public List<String> lijstRapportagesSql() { List<String> rapportageLijst = new ArrayList<>(); try (Connection connection = connectionFactory.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT name FROM sys.views WHERE name LIKE 'RAPPORTAGE_%'")) { ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { rapportageLijst.add(resultSet.getString("name")); } return rapportageLijst; } catch (SQLException e) { logger.log(Level.SEVERE, "SQL EXCEPTION BIJ OPHALEN LIJST VAN RAPPORTAGES", e); throw new RuntimeException(e); } } }
True
False
1,561
3,875
126655_20
package com.programmeren4.turnahead.server.model.dao;_x000D_ _x000D_ import java.sql.Connection;_x000D_ import java.sql.ResultSet;_x000D_ import java.sql.SQLException;_x000D_ import java.util.ArrayList;_x000D_ import java.util.List;_x000D_ _x000D_ import com.programmeren4.turnahead.server.database.DBConnector;_x000D_ import com.programmeren4.turnahead.shared.dto.ItemDTO;_x000D_ import com.programmeren4.turnahead.shared.dto.KarakterDTO;_x000D_ import com.programmeren4.turnahead.shared.exception.DAOException;_x000D_ _x000D_ public class KarakterDataDao {_x000D_ // attributen_x000D_ private Connection conn;_x000D_ private String sql;_x000D_ _x000D_ // private String tabelnaam = "KARAKTER";_x000D_ // private String[] tabelvelden =_x000D_ // {"CHARACTERID","CHARACTERNAME","CURRENTLOCATION", "CREATION_DATE", "LASTUSE_DATE", "USERID","LOCATIONID"};_x000D_ _x000D_ // constructor_x000D_ public KarakterDataDao() {_x000D_ }_x000D_ _x000D_ // getters en setters_x000D_ _x000D_ // SELECT - UPDATE - INSERT - DELETE_x000D_ /**_x000D_ * Gegevens van een karakter opvragen (SELECT)_x000D_ */_x000D_ public KarakterDTO getKarakterData(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ KarakterDTO karakterReturn = null;_x000D_ ResultSet rs = null;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();_x000D_ rs = conn.createStatement().executeQuery(sql);_x000D_ if (rs.next()) {_x000D_ karakterReturn = new KarakterDTO();_x000D_ karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));_x000D_ karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));_x000D_ karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));_x000D_ karakterReturn.setUserId(rs.getLong("USERID"));_x000D_ karakterReturn.setLocationId(rs.getLong("LOCATIONID"));_x000D_ }_x000D_ if (!rs.isBeforeFirst() ) { _x000D_ System.out.println("No data"); _x000D_ } _x000D_ _x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return karakterReturn;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Karakter toevoegen (INSERT) of wijzigen (UPDATE)_x000D_ */_x000D_ public void addKarakterData(KarakterDTO karakterData) throws DAOException {_x000D_ // Controle (Bestaat Karakter al in tabel Karakter ?)_x000D_ boolean karakterTest = this.VerifyKarakterId(karakterData);_x000D_ _x000D_ // Naam en id van eerste Locatie in tabel LOCATION ophalen_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ _x000D_ if (karakterTest == true) {_x000D_ // JA -> UPDATE bestaande record_x000D_ // "UPDATE programmeren4.KARAKTER SET_x000D_ // *veld='karakterData.getX()',*veld='karakterData.getY()',_x000D_ // "WHERE KARAKTERID=" + karakterData.getKarakterId();_x000D_ String sql = "UPDATE programmeren4.KARAKTER SET ";_x000D_ sql += "CHARACTERNAME='" + karakterData.getKarakterName().toUpperCase() + "', ";_x000D_ sql += " CURRENTLOCATION='" + karakterData.getCurrentLocation().toUpperCase() + "'";_x000D_ sql += " WHERE CHARACTERID=" + karakterData.getKarakterId();_x000D_ _x000D_ conn.createStatement().executeUpdate(sql);_x000D_ } else {_x000D_ // NEEN -> Karakter toevoegen aan de database>_x000D_ // INSERT INTO programmeren4.KARAKTER(Columns db) VALUES_x000D_ // (karakterData.getXXX(),_x000D_ // karakterData.getYYY(), karakterData.getZZZ())_x000D_ String sql = "INSERT INTO programmeren4.KARAKTER(";_x000D_ sql += "CHARACTERNAME, CURRENTLOCATION, USERID, LOCATIONID) VALUES ('";_x000D_ sql += karakterData.getKarakterName() + "', '";_x000D_ sql += "SMIDSE', '";_x000D_ sql += karakterData.getUserId() + "','"; // UserId van de User die Karakter_x000D_ sql += "1";_x000D_ sql += "')";_x000D_ conn.createStatement().executeUpdate(sql);_x000D_ }_x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Karakter verwijderen (DELETE)_x000D_ */_x000D_ public void deleteKarakterData(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ sql = "DELETE FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();_x000D_ conn.createStatement().executeUpdate(sql);_x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ }_x000D_ _x000D_ // LIST_x000D_ /**_x000D_ * Lijst van alle karakters (LIST ALL)_x000D_ */_x000D_ public List<KarakterDTO> getKarakters() throws DAOException {_x000D_ String query = "SELECT * FROM programmeren4.KARAKTER";_x000D_ List<KarakterDTO> list = new ArrayList<KarakterDTO>();_x000D_ KarakterDTO karakterReturn = null;_x000D_ ResultSet rs = null;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ rs = conn.createStatement().executeQuery(query);_x000D_ _x000D_ while (rs.next()) {_x000D_ karakterReturn = new KarakterDTO();_x000D_ karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));_x000D_ karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));_x000D_ karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));_x000D_ karakterReturn.setUserId(rs.getLong("USERID"));_x000D_ karakterReturn.setLocationId(rs.getLong("LOCATIONID"));_x000D_ _x000D_ list.add(karakterReturn);_x000D_ }_x000D_ if (list.isEmpty()) {_x000D_ System.out.println("List fetched from database is empty.");_x000D_ }_x000D_ } catch (SQLException se) {_x000D_ // Handle errors for JDBC_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return list;_x000D_ }_x000D_ _x000D_ /**_x000D_ * LIST BY USER - Lijst van alle karakters voor één UserId_x000D_ */_x000D_ public List<KarakterDTO> getKaraktersOfUserId(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ List<KarakterDTO> list = new ArrayList<KarakterDTO>();_x000D_ KarakterDTO karakterReturn = null;_x000D_ ResultSet rs = null;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ String query = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID="_x000D_ + karakterData.getUserId();_x000D_ rs = conn.createStatement().executeQuery(query);_x000D_ _x000D_ while (rs.next()) {_x000D_ karakterReturn = new KarakterDTO();_x000D_ karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));_x000D_ karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));_x000D_ karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));_x000D_ karakterReturn.setUserId(rs.getLong("USERID"));_x000D_ karakterReturn.setLocationId(rs.getLong("LOCATIONID"));_x000D_ System.out.println(karakterReturn);_x000D_ list.add(karakterReturn);_x000D_ }_x000D_ if (list.isEmpty()) {_x000D_ System.out.println("List fetched from database is empty.");_x000D_ } _x000D_ } catch (SQLException se) {_x000D_ // Handle errors for JDBC_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return list;_x000D_ }_x000D_ _x000D_ /**_x000D_ * LIST BY LOCATION - Lijst van alle karakters voor één LocationId_x000D_ */_x000D_ public List<KarakterDTO> getKaraktersOfLocationId(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ List<KarakterDTO> list = new ArrayList<KarakterDTO>();_x000D_ KarakterDTO karakterReturn = null;_x000D_ ResultSet rs = null;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ String query = "SELECT * FROM programmeren4.KARAKTER WHERE LOCATIONID="_x000D_ + karakterData.getLocationId();_x000D_ rs = conn.createStatement().executeQuery(query);_x000D_ _x000D_ while (rs.next()) {_x000D_ karakterReturn = new KarakterDTO();_x000D_ karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));_x000D_ karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));_x000D_ karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));_x000D_ karakterReturn.setUserId(rs.getLong("USERID"));_x000D_ karakterReturn.setLocationId(rs.getLong("LOCATIONID"));_x000D_ _x000D_ list.add(karakterReturn);_x000D_ }_x000D_ if (list.isEmpty()) {_x000D_ System.out.println("List fetched from database is empty.");_x000D_ }_x000D_ } catch (SQLException se) {_x000D_ // Handle errors for JDBC_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return list;_x000D_ }_x000D_ _x000D_ _x000D_ //Itemownership_x000D_ /**_x000D_ * TODO - verify_x000D_ * Methode om een item toe te wijzen aan een karakter_x000D_ */_x000D_ public void AllocateItemToKarakter(KarakterDTO karakterData, ItemDTO itemData){_x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn(); _x000D_ sql = "UPDATE programmeren4.ITEMOWNERSHIP SET ";_x000D_ sql += "CHARACTERID='" + karakterData.getKarakterId() + "', ";_x000D_ sql += "LOCATIONID=null ";_x000D_ sql += "WHERE ITEMID=" + itemData.getItemId();_x000D_ conn.createStatement().executeUpdate(sql);_x000D_ _x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ }_x000D_ _x000D_ _x000D_ // Overige methodes_x000D_ /**_x000D_ * Methode om te controleren of een karakter al aanwezig is (in de database)_x000D_ * (op basis van een KarakterId)_x000D_ */_x000D_ public boolean VerifyKarakterId(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ ResultSet rs = null;_x000D_ boolean inDatabase = false;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();_x000D_ rs = conn.createStatement().executeQuery(sql);_x000D_ // System.out.println("karakterData KarakterID: " +_x000D_ // userData.getUserId());_x000D_ _x000D_ if (rs.next()) {_x000D_ long a = new Long(rs.getLong("CHARACTERID"));_x000D_ // System.out.println(a);_x000D_ if (a == karakterData.getKarakterId()) {_x000D_ inDatabase = true;_x000D_ System.out.println("IF-true");_x000D_ } else {_x000D_ inDatabase = false;_x000D_ System.out.println("IF-false");_x000D_ }_x000D_ }_x000D_ System.out.println(inDatabase);_x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return inDatabase;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Methode om te controleren of een Karakter al aanwezig is in de database_x000D_ * (op basis van Karakternaam)_x000D_ */_x000D_ public boolean VerifyKarakterNaam(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ ResultSet rs = null;_x000D_ boolean inDatabase = false;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERNAME='"_x000D_ + karakterData.getKarakterName().toUpperCase() + "'";_x000D_ rs = conn.createStatement().executeQuery(sql);_x000D_ // System.out.println("karakterData KarakterID: " + karakterData.getKarakterId());_x000D_ _x000D_ if (rs.next()) {_x000D_ if (rs.getRow() == 1_x000D_ & new String(rs.getString("CHARACTERNAME").toUpperCase()).equals(karakterData.getKarakterName().toUpperCase())) {_x000D_ inDatabase = true;_x000D_ } else {_x000D_ inDatabase = false;_x000D_ }_x000D_ }_x000D_ _x000D_ System.out.println(inDatabase);_x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return inDatabase;_x000D_ }_x000D_ _x000D_ }_x000D_
oliviervanroey/turnahead
src/main/java/com/programmeren4/turnahead/server/model/dao/KarakterDataDao.java
4,148
/**_x000D_ * LIST BY LOCATION - Lijst van alle karakters voor één LocationId_x000D_ */
block_comment
nl
package com.programmeren4.turnahead.server.model.dao;_x000D_ _x000D_ import java.sql.Connection;_x000D_ import java.sql.ResultSet;_x000D_ import java.sql.SQLException;_x000D_ import java.util.ArrayList;_x000D_ import java.util.List;_x000D_ _x000D_ import com.programmeren4.turnahead.server.database.DBConnector;_x000D_ import com.programmeren4.turnahead.shared.dto.ItemDTO;_x000D_ import com.programmeren4.turnahead.shared.dto.KarakterDTO;_x000D_ import com.programmeren4.turnahead.shared.exception.DAOException;_x000D_ _x000D_ public class KarakterDataDao {_x000D_ // attributen_x000D_ private Connection conn;_x000D_ private String sql;_x000D_ _x000D_ // private String tabelnaam = "KARAKTER";_x000D_ // private String[] tabelvelden =_x000D_ // {"CHARACTERID","CHARACTERNAME","CURRENTLOCATION", "CREATION_DATE", "LASTUSE_DATE", "USERID","LOCATIONID"};_x000D_ _x000D_ // constructor_x000D_ public KarakterDataDao() {_x000D_ }_x000D_ _x000D_ // getters en setters_x000D_ _x000D_ // SELECT - UPDATE - INSERT - DELETE_x000D_ /**_x000D_ * Gegevens van een karakter opvragen (SELECT)_x000D_ */_x000D_ public KarakterDTO getKarakterData(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ KarakterDTO karakterReturn = null;_x000D_ ResultSet rs = null;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();_x000D_ rs = conn.createStatement().executeQuery(sql);_x000D_ if (rs.next()) {_x000D_ karakterReturn = new KarakterDTO();_x000D_ karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));_x000D_ karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));_x000D_ karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));_x000D_ karakterReturn.setUserId(rs.getLong("USERID"));_x000D_ karakterReturn.setLocationId(rs.getLong("LOCATIONID"));_x000D_ }_x000D_ if (!rs.isBeforeFirst() ) { _x000D_ System.out.println("No data"); _x000D_ } _x000D_ _x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return karakterReturn;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Karakter toevoegen (INSERT) of wijzigen (UPDATE)_x000D_ */_x000D_ public void addKarakterData(KarakterDTO karakterData) throws DAOException {_x000D_ // Controle (Bestaat Karakter al in tabel Karakter ?)_x000D_ boolean karakterTest = this.VerifyKarakterId(karakterData);_x000D_ _x000D_ // Naam en id van eerste Locatie in tabel LOCATION ophalen_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ _x000D_ if (karakterTest == true) {_x000D_ // JA -> UPDATE bestaande record_x000D_ // "UPDATE programmeren4.KARAKTER SET_x000D_ // *veld='karakterData.getX()',*veld='karakterData.getY()',_x000D_ // "WHERE KARAKTERID=" + karakterData.getKarakterId();_x000D_ String sql = "UPDATE programmeren4.KARAKTER SET ";_x000D_ sql += "CHARACTERNAME='" + karakterData.getKarakterName().toUpperCase() + "', ";_x000D_ sql += " CURRENTLOCATION='" + karakterData.getCurrentLocation().toUpperCase() + "'";_x000D_ sql += " WHERE CHARACTERID=" + karakterData.getKarakterId();_x000D_ _x000D_ conn.createStatement().executeUpdate(sql);_x000D_ } else {_x000D_ // NEEN -> Karakter toevoegen aan de database>_x000D_ // INSERT INTO programmeren4.KARAKTER(Columns db) VALUES_x000D_ // (karakterData.getXXX(),_x000D_ // karakterData.getYYY(), karakterData.getZZZ())_x000D_ String sql = "INSERT INTO programmeren4.KARAKTER(";_x000D_ sql += "CHARACTERNAME, CURRENTLOCATION, USERID, LOCATIONID) VALUES ('";_x000D_ sql += karakterData.getKarakterName() + "', '";_x000D_ sql += "SMIDSE', '";_x000D_ sql += karakterData.getUserId() + "','"; // UserId van de User die Karakter_x000D_ sql += "1";_x000D_ sql += "')";_x000D_ conn.createStatement().executeUpdate(sql);_x000D_ }_x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Karakter verwijderen (DELETE)_x000D_ */_x000D_ public void deleteKarakterData(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ sql = "DELETE FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();_x000D_ conn.createStatement().executeUpdate(sql);_x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ }_x000D_ _x000D_ // LIST_x000D_ /**_x000D_ * Lijst van alle karakters (LIST ALL)_x000D_ */_x000D_ public List<KarakterDTO> getKarakters() throws DAOException {_x000D_ String query = "SELECT * FROM programmeren4.KARAKTER";_x000D_ List<KarakterDTO> list = new ArrayList<KarakterDTO>();_x000D_ KarakterDTO karakterReturn = null;_x000D_ ResultSet rs = null;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ rs = conn.createStatement().executeQuery(query);_x000D_ _x000D_ while (rs.next()) {_x000D_ karakterReturn = new KarakterDTO();_x000D_ karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));_x000D_ karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));_x000D_ karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));_x000D_ karakterReturn.setUserId(rs.getLong("USERID"));_x000D_ karakterReturn.setLocationId(rs.getLong("LOCATIONID"));_x000D_ _x000D_ list.add(karakterReturn);_x000D_ }_x000D_ if (list.isEmpty()) {_x000D_ System.out.println("List fetched from database is empty.");_x000D_ }_x000D_ } catch (SQLException se) {_x000D_ // Handle errors for JDBC_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return list;_x000D_ }_x000D_ _x000D_ /**_x000D_ * LIST BY USER - Lijst van alle karakters voor één UserId_x000D_ */_x000D_ public List<KarakterDTO> getKaraktersOfUserId(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ List<KarakterDTO> list = new ArrayList<KarakterDTO>();_x000D_ KarakterDTO karakterReturn = null;_x000D_ ResultSet rs = null;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ String query = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID="_x000D_ + karakterData.getUserId();_x000D_ rs = conn.createStatement().executeQuery(query);_x000D_ _x000D_ while (rs.next()) {_x000D_ karakterReturn = new KarakterDTO();_x000D_ karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));_x000D_ karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));_x000D_ karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));_x000D_ karakterReturn.setUserId(rs.getLong("USERID"));_x000D_ karakterReturn.setLocationId(rs.getLong("LOCATIONID"));_x000D_ System.out.println(karakterReturn);_x000D_ list.add(karakterReturn);_x000D_ }_x000D_ if (list.isEmpty()) {_x000D_ System.out.println("List fetched from database is empty.");_x000D_ } _x000D_ } catch (SQLException se) {_x000D_ // Handle errors for JDBC_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return list;_x000D_ }_x000D_ _x000D_ /**_x000D_ * LIST BY LOCATION<SUF>*/_x000D_ public List<KarakterDTO> getKaraktersOfLocationId(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ List<KarakterDTO> list = new ArrayList<KarakterDTO>();_x000D_ KarakterDTO karakterReturn = null;_x000D_ ResultSet rs = null;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ String query = "SELECT * FROM programmeren4.KARAKTER WHERE LOCATIONID="_x000D_ + karakterData.getLocationId();_x000D_ rs = conn.createStatement().executeQuery(query);_x000D_ _x000D_ while (rs.next()) {_x000D_ karakterReturn = new KarakterDTO();_x000D_ karakterReturn.setKarakterId(rs.getLong("CHARACTERID"));_x000D_ karakterReturn.setKarakterName(rs.getString("CHARACTERNAME"));_x000D_ karakterReturn.setCurrentLocation(rs.getString("CURRENTLOCATION"));_x000D_ karakterReturn.setUserId(rs.getLong("USERID"));_x000D_ karakterReturn.setLocationId(rs.getLong("LOCATIONID"));_x000D_ _x000D_ list.add(karakterReturn);_x000D_ }_x000D_ if (list.isEmpty()) {_x000D_ System.out.println("List fetched from database is empty.");_x000D_ }_x000D_ } catch (SQLException se) {_x000D_ // Handle errors for JDBC_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return list;_x000D_ }_x000D_ _x000D_ _x000D_ //Itemownership_x000D_ /**_x000D_ * TODO - verify_x000D_ * Methode om een item toe te wijzen aan een karakter_x000D_ */_x000D_ public void AllocateItemToKarakter(KarakterDTO karakterData, ItemDTO itemData){_x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn(); _x000D_ sql = "UPDATE programmeren4.ITEMOWNERSHIP SET ";_x000D_ sql += "CHARACTERID='" + karakterData.getKarakterId() + "', ";_x000D_ sql += "LOCATIONID=null ";_x000D_ sql += "WHERE ITEMID=" + itemData.getItemId();_x000D_ conn.createStatement().executeUpdate(sql);_x000D_ _x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ }_x000D_ _x000D_ _x000D_ // Overige methodes_x000D_ /**_x000D_ * Methode om te controleren of een karakter al aanwezig is (in de database)_x000D_ * (op basis van een KarakterId)_x000D_ */_x000D_ public boolean VerifyKarakterId(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ ResultSet rs = null;_x000D_ boolean inDatabase = false;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERID=" + karakterData.getKarakterId();_x000D_ rs = conn.createStatement().executeQuery(sql);_x000D_ // System.out.println("karakterData KarakterID: " +_x000D_ // userData.getUserId());_x000D_ _x000D_ if (rs.next()) {_x000D_ long a = new Long(rs.getLong("CHARACTERID"));_x000D_ // System.out.println(a);_x000D_ if (a == karakterData.getKarakterId()) {_x000D_ inDatabase = true;_x000D_ System.out.println("IF-true");_x000D_ } else {_x000D_ inDatabase = false;_x000D_ System.out.println("IF-false");_x000D_ }_x000D_ }_x000D_ System.out.println(inDatabase);_x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return inDatabase;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Methode om te controleren of een Karakter al aanwezig is in de database_x000D_ * (op basis van Karakternaam)_x000D_ */_x000D_ public boolean VerifyKarakterNaam(KarakterDTO karakterData)_x000D_ throws DAOException {_x000D_ ResultSet rs = null;_x000D_ boolean inDatabase = false;_x000D_ _x000D_ try {_x000D_ DBConnector.getInstance().init();_x000D_ this.conn = DBConnector.getInstance().getConn();_x000D_ sql = "SELECT * FROM programmeren4.KARAKTER WHERE CHARACTERNAME='"_x000D_ + karakterData.getKarakterName().toUpperCase() + "'";_x000D_ rs = conn.createStatement().executeQuery(sql);_x000D_ // System.out.println("karakterData KarakterID: " + karakterData.getKarakterId());_x000D_ _x000D_ if (rs.next()) {_x000D_ if (rs.getRow() == 1_x000D_ & new String(rs.getString("CHARACTERNAME").toUpperCase()).equals(karakterData.getKarakterName().toUpperCase())) {_x000D_ inDatabase = true;_x000D_ } else {_x000D_ inDatabase = false;_x000D_ }_x000D_ }_x000D_ _x000D_ System.out.println(inDatabase);_x000D_ } catch (SQLException se) {_x000D_ se.printStackTrace();_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ } finally {_x000D_ DBConnector.getInstance().close(rs);_x000D_ DBConnector.getInstance().closeConn();_x000D_ }_x000D_ return inDatabase;_x000D_ }_x000D_ _x000D_ }_x000D_
True
False
1,562
3,017
14615_8
package nl.atd.model; import java.util.Calendar; /** * Auto data object * * @author ATD Developers * */ public class Auto { private String merk; private String model; private int bouwjaar; private Calendar laatsteBeurt; private String kenteken; public Auto(String mk, String ml, int bj, Calendar lb) { this.merk = mk; this.model = ml; this.bouwjaar = bj; this.kenteken = ""; this.laatsteBeurt = lb; } /** * Is laatste beurt na 6 maanden geweest? * * @return na 6 maanden? */ public boolean isLaatsteBeurtRedelijk() { if(this.laatsteBeurt == null) return false; Calendar streef = Calendar.getInstance(); Calendar lb = (Calendar)laatsteBeurt.clone(); if(lb == null) return false; streef.add(Calendar.MONTH, -6); return !lb.before(streef); } /** * Get merk * * @return merk */ public String getMerk() { return merk; } /** * Get model * * @return model */ public String getModel() { return model; } /** * Get bouwjaar * * @return bouwjaar */ public int getBouwjaar() { return bouwjaar; } /** * Get laatste beurt datum * * @return Datum van laatste beurt */ public Calendar getLaatsteBeurt() { return laatsteBeurt; } /** * Set laatste beurt datum * * @param cal nieuwe datum */ public void setLaatsteBeurt(Calendar cal) { this.laatsteBeurt = cal; } /** * Get Kenteken van auto * * @return Kenteken */ public String getKenteken() { return this.kenteken; } /** * Set Kenteken van auto * * @param Nieuw * kenteken */ public void setKenteken(String nieuwKent) { this.kenteken = nieuwKent; } @Override public String toString() { return merk + " " + model; } @Override public boolean equals(Object ander) { boolean b; if (ander instanceof Auto) { b = true; } else { b = false; } b = b && (this.merk.equals(((Auto) ander).getMerk())); b = b && (this.model.equals(((Auto) ander).getModel())); b = b && (this.bouwjaar == ((Auto) ander).getBouwjaar()); b = b && (this.kenteken.equals(((Auto) ander).getKenteken())); // Calendar vergelijken, DAY.OF.YEAR - YEAR - HOURS : MINUTES b = b && ((this.laatsteBeurt == null && ((Auto)ander).getLaatsteBeurt() == null) || ((this.laatsteBeurt).get(Calendar.YEAR) == ((Auto)ander).getLaatsteBeurt().get(Calendar.YEAR) && (this.laatsteBeurt).get(Calendar.HOUR_OF_DAY) == ((Auto)ander).getLaatsteBeurt().get(Calendar.HOUR_OF_DAY) && (this.laatsteBeurt).get(Calendar.MINUTE) == ((Auto)ander).getLaatsteBeurt().get(Calendar.MINUTE))); return b; } }
hu-team/atd-garagesysteem
src/nl/atd/model/Auto.java
1,041
/** * Set Kenteken van auto * * @param Nieuw * kenteken */
block_comment
nl
package nl.atd.model; import java.util.Calendar; /** * Auto data object * * @author ATD Developers * */ public class Auto { private String merk; private String model; private int bouwjaar; private Calendar laatsteBeurt; private String kenteken; public Auto(String mk, String ml, int bj, Calendar lb) { this.merk = mk; this.model = ml; this.bouwjaar = bj; this.kenteken = ""; this.laatsteBeurt = lb; } /** * Is laatste beurt na 6 maanden geweest? * * @return na 6 maanden? */ public boolean isLaatsteBeurtRedelijk() { if(this.laatsteBeurt == null) return false; Calendar streef = Calendar.getInstance(); Calendar lb = (Calendar)laatsteBeurt.clone(); if(lb == null) return false; streef.add(Calendar.MONTH, -6); return !lb.before(streef); } /** * Get merk * * @return merk */ public String getMerk() { return merk; } /** * Get model * * @return model */ public String getModel() { return model; } /** * Get bouwjaar * * @return bouwjaar */ public int getBouwjaar() { return bouwjaar; } /** * Get laatste beurt datum * * @return Datum van laatste beurt */ public Calendar getLaatsteBeurt() { return laatsteBeurt; } /** * Set laatste beurt datum * * @param cal nieuwe datum */ public void setLaatsteBeurt(Calendar cal) { this.laatsteBeurt = cal; } /** * Get Kenteken van auto * * @return Kenteken */ public String getKenteken() { return this.kenteken; } /** * Set Kenteken van<SUF>*/ public void setKenteken(String nieuwKent) { this.kenteken = nieuwKent; } @Override public String toString() { return merk + " " + model; } @Override public boolean equals(Object ander) { boolean b; if (ander instanceof Auto) { b = true; } else { b = false; } b = b && (this.merk.equals(((Auto) ander).getMerk())); b = b && (this.model.equals(((Auto) ander).getModel())); b = b && (this.bouwjaar == ((Auto) ander).getBouwjaar()); b = b && (this.kenteken.equals(((Auto) ander).getKenteken())); // Calendar vergelijken, DAY.OF.YEAR - YEAR - HOURS : MINUTES b = b && ((this.laatsteBeurt == null && ((Auto)ander).getLaatsteBeurt() == null) || ((this.laatsteBeurt).get(Calendar.YEAR) == ((Auto)ander).getLaatsteBeurt().get(Calendar.YEAR) && (this.laatsteBeurt).get(Calendar.HOUR_OF_DAY) == ((Auto)ander).getLaatsteBeurt().get(Calendar.HOUR_OF_DAY) && (this.laatsteBeurt).get(Calendar.MINUTE) == ((Auto)ander).getLaatsteBeurt().get(Calendar.MINUTE))); return b; } }
True
False
1,563
382
38772_0
package Facade; public class TestBankAccount { public static void main(String[] args) { //nieuwe facade maken en bank account nr 123456 gebruiken met code 1234 BankAccountFacade accessingBank = new BankAccountFacade(123456, 1234); accessingBank.withDrawCash(50.00); accessingBank.withDrawCash(900.00); accessingBank.depositCash(200.00); accessingBank.depositCash(150.00); } }
DalderupMaurice/Facade_Pattern_Demo
src/Facade/TestBankAccount.java
143
//nieuwe facade maken en bank account nr 123456 gebruiken met code 1234
line_comment
nl
package Facade; public class TestBankAccount { public static void main(String[] args) { //nieuwe facade<SUF> BankAccountFacade accessingBank = new BankAccountFacade(123456, 1234); accessingBank.withDrawCash(50.00); accessingBank.withDrawCash(900.00); accessingBank.depositCash(200.00); accessingBank.depositCash(150.00); } }
True
False
1,566
4,655
127401_1
package com.mybaggage.controllers; import com.jfoenix.controls.JFXButton; import com.mybaggage.Utilities; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.animation.FadeTransition; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javafx.util.Duration; /** * * @author Ludo Bak */ public class AdminController implements Initializable { @FXML private AnchorPane holderPane; @FXML private JFXButton btnHome; @FXML private Button btnLogOut; @FXML private Button btnExit; @FXML private Button btnHelpdesk; @FXML private Button btnBagage; @FXML private Button btnUM; @FXML private Button btnRegistreerSchadevergoeding; @FXML private Button btnBagageZoeken; @FXML private Button btnBagageOverzicht; @FXML private Button btnBagageToevoegen; AnchorPane bagageOverzicht, bagageZoeken, faq, helpdesk, fxml2, inlogscherm, UM, registreerSchadevergoeding; //Zet waarden leeg en maakt nieuwe objecten via classes. Stage dialogStage = new Stage(); Scene scene; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; ResultSet resultSet2 = null; @Override public void initialize(URL url, ResourceBundle rb) { //Load all fxmls in a cache try { bagageOverzicht = FXMLLoader.load(getClass().getResource("BagageOverzicht.fxml")); bagageZoeken = FXMLLoader.load(getClass().getResource("FXML2.fxml")); inlogscherm = FXMLLoader.load(getClass().getResource("Inlogscherm.fxml")); faq = FXMLLoader.load(getClass().getResource("FAQ.fxml")); fxml2 = FXMLLoader.load(getClass().getResource("Rapportage.fxml")); UM = FXMLLoader.load(getClass().getResource("UM.fxml")); helpdesk = FXMLLoader.load(getClass().getResource("HelpdeskAdmin.fxml")); registreerSchadevergoeding = FXMLLoader.load(getClass().getResource("RegistreerSchadevergoeding.fxml")); setNode(fxml2); } catch (IOException ex) { Logger.getLogger(MedewerkerController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void logOff(ActionEvent event) throws IOException { Node source = (Node) event.getSource(); dialogStage = (Stage) source.getScene().getWindow(); dialogStage.close(); scene = new Scene((Parent) FXMLLoader.load(getClass().getResource("Inlogscherm.fxml"))); dialogStage.setScene(scene); dialogStage.show(); } @FXML private void exit(ActionEvent event) throws IOException { Stage stage = (Stage) btnExit.getScene().getWindow(); stage.close(); } //Set selected node to a content holder private void setNode(Node node) { holderPane.getChildren().clear(); holderPane.getChildren().add((Node) node); FadeTransition ft = new FadeTransition(Duration.millis(1500)); ft.setNode(node); ft.setFromValue(0.1); ft.setToValue(1); ft.setCycleCount(1); ft.setAutoReverse(false); ft.play(); } /** * Keyboard-shortcuts methode om te navigeren met F-Keys. * * @author Ismail Bahar (500783727) */ @FXML private void keyPressed(KeyEvent event) throws IOException { switch (event.getCode()) { case F2: Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane); break; case F3: Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane); break; case F4: Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane); break; case F5: Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane); break; case F6: Utilities.switchSchermNaarFXML("FAQ.fxml", holderPane); break; case F7: Utilities.switchSchermNaarFXML("HelpdeskAdmin.fxml", holderPane); break; case F8: Utilities.switchSchermNaarFXML("UM.fxml", holderPane); break; default: break; } } @FXML private void openHome(ActionEvent event) { setNode(fxml2); } @FXML private void openBagageToevoegen(ActionEvent event) throws IOException { //setNode(bagageToevoegen); Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane); } @FXML private void openBagageOverzicht(ActionEvent event) throws IOException { //setNode(bagageOverzicht); Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane); } @FXML private void openBagageZoeken(ActionEvent event) throws IOException { //setNode(bagageZoeken); Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane); } @FXML private void openContact(ActionEvent event) { setNode(faq); } @FXML private void openHelpdesk(ActionEvent event) { setNode(helpdesk); } @FXML private void openUM(ActionEvent event) { setNode(UM); } @FXML private void openRegistreerSchadevergoeding(ActionEvent event) throws IOException { //setNode(registreerSchadevergoeding); Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane); } }
vriesr032/MyBaggage
src/main/java/com/mybaggage/controllers/AdminController.java
1,963
//Zet waarden leeg en maakt nieuwe objecten via classes.
line_comment
nl
package com.mybaggage.controllers; import com.jfoenix.controls.JFXButton; import com.mybaggage.Utilities; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.animation.FadeTransition; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javafx.util.Duration; /** * * @author Ludo Bak */ public class AdminController implements Initializable { @FXML private AnchorPane holderPane; @FXML private JFXButton btnHome; @FXML private Button btnLogOut; @FXML private Button btnExit; @FXML private Button btnHelpdesk; @FXML private Button btnBagage; @FXML private Button btnUM; @FXML private Button btnRegistreerSchadevergoeding; @FXML private Button btnBagageZoeken; @FXML private Button btnBagageOverzicht; @FXML private Button btnBagageToevoegen; AnchorPane bagageOverzicht, bagageZoeken, faq, helpdesk, fxml2, inlogscherm, UM, registreerSchadevergoeding; //Zet waarden<SUF> Stage dialogStage = new Stage(); Scene scene; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; ResultSet resultSet2 = null; @Override public void initialize(URL url, ResourceBundle rb) { //Load all fxmls in a cache try { bagageOverzicht = FXMLLoader.load(getClass().getResource("BagageOverzicht.fxml")); bagageZoeken = FXMLLoader.load(getClass().getResource("FXML2.fxml")); inlogscherm = FXMLLoader.load(getClass().getResource("Inlogscherm.fxml")); faq = FXMLLoader.load(getClass().getResource("FAQ.fxml")); fxml2 = FXMLLoader.load(getClass().getResource("Rapportage.fxml")); UM = FXMLLoader.load(getClass().getResource("UM.fxml")); helpdesk = FXMLLoader.load(getClass().getResource("HelpdeskAdmin.fxml")); registreerSchadevergoeding = FXMLLoader.load(getClass().getResource("RegistreerSchadevergoeding.fxml")); setNode(fxml2); } catch (IOException ex) { Logger.getLogger(MedewerkerController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void logOff(ActionEvent event) throws IOException { Node source = (Node) event.getSource(); dialogStage = (Stage) source.getScene().getWindow(); dialogStage.close(); scene = new Scene((Parent) FXMLLoader.load(getClass().getResource("Inlogscherm.fxml"))); dialogStage.setScene(scene); dialogStage.show(); } @FXML private void exit(ActionEvent event) throws IOException { Stage stage = (Stage) btnExit.getScene().getWindow(); stage.close(); } //Set selected node to a content holder private void setNode(Node node) { holderPane.getChildren().clear(); holderPane.getChildren().add((Node) node); FadeTransition ft = new FadeTransition(Duration.millis(1500)); ft.setNode(node); ft.setFromValue(0.1); ft.setToValue(1); ft.setCycleCount(1); ft.setAutoReverse(false); ft.play(); } /** * Keyboard-shortcuts methode om te navigeren met F-Keys. * * @author Ismail Bahar (500783727) */ @FXML private void keyPressed(KeyEvent event) throws IOException { switch (event.getCode()) { case F2: Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane); break; case F3: Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane); break; case F4: Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane); break; case F5: Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane); break; case F6: Utilities.switchSchermNaarFXML("FAQ.fxml", holderPane); break; case F7: Utilities.switchSchermNaarFXML("HelpdeskAdmin.fxml", holderPane); break; case F8: Utilities.switchSchermNaarFXML("UM.fxml", holderPane); break; default: break; } } @FXML private void openHome(ActionEvent event) { setNode(fxml2); } @FXML private void openBagageToevoegen(ActionEvent event) throws IOException { //setNode(bagageToevoegen); Utilities.switchSchermNaarFXML("GevondenBagageRegistratie.fxml", holderPane); } @FXML private void openBagageOverzicht(ActionEvent event) throws IOException { //setNode(bagageOverzicht); Utilities.switchSchermNaarFXML("BagageOverzicht.fxml", holderPane); } @FXML private void openBagageZoeken(ActionEvent event) throws IOException { //setNode(bagageZoeken); Utilities.switchSchermNaarFXML("VermisteBagageRegistratie.fxml", holderPane); } @FXML private void openContact(ActionEvent event) { setNode(faq); } @FXML private void openHelpdesk(ActionEvent event) { setNode(helpdesk); } @FXML private void openUM(ActionEvent event) { setNode(UM); } @FXML private void openRegistreerSchadevergoeding(ActionEvent event) throws IOException { //setNode(registreerSchadevergoeding); Utilities.switchSchermNaarFXML("RegistreerSchadevergoeding.fxml", holderPane); } }
True
False
1,569
2,185
121894_5
public class Tester { public Tester() { // Dit compileert niet; we kunnen er niet van uitgaan dat het Object dat we // aanmaken werkelijk een String is // compile-time: linkerkant van het is-gelijkteken // run-time: rechterkant van het is-gelijkteken Object demo1 ="Hallo"; //String s1 = demo1; // We kunnen de compiler er wel van overtuigen dat we wel degelijk met een // String te maken hebben -> casting Object demo2 = "Hallo"; String s = (String)demo2; // Het volgende compileert wel, maar geeft in run-time een error // omdat we een boolean niet naar een string kunnen casten Object demo3 = Boolean.FALSE; String s2 = (String)demo3; // linkerkant -> STATISCHE DATATYPE // rechterkant -> DYNAMISCHE DATATYPE } }
bart314/ITANN
StaticAndDynamicDemo/Tester.java
268
// We kunnen de compiler er wel van overtuigen dat we wel degelijk met een
line_comment
nl
public class Tester { public Tester() { // Dit compileert niet; we kunnen er niet van uitgaan dat het Object dat we // aanmaken werkelijk een String is // compile-time: linkerkant van het is-gelijkteken // run-time: rechterkant van het is-gelijkteken Object demo1 ="Hallo"; //String s1 = demo1; // We kunnen<SUF> // String te maken hebben -> casting Object demo2 = "Hallo"; String s = (String)demo2; // Het volgende compileert wel, maar geeft in run-time een error // omdat we een boolean niet naar een string kunnen casten Object demo3 = Boolean.FALSE; String s2 = (String)demo3; // linkerkant -> STATISCHE DATATYPE // rechterkant -> DYNAMISCHE DATATYPE } }
True
False
1,572
2,982
43439_2
package techiteasy1121.config; @Configuration @EnableWebSecurity public class SpringSecurityConfig { /*TODO inject customUserDetailService en jwtRequestFilter*/ // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig. // Je kunt dit ook in een aparte configuratie klasse zetten. @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Authenticatie met customUserDetailsService en passwordEncoder @Bean public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoder passwordEncoder) throws Exception { var auth = new DaoAuthenticationProvider(); auth.setPasswordEncoder(passwordEncoder); auth.setUserDetailsService(customUserDetailsService); return new ProviderManager(auth); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { //JWT token authentication http .csrf(csrf -> csrf.disable()) .httpBasic(basic -> basic.disable()) .cors(Customizer.withDefaults()) .authorizeHttpRequests(auth -> auth // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").hasRole("ADMIN") .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") /*TODO voeg de antmatchers toe voor admin(post en delete) en user (overige)*/ .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll()/*alleen dit punt mag toegankelijk zijn voor niet ingelogde gebruikers*/ .anyRequest().denyAll() /*Deze voeg je altijd als laatste toe, om een default beveiliging te hebben voor eventuele vergeten endpoints of endpoints die je later toevoegd. */ ) .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
hogeschoolnovi/backend-spring-boot-tech-it-easy-security
src/techiteasy1121/config/SpringSecurityConfig.java
640
// Je kunt dit ook in een aparte configuratie klasse zetten.
line_comment
nl
package techiteasy1121.config; @Configuration @EnableWebSecurity public class SpringSecurityConfig { /*TODO inject customUserDetailService en jwtRequestFilter*/ // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig. // Je kunt<SUF> @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Authenticatie met customUserDetailsService en passwordEncoder @Bean public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoder passwordEncoder) throws Exception { var auth = new DaoAuthenticationProvider(); auth.setPasswordEncoder(passwordEncoder); auth.setUserDetailsService(customUserDetailsService); return new ProviderManager(auth); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { //JWT token authentication http .csrf(csrf -> csrf.disable()) .httpBasic(basic -> basic.disable()) .cors(Customizer.withDefaults()) .authorizeHttpRequests(auth -> auth // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").hasRole("ADMIN") .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") /*TODO voeg de antmatchers toe voor admin(post en delete) en user (overige)*/ .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll()/*alleen dit punt mag toegankelijk zijn voor niet ingelogde gebruikers*/ .anyRequest().denyAll() /*Deze voeg je altijd als laatste toe, om een default beveiliging te hebben voor eventuele vergeten endpoints of endpoints die je later toevoegd. */ ) .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
True
False
1,578
473
1684_13
/** * @author Vera Wise * @author Elias De Hondt * @since 08/12/2022 */ // ===================================================================================================================== /* * Canvas KdG * @see https://canvas.kdg.be/courses/37158/pages/afspraken-en-deadlines?module_item_id=663060 * * Github * @see https://github.com/EliasDeHondt/Memo-Race * * Google Docs * @see https://docs.google.com/spreadsheets/d/199y9TW0weDEmgGD8Iv0UWyqQnMW8zF_RrBZ8XB4lQBc/edit#gid=0 * */ // ===================================================================================================================== // TODO: - Voorzie een startscherm waar je de namen van de spelers kan ingeven. // - Elke speler kan een avatar kiezen of zelf een foto toevoegen. // - Voorzie een lijst op het scherm met eerder aangemaakte spelers. Sla deze op in een bestand. // - Zorg voor een mooi grafische vormgeving. // - Tijdens het spelverloop moet volgende zichtbaar zijn: // - Een dobbelsteen. // - Het speelveld met in het midden de omgedraaide kaarten. // - Per speler zijn naam, de avatar en de gewonnen kaarten. // - Een pion die automatisch verplaatst na een worp. // - Kaarten moeten met de muis omgedraaid kunnen worden. // - Als een figuur gevonden is moet het overeenkomstige vak een alternatieve opmaak // (bv. donkerder) krijgen zodat duidelijk is dat de pion deze vakken mag overslaan. // - Maak visueel zichtbaar welke speler aan de beurt is. // ===================================================================================================================== // SPELBESCHRIJVING /* * MemoRace is een variant op memory, maar een dobbelsteen zorgt voor een extra dimensie. Het * spel leert kinderen dezelfde vaardigheden als Memory en de dobbelsteen bevorderd het tellen. * Een pion loopt op een pad met in elk vak een verschillende afbeelding rond een speelveld. In het * speelveld liggen omgedraaide kaarten met de verschillende afbeeldingen. De spelers moeten * zoveel mogelijk van de afbeeldingen op het pad terugvinden bij de omgedraaide kaarten in het * midden van het speelveld. De speler die op het einde de meeste kaarten gevonden heeft wint * het spel. Het kan gespeeld worden met 2 tot 6 spelers * Hieronder een overzicht van de belangrijkste spelonderdelen: * • een spelbord * • 16 kaarten die willekeurig in het midden van het spelbord gelegd worden * • 1 dobbelsteen * • 1 pion */ // ===================================================================================================================== // SPELVERLOOP /* * Er wordt om de beurt gespeeld. Het spel beslist random in welke * volgorde de spelers mogen spelen. De pion start op “go”. De eerste * speler werpt de dobbelsteen en zet de pion evenveel vakken (groene * genummerd in de afbeelding) vooruit. Elk vak toont een afbeelding. * Het is de bedoeling dat de speler de kaart met dezelfde afbeelding * omdraait (kaarten zijn de witte vakjes in de afbeelding). Als dat lukt, * dan krijgt hij de kaart. In het andere geval wordt de kaart terug * omgedraaid. Hierna is de beurt van deze speler om en is het aan de * volgende speler. Hij gooit en verplaatst de pion. Ook hij moet proberen * die kaart om te draaien die overeenkomt met de afbeelding van het * vak waar de pion nu op staat. Het spel loopt zo verder tot alle kaarten van het veld verdwenen * zijn. De persoon met de meeste kaarten wint het spel. De pion slaat de vakken met reeds * gevonden figuren en de hoekvakken over. */ // =====================================================================================================================
EliasDeHondt/Memo-Race
TODO.java
1,134
// (bv. donkerder) krijgen zodat duidelijk is dat de pion deze vakken mag overslaan.
line_comment
nl
/** * @author Vera Wise * @author Elias De Hondt * @since 08/12/2022 */ // ===================================================================================================================== /* * Canvas KdG * @see https://canvas.kdg.be/courses/37158/pages/afspraken-en-deadlines?module_item_id=663060 * * Github * @see https://github.com/EliasDeHondt/Memo-Race * * Google Docs * @see https://docs.google.com/spreadsheets/d/199y9TW0weDEmgGD8Iv0UWyqQnMW8zF_RrBZ8XB4lQBc/edit#gid=0 * */ // ===================================================================================================================== // TODO: - Voorzie een startscherm waar je de namen van de spelers kan ingeven. // - Elke speler kan een avatar kiezen of zelf een foto toevoegen. // - Voorzie een lijst op het scherm met eerder aangemaakte spelers. Sla deze op in een bestand. // - Zorg voor een mooi grafische vormgeving. // - Tijdens het spelverloop moet volgende zichtbaar zijn: // - Een dobbelsteen. // - Het speelveld met in het midden de omgedraaide kaarten. // - Per speler zijn naam, de avatar en de gewonnen kaarten. // - Een pion die automatisch verplaatst na een worp. // - Kaarten moeten met de muis omgedraaid kunnen worden. // - Als een figuur gevonden is moet het overeenkomstige vak een alternatieve opmaak // (bv. donkerder)<SUF> // - Maak visueel zichtbaar welke speler aan de beurt is. // ===================================================================================================================== // SPELBESCHRIJVING /* * MemoRace is een variant op memory, maar een dobbelsteen zorgt voor een extra dimensie. Het * spel leert kinderen dezelfde vaardigheden als Memory en de dobbelsteen bevorderd het tellen. * Een pion loopt op een pad met in elk vak een verschillende afbeelding rond een speelveld. In het * speelveld liggen omgedraaide kaarten met de verschillende afbeeldingen. De spelers moeten * zoveel mogelijk van de afbeeldingen op het pad terugvinden bij de omgedraaide kaarten in het * midden van het speelveld. De speler die op het einde de meeste kaarten gevonden heeft wint * het spel. Het kan gespeeld worden met 2 tot 6 spelers * Hieronder een overzicht van de belangrijkste spelonderdelen: * • een spelbord * • 16 kaarten die willekeurig in het midden van het spelbord gelegd worden * • 1 dobbelsteen * • 1 pion */ // ===================================================================================================================== // SPELVERLOOP /* * Er wordt om de beurt gespeeld. Het spel beslist random in welke * volgorde de spelers mogen spelen. De pion start op “go”. De eerste * speler werpt de dobbelsteen en zet de pion evenveel vakken (groene * genummerd in de afbeelding) vooruit. Elk vak toont een afbeelding. * Het is de bedoeling dat de speler de kaart met dezelfde afbeelding * omdraait (kaarten zijn de witte vakjes in de afbeelding). Als dat lukt, * dan krijgt hij de kaart. In het andere geval wordt de kaart terug * omgedraaid. Hierna is de beurt van deze speler om en is het aan de * volgende speler. Hij gooit en verplaatst de pion. Ook hij moet proberen * die kaart om te draaien die overeenkomt met de afbeelding van het * vak waar de pion nu op staat. Het spel loopt zo verder tot alle kaarten van het veld verdwenen * zijn. De persoon met de meeste kaarten wint het spel. De pion slaat de vakken met reeds * gevonden figuren en de hoekvakken over. */ // =====================================================================================================================
True
False
1,579
850
36825_1
package app; import java.util.Scanner; import java.io.FileWriter; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class App { static ChatClient client; static boolean shouldLog = false; static String[] kamers = {"Zolder", "Woonkamer", "WC"}; public static void main(String[] args) throws Exception { System.out.println("Welkom bij deze chatapp, we hebben uw naam nodig om te kunnen chatten.."); String username = getUserInput("Wat is uw naam?"); // start de chatclient client = new ChatClient(); client.start(username, new IWantNewMessages(){ @Override public void processNewMessage(String message) { while (message.contains("room ")) { char roomnumber = message.charAt(message.indexOf("room ") + 5); if (roomnumber != 'u') { int roomno = Integer.parseInt(roomnumber + ""); String kamer = kamers[roomno-1]; message = message.replace("room " + roomno,kamer); } else { message = message.replace("room undefined", "onbekend"); } } System.out.println(Log("SERVER SENDS: " + message)); } }); client.sendMessage(Log("USER:" + username)); // zolang de gebruiker iets wil, doen we dat String command = getUserInput("client :>"); while (!command.equals("q")){ processCommand(command); command = getUserInput("client :>"); } System.out.println("Ok, bye!"); } public static void processCommand(String command){ switch (command) { case "h": { System.out.println("De beschikbare commando's zijn: "); System.out.println("\th: toont deze hulp functie"); System.out.println("\tq: eindigt dit programma"); System.out.println("\tr: verander van kamer"); System.out.println("\ts: stuur een bericht"); System.out.println("\tx: voer een ban uit (admin only)"); System.out.println("\tb: vraag om een ban"); System.out.println("\t?: vraag om status informatie"); break; } case "r": { System.out.println("De beschikbare kamers zijn: "); for (int i = 0; i < kamers.length; i++) { System.out.println("\th: " + (i + 1) + ". " + kamers[i]); } String kamer = getUserInput("Welke kamer wilt u in?"); client.sendMessage(Log("ROOM:" + kamer)); break; } case "s": { String datatosend = getUserInput("Wat wilt u versturen?"); client.sendMessage(Log("MESSAGE:" + datatosend )); break; } case "log": { shouldLog = !shouldLog; System.out.println(Log("Logging is set to " + shouldLog)); break; } case "x": { String user = getUserInput("execute ban on user?"); client.sendMessage(Log("EXECUTEBAN:" + user )); break; } case "xx": { String user = getUserInput("execute superban on?"); client.sendMessage(Log("EXECUTEBAN2:" + user )); break; } case "b": { String user = getUserInput("Wie wilt u bannen?"); client.sendMessage(Log("BAN:" + user )); break; } case "?": { client.sendMessage(Log("STATUS")); break; } default: { System.out.println(Log("onbekend commando!")); break; } } } public static String Log(String line) { if (shouldLog) { try { FileWriter logFile = new FileWriter("./log.txt", true); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); logFile.append(dtf.format(now) + " " + line + "\r\n"); logFile.close(); } catch (IOException io){ System.out.println("error: " + io.getMessage()); } } return line; } public static String getUserInput(String prompt){ System.out.println(prompt); Scanner s = new Scanner(System.in); String data = s.nextLine(); return data; } }
JohnGorter/JavaChatDemo
src/app/App.java
1,250
// zolang de gebruiker iets wil, doen we dat
line_comment
nl
package app; import java.util.Scanner; import java.io.FileWriter; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class App { static ChatClient client; static boolean shouldLog = false; static String[] kamers = {"Zolder", "Woonkamer", "WC"}; public static void main(String[] args) throws Exception { System.out.println("Welkom bij deze chatapp, we hebben uw naam nodig om te kunnen chatten.."); String username = getUserInput("Wat is uw naam?"); // start de chatclient client = new ChatClient(); client.start(username, new IWantNewMessages(){ @Override public void processNewMessage(String message) { while (message.contains("room ")) { char roomnumber = message.charAt(message.indexOf("room ") + 5); if (roomnumber != 'u') { int roomno = Integer.parseInt(roomnumber + ""); String kamer = kamers[roomno-1]; message = message.replace("room " + roomno,kamer); } else { message = message.replace("room undefined", "onbekend"); } } System.out.println(Log("SERVER SENDS: " + message)); } }); client.sendMessage(Log("USER:" + username)); // zolang de<SUF> String command = getUserInput("client :>"); while (!command.equals("q")){ processCommand(command); command = getUserInput("client :>"); } System.out.println("Ok, bye!"); } public static void processCommand(String command){ switch (command) { case "h": { System.out.println("De beschikbare commando's zijn: "); System.out.println("\th: toont deze hulp functie"); System.out.println("\tq: eindigt dit programma"); System.out.println("\tr: verander van kamer"); System.out.println("\ts: stuur een bericht"); System.out.println("\tx: voer een ban uit (admin only)"); System.out.println("\tb: vraag om een ban"); System.out.println("\t?: vraag om status informatie"); break; } case "r": { System.out.println("De beschikbare kamers zijn: "); for (int i = 0; i < kamers.length; i++) { System.out.println("\th: " + (i + 1) + ". " + kamers[i]); } String kamer = getUserInput("Welke kamer wilt u in?"); client.sendMessage(Log("ROOM:" + kamer)); break; } case "s": { String datatosend = getUserInput("Wat wilt u versturen?"); client.sendMessage(Log("MESSAGE:" + datatosend )); break; } case "log": { shouldLog = !shouldLog; System.out.println(Log("Logging is set to " + shouldLog)); break; } case "x": { String user = getUserInput("execute ban on user?"); client.sendMessage(Log("EXECUTEBAN:" + user )); break; } case "xx": { String user = getUserInput("execute superban on?"); client.sendMessage(Log("EXECUTEBAN2:" + user )); break; } case "b": { String user = getUserInput("Wie wilt u bannen?"); client.sendMessage(Log("BAN:" + user )); break; } case "?": { client.sendMessage(Log("STATUS")); break; } default: { System.out.println(Log("onbekend commando!")); break; } } } public static String Log(String line) { if (shouldLog) { try { FileWriter logFile = new FileWriter("./log.txt", true); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); logFile.append(dtf.format(now) + " " + line + "\r\n"); logFile.close(); } catch (IOException io){ System.out.println("error: " + io.getMessage()); } } return line; } public static String getUserInput(String prompt){ System.out.println(prompt); Scanner s = new Scanner(System.in); String data = s.nextLine(); return data; } }
True
False
1,585
297
158361_1
package me.goowen.kitpvp.modules.kits; import me.goowen.kitpvp.Kitpvp; import me.goowen.kitpvp.modules.config.ConfigModule; import me.goowen.kitpvp.modules.utilities.ItemBuilder; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import java.util.List; import java.util.Objects; public class KitsManager { private ConfigModule configModule = Kitpvp.getConfigModule(); private Kitpvp plugin = Kitpvp.getInstance(); /** * Slaat de kit op in een config vanuit de spelers inventory op basis van naam! * @param player de speler wiens inventory moet worden opgeslagen als kit! * @param name de naam van de kit! */ public void saveKit(Player player, String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".armor", player.getInventory().getArmorContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".items", player.getInventory().getContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".icon", new ItemBuilder(player.getInventory().getItemInMainHand().clone()).setName(ChatColor.DARK_AQUA + name).addLoreLine(ChatColor.GRAY + "" + ChatColor.UNDERLINE + "Click to select this kit").toItemStack()); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } public void deleteKit(String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name, null); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } /** * Haalt de kit op uit de config en zet hem om in een inventory. * Geeft de zojuist opgehaalde kit aan de speler. * @param player de speler die de kit moet krijgen. * @param name de naam van de kit die de speler moet krijgen. */ @SuppressWarnings("unchecked") public void giveKit(Player player, String name) { FileConfiguration kitsConfig = configModule.getKitsConfig().getConfigConfiguration(); //Haalt de armor op een geeft deze. ItemStack[] content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".armor"))).toArray(new ItemStack[0]); player.getInventory().setArmorContents(content); //Haalt de Items in de inventory op een geeft deze. content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".items"))).toArray(new ItemStack[0]); player.getInventory().setContents(content); } /** * Maakt het kits menu aan en toont hem aan de speler. * @param player de speler die het menu moet krijgen */ public void kitsMenu(Player player) { try { //Maakt de inventory aan. Inventory kits = plugin.getServer().createInventory(null, 9, ChatColor.DARK_AQUA + "Kies een Kit!"); for(String name : configModule.getKitsConfig().getConfigConfiguration().getConfigurationSection("kits").getKeys(false)) { kits.addItem(configModule.getKitsConfig().getConfigConfiguration().getItemStack("kits." + name + ".icon")); } //Toont(Opent) de inventory aan de speler. player.openInventory(kits); } catch (NullPointerException exeption) { player.sendMessage(ChatColor.RED + "There are not current kits, please make some!"); } } }
Caaarlowsz/Kitpvp-21
src/main/java/me/goowen/kitpvp/modules/kits/KitsManager.java
1,043
/** * Haalt de kit op uit de config en zet hem om in een inventory. * Geeft de zojuist opgehaalde kit aan de speler. * @param player de speler die de kit moet krijgen. * @param name de naam van de kit die de speler moet krijgen. */
block_comment
nl
package me.goowen.kitpvp.modules.kits; import me.goowen.kitpvp.Kitpvp; import me.goowen.kitpvp.modules.config.ConfigModule; import me.goowen.kitpvp.modules.utilities.ItemBuilder; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import java.util.List; import java.util.Objects; public class KitsManager { private ConfigModule configModule = Kitpvp.getConfigModule(); private Kitpvp plugin = Kitpvp.getInstance(); /** * Slaat de kit op in een config vanuit de spelers inventory op basis van naam! * @param player de speler wiens inventory moet worden opgeslagen als kit! * @param name de naam van de kit! */ public void saveKit(Player player, String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".armor", player.getInventory().getArmorContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".items", player.getInventory().getContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".icon", new ItemBuilder(player.getInventory().getItemInMainHand().clone()).setName(ChatColor.DARK_AQUA + name).addLoreLine(ChatColor.GRAY + "" + ChatColor.UNDERLINE + "Click to select this kit").toItemStack()); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } public void deleteKit(String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name, null); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } /** * Haalt de kit<SUF>*/ @SuppressWarnings("unchecked") public void giveKit(Player player, String name) { FileConfiguration kitsConfig = configModule.getKitsConfig().getConfigConfiguration(); //Haalt de armor op een geeft deze. ItemStack[] content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".armor"))).toArray(new ItemStack[0]); player.getInventory().setArmorContents(content); //Haalt de Items in de inventory op een geeft deze. content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".items"))).toArray(new ItemStack[0]); player.getInventory().setContents(content); } /** * Maakt het kits menu aan en toont hem aan de speler. * @param player de speler die het menu moet krijgen */ public void kitsMenu(Player player) { try { //Maakt de inventory aan. Inventory kits = plugin.getServer().createInventory(null, 9, ChatColor.DARK_AQUA + "Kies een Kit!"); for(String name : configModule.getKitsConfig().getConfigConfiguration().getConfigurationSection("kits").getKeys(false)) { kits.addItem(configModule.getKitsConfig().getConfigConfiguration().getItemStack("kits." + name + ".icon")); } //Toont(Opent) de inventory aan de speler. player.openInventory(kits); } catch (NullPointerException exeption) { player.sendMessage(ChatColor.RED + "There are not current kits, please make some!"); } } }
True
False
1,588
2,754
57593_2
package com.mycompany.minorigv.gffparser; import com.mycompany.minorigv.blast.BlastORF; import com.mycompany.minorigv.blast.ColorORFs; import com.mycompany.minorigv.sequence.FindORF; import java.awt.*; import java.util.ArrayList; import java.util.HashMap; /** * Deze class maakt objecten voor chromosomen/contigs. Ook worden hier de bijbehorende features in object gezet. * * @author Anne van Ewijk en Amber Janssen Groesbeek */ public class Chromosome { private String id; private ArrayList<Feature> features; private String seqTemp; private ArrayList<ORF> listORF; private HashMap<String, Object> readingframe; private HashMap<String, Color> headerColor; /** * De constructor. */ public Chromosome() { features = new ArrayList<Feature>(); } /** * De constructor. * @param id Het id van het chromosoom/contig. * @param features Features zijn het CDS, Exon, Gene, mRNA en Region. */ public Chromosome(String id, ArrayList<Feature> features) { this.id = id; this.features = features; } /** * De constructor. * @param id Het id van het chromosoom/contig * @param seqTemp Sequentie van de template strand * @param listORF Lijst met alle ORFs gevonden */ public Chromosome(String id, String seqTemp, ArrayList<ORF> listORF){ this.id = id; this.seqTemp = seqTemp; this.listORF = listORF; } /** * Het toevoegen van features aan het chromosoom. * @param feat Features zijn het CDS, Exon, Gene, mRNA en Region. */ public void addFeature(Feature feat){ if (feat instanceof Feature){ features.add(feat); } } /** * Het returned het id van het chromosoom/contig. * @return id is een String. Het is het id van het chromosoom/contig. */ public String getId() { return id; } /** * Het genereerd het id van het chromosoom/contig. * @param id is een String. Het is het id van het chromosoom/contig. */ public void setId(String id) { this.id = id; } /** * Het returned de sequentie van het chromosoom/contig. * @return seqTemp is een String. Het is de DNA sequentie van het chromosoom. */ public String getSeqTemp() { return seqTemp; } /** * Het genereerd de sequentie van het chromosoom/contig. * @param seqTemp */ public void setSeqTemp(String seqTemp) { this.seqTemp = seqTemp; } /** * Het returned een ArrayList met de features erin. * @return features is een ArrayList met daarin de features */ public ArrayList<Feature> getFeatures() { return features; } /** * Het genereerd de ArrayList met daarin de features. * @param features is een Arraylist met daarin de features */ public void setFeatures(ArrayList<Feature> features) { this.features = features; } /** * Het returned een ArrayList met daarin de ORFs. * @return listORF is een ArrayList met daarin de ORFs. */ public ArrayList<ORF> getListORF() { return listORF; } public void setListORF(ArrayList<ORF> newListOrf){ this.listORF = newListOrf; } /** * Het genereerd de ArrayList met daarin de ORFs */ public void createListOrf(int lenghtORF) { // ORFs zoeken in de template strand en complementaire streng. listORF = FindORF.searchORF(getId(), getSeqTemp(), lenghtORF); } /** * Hashmap met als key de readingframes (RF1, RF2, ..., RF6) en als value de aminozuursequentie * @return Een hashmap. key: readingframes, value: aminozuursequentie */ public HashMap<String, Object> getReadingframe() { return readingframe; } /** * Het opslaan van de hashmap met daarin voor elk readingframe (key), de aminozuursequentie (value) * @param readingframe Hashmap. Key: readingframes, value: aminozuursequentie */ public void setReadingframe(HashMap<String, Object> readingframe) { this.readingframe = readingframe; } /** * Alle features die tussen de start en stop positie voorkomen wordenom eem ArrayList gezet. * @param start Start positie van de feature op het chromosoom. * @param stop Stop positie van de feature op het chromosoom * @return Een lijst met de features die voldoen aan de start en stop */ public ArrayList<Feature> getFeaturesBetween(int start, int stop){ ArrayList<Feature> featureList = new ArrayList<Feature>(); for(Feature f : features){ if (f.getStop() > start && f.getStop() < stop){ featureList.add(f); }else if(f.getStart() >= start && f.getStart() < stop){ featureList.add(f); }else if(f.getStart() <= start && f.getStop() > stop){ featureList.add(f); } } return featureList; } /** * De Features worden opgehaald na keuze van de gebruiker. * Stel de gebruiker wilt alleen Gene en CDS zien, dan worden deze features opgehaald die behoren tot CDS en Gene. * @param featureList is de lijst met alle features uit het chromosoom/contig. * @param SelectedFeatures is de lijst met de gekozen features (dus bijv. Gene en CDS) die de gebruiker heeft gekozen. * @return Een lijst met de gekozen features wordt gereturned. */ public static ArrayList<Feature> filterFeatures(ArrayList<Feature> featureList, ArrayList<String> SelectedFeatures){ ArrayList<Feature> featureFilteredList = new ArrayList<Feature>(); for (Feature feat : featureList){ String klas = feat.getClass().toString(); for (String optie : SelectedFeatures){ if (klas.contains(optie)){ featureFilteredList.add(feat); } } } return featureFilteredList; } /** * Alle ORFs die tussen de start en stop positie voorkomen worden om eem ArrayList gezet. * @param start Startpositie waar vandaan de orfs gezocht moeten worden * @param stop Stoppositie tot waar de orfs gezocht moeten worden * @return Een lijst met de orfs die voldoen aan de start en stop */ public ArrayList<ORF> getORFsBetween(int start, int stop){ ArrayList<ORF> orfsFilteredList = new ArrayList<>(); if(listORF != null){ for(ORF o : listORF){ if (o.getStop() > start && o.getStop() < stop){ orfsFilteredList.add(o); }else if(o.getStart() > start && o.getStart() < stop){ orfsFilteredList.add(o); }else if(o.getStart() < start && o.getStop() > stop){ orfsFilteredList.add(o); } } return orfsFilteredList; }else{ return null; } } @Override public String toString() { return "Chromosome{" + "id='" + id + '\'' + ", features=" + features + '}'; } }
gabeplz/intership-genome-viewer-backup
MinorIGV/src/main/java/com/mycompany/minorigv/gffparser/Chromosome.java
2,153
/** * De constructor. * @param id Het id van het chromosoom/contig. * @param features Features zijn het CDS, Exon, Gene, mRNA en Region. */
block_comment
nl
package com.mycompany.minorigv.gffparser; import com.mycompany.minorigv.blast.BlastORF; import com.mycompany.minorigv.blast.ColorORFs; import com.mycompany.minorigv.sequence.FindORF; import java.awt.*; import java.util.ArrayList; import java.util.HashMap; /** * Deze class maakt objecten voor chromosomen/contigs. Ook worden hier de bijbehorende features in object gezet. * * @author Anne van Ewijk en Amber Janssen Groesbeek */ public class Chromosome { private String id; private ArrayList<Feature> features; private String seqTemp; private ArrayList<ORF> listORF; private HashMap<String, Object> readingframe; private HashMap<String, Color> headerColor; /** * De constructor. */ public Chromosome() { features = new ArrayList<Feature>(); } /** * De constructor. <SUF>*/ public Chromosome(String id, ArrayList<Feature> features) { this.id = id; this.features = features; } /** * De constructor. * @param id Het id van het chromosoom/contig * @param seqTemp Sequentie van de template strand * @param listORF Lijst met alle ORFs gevonden */ public Chromosome(String id, String seqTemp, ArrayList<ORF> listORF){ this.id = id; this.seqTemp = seqTemp; this.listORF = listORF; } /** * Het toevoegen van features aan het chromosoom. * @param feat Features zijn het CDS, Exon, Gene, mRNA en Region. */ public void addFeature(Feature feat){ if (feat instanceof Feature){ features.add(feat); } } /** * Het returned het id van het chromosoom/contig. * @return id is een String. Het is het id van het chromosoom/contig. */ public String getId() { return id; } /** * Het genereerd het id van het chromosoom/contig. * @param id is een String. Het is het id van het chromosoom/contig. */ public void setId(String id) { this.id = id; } /** * Het returned de sequentie van het chromosoom/contig. * @return seqTemp is een String. Het is de DNA sequentie van het chromosoom. */ public String getSeqTemp() { return seqTemp; } /** * Het genereerd de sequentie van het chromosoom/contig. * @param seqTemp */ public void setSeqTemp(String seqTemp) { this.seqTemp = seqTemp; } /** * Het returned een ArrayList met de features erin. * @return features is een ArrayList met daarin de features */ public ArrayList<Feature> getFeatures() { return features; } /** * Het genereerd de ArrayList met daarin de features. * @param features is een Arraylist met daarin de features */ public void setFeatures(ArrayList<Feature> features) { this.features = features; } /** * Het returned een ArrayList met daarin de ORFs. * @return listORF is een ArrayList met daarin de ORFs. */ public ArrayList<ORF> getListORF() { return listORF; } public void setListORF(ArrayList<ORF> newListOrf){ this.listORF = newListOrf; } /** * Het genereerd de ArrayList met daarin de ORFs */ public void createListOrf(int lenghtORF) { // ORFs zoeken in de template strand en complementaire streng. listORF = FindORF.searchORF(getId(), getSeqTemp(), lenghtORF); } /** * Hashmap met als key de readingframes (RF1, RF2, ..., RF6) en als value de aminozuursequentie * @return Een hashmap. key: readingframes, value: aminozuursequentie */ public HashMap<String, Object> getReadingframe() { return readingframe; } /** * Het opslaan van de hashmap met daarin voor elk readingframe (key), de aminozuursequentie (value) * @param readingframe Hashmap. Key: readingframes, value: aminozuursequentie */ public void setReadingframe(HashMap<String, Object> readingframe) { this.readingframe = readingframe; } /** * Alle features die tussen de start en stop positie voorkomen wordenom eem ArrayList gezet. * @param start Start positie van de feature op het chromosoom. * @param stop Stop positie van de feature op het chromosoom * @return Een lijst met de features die voldoen aan de start en stop */ public ArrayList<Feature> getFeaturesBetween(int start, int stop){ ArrayList<Feature> featureList = new ArrayList<Feature>(); for(Feature f : features){ if (f.getStop() > start && f.getStop() < stop){ featureList.add(f); }else if(f.getStart() >= start && f.getStart() < stop){ featureList.add(f); }else if(f.getStart() <= start && f.getStop() > stop){ featureList.add(f); } } return featureList; } /** * De Features worden opgehaald na keuze van de gebruiker. * Stel de gebruiker wilt alleen Gene en CDS zien, dan worden deze features opgehaald die behoren tot CDS en Gene. * @param featureList is de lijst met alle features uit het chromosoom/contig. * @param SelectedFeatures is de lijst met de gekozen features (dus bijv. Gene en CDS) die de gebruiker heeft gekozen. * @return Een lijst met de gekozen features wordt gereturned. */ public static ArrayList<Feature> filterFeatures(ArrayList<Feature> featureList, ArrayList<String> SelectedFeatures){ ArrayList<Feature> featureFilteredList = new ArrayList<Feature>(); for (Feature feat : featureList){ String klas = feat.getClass().toString(); for (String optie : SelectedFeatures){ if (klas.contains(optie)){ featureFilteredList.add(feat); } } } return featureFilteredList; } /** * Alle ORFs die tussen de start en stop positie voorkomen worden om eem ArrayList gezet. * @param start Startpositie waar vandaan de orfs gezocht moeten worden * @param stop Stoppositie tot waar de orfs gezocht moeten worden * @return Een lijst met de orfs die voldoen aan de start en stop */ public ArrayList<ORF> getORFsBetween(int start, int stop){ ArrayList<ORF> orfsFilteredList = new ArrayList<>(); if(listORF != null){ for(ORF o : listORF){ if (o.getStop() > start && o.getStop() < stop){ orfsFilteredList.add(o); }else if(o.getStart() > start && o.getStart() < stop){ orfsFilteredList.add(o); }else if(o.getStart() < start && o.getStop() > stop){ orfsFilteredList.add(o); } } return orfsFilteredList; }else{ return null; } } @Override public String toString() { return "Chromosome{" + "id='" + id + '\'' + ", features=" + features + '}'; } }
True
False
1,594
4,623
37944_4
package org.cq2.delegator.internal; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import org.cq2.delegator.Component; import org.cq2.delegator.Self; import org.cq2.delegator.internal.MethodsCache.Tuple; import org.cq2.delegator.method.MethodUtil; public class ComposedClass { private List classes; private ComposedClass[] removeReferences; private Map addMap; private Map insertMap; private ForwardingMethod[] implementingMethods; private static ComposedClass emptyClass; private int[] componentIndexes; private ComposedClass() { this(new ArrayList()); } ComposedClass(List classes) { this.classes = classes; removeReferences = new ComposedClass[classes.size()]; addMap = new HashMap(); insertMap = new HashMap(); implementingMethods = new ForwardingMethod[0]; componentIndexes = new int[0]; } public static ComposedClass getEmptyClass() { if (emptyClass == null) { emptyClass = ComposedClassCache.get(new ArrayList()); } return emptyClass; } public ComposedClass remove(int i) { ComposedClass result = removeReferences[i]; if (result == null) { List smallerClasses = new ArrayList(classes); smallerClasses.remove(i); result = ComposedClassCache.get(smallerClasses); removeReferences[i] = result; } return result; } public ComposedClass add(Class clazz) { ComposedClass result = (ComposedClass) addMap.get(clazz); if (result == null) { List largerClasses = new ArrayList(classes); largerClasses.add(clazz); result = ComposedClassCache.get(largerClasses); addMap.put(clazz, result); } return result; } public ComposedClass insert(Class clazz) { ComposedClass result = (ComposedClass) insertMap.get(clazz); if (result == null) { List largerClasses = new ArrayList(classes); largerClasses.add(0, clazz); result = ComposedClassCache.get(largerClasses); insertMap.put(clazz, result); } return result; } public int getComponentIndex(int methodIdentifier) { if (methodIdentifier < componentIndexes.length) { int result = componentIndexes[methodIdentifier]; if (result != -1) return result; } else enlargeArrays(methodIdentifier + 1); setMethod(methodIdentifier); return componentIndexes[methodIdentifier]; } public ForwardingMethod getMethod(int methodIdentifier) { if (methodIdentifier < implementingMethods.length) { ForwardingMethod result = implementingMethods[methodIdentifier]; if (result != null) return result; } else enlargeArrays(methodIdentifier + 1); return setMethod(methodIdentifier); } private Tuple resolve(int uniqueIdentifier) { Method method = ForwardingMethodRegister.getInstance().getMethod(uniqueIdentifier); //TODO synchronization noodzaak opnieuw checken. if ("hashCode".equals(method.getName()) || "equals".equals(method.getName())) return resolve(method, classes.size(), Self.class); int i = 0; for (; i < classes.size(); i++) { Class clazz = (Class) classes.get(i); Tuple result = resolve(method, i, clazz); if (result != null) return result; } Tuple result = resolve(method, classes.size(), Self.class); if (result != null) return result; throw new NoSuchMethodError(method.toString()); } private Tuple resolve(Method method, int i, Class clazz) { Method delegateMethod; boolean componentMethodIsProtected = false; if (Component.class.isAssignableFrom(clazz)) { delegateMethod = MethodUtil.getDeclaredMethod(clazz, method.getName() + ClassGenerator.SUPERCALL_POSTFIX, method.getParameterTypes(), method.getExceptionTypes()); //De superdelegatemethod is feitelijk de methode zoals // ingetiept door de programmeur //deze bestaat per definitie - als die niet gevonden wordt // betekent dat hij protected of package is Method superDelegateMethod = MethodUtil.getDeclaredMethod( clazz.getSuperclass(), method.getName(), method.getParameterTypes(), method.getExceptionTypes()); componentMethodIsProtected = (delegateMethod != null) && (superDelegateMethod == null); } else { delegateMethod = MethodUtil.getDeclaredMethod(clazz, method.getName(), method.getParameterTypes(), method.getExceptionTypes()); if (delegateMethod != null) componentMethodIsProtected = Modifier .isProtected(delegateMethod.getModifiers()); } if (delegateMethod != null && (!componentMethodIsProtected || Modifier .isProtected(method.getModifiers())) || !Modifier.isPublic(method.getModifiers())) { return new Tuple(i, delegateMethod); } return null; } private ForwardingMethod setMethod(int methodIdentifier) { Tuple tuple = resolve(methodIdentifier); int componentIndex = tuple.componentIndex; Class componentClass; if (componentIndex == classes.size()) componentClass = Self.class; else componentClass = (Class) classes.get(componentIndex); Method delegateMethod = tuple.method; int componentClassIdentifier = ComponentClassRegister.getInstance().getIdentifier(componentClass); Class clazz = null; try { clazz = ClassGenerator.getClassLoader().loadClass("org.cq2.delegator.ComponentMethod" + methodIdentifier + "_" + componentClassIdentifier); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } ForwardingMethod result = null; try { result = (ForwardingMethod) clazz.newInstance(); clazz.getField("componentIndex").set(result, new Integer(componentIndex)); } catch (Exception e) { throw new RuntimeException(e); } implementingMethods[methodIdentifier] = result; componentIndexes[methodIdentifier] = componentIndex; return result; } private void enlargeArrays(int length) { ForwardingMethod[] oldComponentMethods = implementingMethods; implementingMethods = new ForwardingMethod[length]; System.arraycopy(oldComponentMethods, 0, implementingMethods, 0, oldComponentMethods.length); int[] oldComponentIndexes = componentIndexes; componentIndexes = new int[length]; System.arraycopy(oldComponentIndexes, 0, componentIndexes, 0, oldComponentIndexes.length); Arrays.fill(componentIndexes, oldComponentIndexes.length, componentIndexes.length - 1, -1); } public String toString() { return "ComposedClass: " + classes.toString(); } public ComposedClass getSuffix(int i) { if (i == 0) return this; return remove(0).getSuffix(i - 1); } }
vanschelven/delegator
org/cq2/delegator/internal/ComposedClass.java
1,951
// betekent dat hij protected of package is
line_comment
nl
package org.cq2.delegator.internal; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import org.cq2.delegator.Component; import org.cq2.delegator.Self; import org.cq2.delegator.internal.MethodsCache.Tuple; import org.cq2.delegator.method.MethodUtil; public class ComposedClass { private List classes; private ComposedClass[] removeReferences; private Map addMap; private Map insertMap; private ForwardingMethod[] implementingMethods; private static ComposedClass emptyClass; private int[] componentIndexes; private ComposedClass() { this(new ArrayList()); } ComposedClass(List classes) { this.classes = classes; removeReferences = new ComposedClass[classes.size()]; addMap = new HashMap(); insertMap = new HashMap(); implementingMethods = new ForwardingMethod[0]; componentIndexes = new int[0]; } public static ComposedClass getEmptyClass() { if (emptyClass == null) { emptyClass = ComposedClassCache.get(new ArrayList()); } return emptyClass; } public ComposedClass remove(int i) { ComposedClass result = removeReferences[i]; if (result == null) { List smallerClasses = new ArrayList(classes); smallerClasses.remove(i); result = ComposedClassCache.get(smallerClasses); removeReferences[i] = result; } return result; } public ComposedClass add(Class clazz) { ComposedClass result = (ComposedClass) addMap.get(clazz); if (result == null) { List largerClasses = new ArrayList(classes); largerClasses.add(clazz); result = ComposedClassCache.get(largerClasses); addMap.put(clazz, result); } return result; } public ComposedClass insert(Class clazz) { ComposedClass result = (ComposedClass) insertMap.get(clazz); if (result == null) { List largerClasses = new ArrayList(classes); largerClasses.add(0, clazz); result = ComposedClassCache.get(largerClasses); insertMap.put(clazz, result); } return result; } public int getComponentIndex(int methodIdentifier) { if (methodIdentifier < componentIndexes.length) { int result = componentIndexes[methodIdentifier]; if (result != -1) return result; } else enlargeArrays(methodIdentifier + 1); setMethod(methodIdentifier); return componentIndexes[methodIdentifier]; } public ForwardingMethod getMethod(int methodIdentifier) { if (methodIdentifier < implementingMethods.length) { ForwardingMethod result = implementingMethods[methodIdentifier]; if (result != null) return result; } else enlargeArrays(methodIdentifier + 1); return setMethod(methodIdentifier); } private Tuple resolve(int uniqueIdentifier) { Method method = ForwardingMethodRegister.getInstance().getMethod(uniqueIdentifier); //TODO synchronization noodzaak opnieuw checken. if ("hashCode".equals(method.getName()) || "equals".equals(method.getName())) return resolve(method, classes.size(), Self.class); int i = 0; for (; i < classes.size(); i++) { Class clazz = (Class) classes.get(i); Tuple result = resolve(method, i, clazz); if (result != null) return result; } Tuple result = resolve(method, classes.size(), Self.class); if (result != null) return result; throw new NoSuchMethodError(method.toString()); } private Tuple resolve(Method method, int i, Class clazz) { Method delegateMethod; boolean componentMethodIsProtected = false; if (Component.class.isAssignableFrom(clazz)) { delegateMethod = MethodUtil.getDeclaredMethod(clazz, method.getName() + ClassGenerator.SUPERCALL_POSTFIX, method.getParameterTypes(), method.getExceptionTypes()); //De superdelegatemethod is feitelijk de methode zoals // ingetiept door de programmeur //deze bestaat per definitie - als die niet gevonden wordt // betekent dat<SUF> Method superDelegateMethod = MethodUtil.getDeclaredMethod( clazz.getSuperclass(), method.getName(), method.getParameterTypes(), method.getExceptionTypes()); componentMethodIsProtected = (delegateMethod != null) && (superDelegateMethod == null); } else { delegateMethod = MethodUtil.getDeclaredMethod(clazz, method.getName(), method.getParameterTypes(), method.getExceptionTypes()); if (delegateMethod != null) componentMethodIsProtected = Modifier .isProtected(delegateMethod.getModifiers()); } if (delegateMethod != null && (!componentMethodIsProtected || Modifier .isProtected(method.getModifiers())) || !Modifier.isPublic(method.getModifiers())) { return new Tuple(i, delegateMethod); } return null; } private ForwardingMethod setMethod(int methodIdentifier) { Tuple tuple = resolve(methodIdentifier); int componentIndex = tuple.componentIndex; Class componentClass; if (componentIndex == classes.size()) componentClass = Self.class; else componentClass = (Class) classes.get(componentIndex); Method delegateMethod = tuple.method; int componentClassIdentifier = ComponentClassRegister.getInstance().getIdentifier(componentClass); Class clazz = null; try { clazz = ClassGenerator.getClassLoader().loadClass("org.cq2.delegator.ComponentMethod" + methodIdentifier + "_" + componentClassIdentifier); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } ForwardingMethod result = null; try { result = (ForwardingMethod) clazz.newInstance(); clazz.getField("componentIndex").set(result, new Integer(componentIndex)); } catch (Exception e) { throw new RuntimeException(e); } implementingMethods[methodIdentifier] = result; componentIndexes[methodIdentifier] = componentIndex; return result; } private void enlargeArrays(int length) { ForwardingMethod[] oldComponentMethods = implementingMethods; implementingMethods = new ForwardingMethod[length]; System.arraycopy(oldComponentMethods, 0, implementingMethods, 0, oldComponentMethods.length); int[] oldComponentIndexes = componentIndexes; componentIndexes = new int[length]; System.arraycopy(oldComponentIndexes, 0, componentIndexes, 0, oldComponentIndexes.length); Arrays.fill(componentIndexes, oldComponentIndexes.length, componentIndexes.length - 1, -1); } public String toString() { return "ComposedClass: " + classes.toString(); } public ComposedClass getSuffix(int i) { if (i == 0) return this; return remove(0).getSuffix(i - 1); } }
True
False
1,600
4,126
117915_0
package nl.topicus.patientcase; import nl.topicus.patientcase.models.Patient; import nl.topicus.patientcase.models.Recipe; import nl.topicus.patientcase.services.PatientService; import nl.topicus.patientcase.services.RecipeService; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @SpringBootApplication public class PatientCaseApplication { public static void main(String[] args) { SpringApplication.run(PatientCaseApplication.class, args); } @Bean public CommandLineRunner demo(PatientService patients, RecipeService recipes){ return (args) -> { // Vul database met voorbeeldrecepten en patiënten List<Recipe> l = new ArrayList<>(); Recipe r = new Recipe("Asperine", 500, "mg"); recipes.save(r); l.add(r); r = new Recipe("Medicijn X", 2, "tabletten"); r.setDescription("Een placebo."); recipes.save(r); l.add(r); r = new Recipe("Lembas bread", 1, "hapje"); r.setDescription("Een hapje is genoeg voor een hele dag."); recipes.save(r); l.add(r); r = new Recipe("Xanax", 1, "pil"); r.setDescription("Generieke naam: Alprazolam."); recipes.save(r); l.add(r); r = new Recipe("Codeïne", 1, "pil"); r.setDescription("Pijnstiller, werkt tegen kriebelhoest."); recipes.save(r); l.add(r); r = new Recipe("Nasacort", 1, "eenheid"); recipes.save(r); l.add(r); r = new Recipe("Tamoxifen", 1, "eenheid"); recipes.save(r); l.add(r); r = new Recipe("Morfine", 1, "eenheid"); recipes.save(r); l.add(r); r = new Recipe("Prednisolol acetaat+benzalkoniumchloride", 1, "druppel per oog"); r.setDescription("Oogdruppels."); recipes.save(r); l.add(r); Patient p = new Patient("Iemand", "Anders", LocalDate.of(1965, 3, 9), "23456235789", "v", "Straatstraat 153", "1234AB", "1234567", "Werkstraat 3", "1234AB"); p.addRecipe(l.get(5)); patients.save(p); p = new Patient("Niemand", "Anders", LocalDate.of(1966, 7, 21), "5343896710", "v", "Straatstraat 153", "1234AB", "1234567", "Arbeidstraat 33", "1234AB"); p.addRecipe(l.get(7)); patients.save(p); p = new Patient("Bilbo", "Baggins", LocalDate.of(1690, 6, 12), "12345678910", "m", "The Shire", "1111TS", "000000", "", ""); p.addRecipe(l.get(1)); p.addRecipe(l.get(0)); patients.save(p); p = new Patient("Frodo", "Baggins", LocalDate.of(1750, 6, 12)); p.setGender("m"); p.setHomeAddress("The Shire"); p.setWorkAddress("Mount Doom"); p.addRecipe(l.get(2)); patients.save(p); p = new Patient("Naam", "Achternaam", LocalDate.of(2000, 1, 1)); p.setGender("m"); p.addRecipe(l.get(8)); patients.save(p); }; } }
rbaas1/PatientCase
patientcase-backend/src/main/java/nl/topicus/patientcase/PatientCaseApplication.java
1,134
// Vul database met voorbeeldrecepten en patiënten
line_comment
nl
package nl.topicus.patientcase; import nl.topicus.patientcase.models.Patient; import nl.topicus.patientcase.models.Recipe; import nl.topicus.patientcase.services.PatientService; import nl.topicus.patientcase.services.RecipeService; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @SpringBootApplication public class PatientCaseApplication { public static void main(String[] args) { SpringApplication.run(PatientCaseApplication.class, args); } @Bean public CommandLineRunner demo(PatientService patients, RecipeService recipes){ return (args) -> { // Vul database<SUF> List<Recipe> l = new ArrayList<>(); Recipe r = new Recipe("Asperine", 500, "mg"); recipes.save(r); l.add(r); r = new Recipe("Medicijn X", 2, "tabletten"); r.setDescription("Een placebo."); recipes.save(r); l.add(r); r = new Recipe("Lembas bread", 1, "hapje"); r.setDescription("Een hapje is genoeg voor een hele dag."); recipes.save(r); l.add(r); r = new Recipe("Xanax", 1, "pil"); r.setDescription("Generieke naam: Alprazolam."); recipes.save(r); l.add(r); r = new Recipe("Codeïne", 1, "pil"); r.setDescription("Pijnstiller, werkt tegen kriebelhoest."); recipes.save(r); l.add(r); r = new Recipe("Nasacort", 1, "eenheid"); recipes.save(r); l.add(r); r = new Recipe("Tamoxifen", 1, "eenheid"); recipes.save(r); l.add(r); r = new Recipe("Morfine", 1, "eenheid"); recipes.save(r); l.add(r); r = new Recipe("Prednisolol acetaat+benzalkoniumchloride", 1, "druppel per oog"); r.setDescription("Oogdruppels."); recipes.save(r); l.add(r); Patient p = new Patient("Iemand", "Anders", LocalDate.of(1965, 3, 9), "23456235789", "v", "Straatstraat 153", "1234AB", "1234567", "Werkstraat 3", "1234AB"); p.addRecipe(l.get(5)); patients.save(p); p = new Patient("Niemand", "Anders", LocalDate.of(1966, 7, 21), "5343896710", "v", "Straatstraat 153", "1234AB", "1234567", "Arbeidstraat 33", "1234AB"); p.addRecipe(l.get(7)); patients.save(p); p = new Patient("Bilbo", "Baggins", LocalDate.of(1690, 6, 12), "12345678910", "m", "The Shire", "1111TS", "000000", "", ""); p.addRecipe(l.get(1)); p.addRecipe(l.get(0)); patients.save(p); p = new Patient("Frodo", "Baggins", LocalDate.of(1750, 6, 12)); p.setGender("m"); p.setHomeAddress("The Shire"); p.setWorkAddress("Mount Doom"); p.addRecipe(l.get(2)); patients.save(p); p = new Patient("Naam", "Achternaam", LocalDate.of(2000, 1, 1)); p.setGender("m"); p.addRecipe(l.get(8)); patients.save(p); }; } }
True
False
1,601
83
23980_10
package mastermind; import java.util.Random; import java.util.Scanner; import java.util.concurrent.TimeUnit; public class MasterMind { public static final String BLACK_BOLD_BRIGHT = "\033[1;90m"; public static final String WHITE_BOLD_BRIGHT = "\033[1;97m"; public static final String BLUE_BOLD_BRIGHT = "\033[1;94m"; public static final String RED_BOLD_BRIGHT = "\033[1;91m"; public static final String GREEN_BOLD_BRIGHT = "\033[1;92m"; public static final String BLACK_BOLD = "\033[1;30m"; public static final String WHITE_BOLD = "\033[1;37m"; public static final String ANSI_CYAN = "\u001B[36m"; public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_YELLOW = "\u001B[33m"; // hierboven zie je de kleurcodes die je kunt toepassen bij tekst om het een // kleur te geven. public static void main(String[] args) throws InterruptedException { Scanner invoer = new Scanner(System.in); System.out.println(BLUE_BOLD_BRIGHT + "Hier komt wat uitleg"); TimeUnit.MILLISECONDS.sleep(600); System.out.println(BLACK_BOLD + "\nZwart" + BLUE_BOLD_BRIGHT + " = goede plek"); TimeUnit.MILLISECONDS.sleep(600); System.out.println(WHITE_BOLD + "Wit" + BLUE_BOLD_BRIGHT + " = erin, verkeerde plek"); TimeUnit.MILLISECONDS.sleep(600); System.out.println("Niks = nummer er niet in"); TimeUnit.MILLISECONDS.sleep(600); System.out.println("Geef een getal van 1 tot 6"); TimeUnit.MILLISECONDS.sleep(600); System.out.println("Je krijgt 10 beurten"); TimeUnit.MILLISECONDS.sleep(600); System.out.println(GREEN_BOLD_BRIGHT + "Veel plezier en succes met raden!" + ANSI_RESET); TimeUnit.MILLISECONDS.sleep(600); // hierboven geef ik wat uitleg over het spel met 600 miliseconden ertussen // voordat de volgende regel afgedrukt wordt. int gok1, gok2, gok3, gok4, zwart = 0, wit = 0, beurt = 0; boolean winnaar = false; Random rand = new Random(); int code1 = rand.nextInt(6) + 1; int code2 = rand.nextInt(6) + 1; int code3 = rand.nextInt(6) + 1; int code4 = rand.nextInt(6) + 1; System.out.println("" + code1 + code2 + code3 + code4); // hierboven heb ik gezorgd dat de integers code 1 tot 4 een random getal tot de // 6 hebben en beginnen bij 1. while (beurt < 10 && !winnaar) { System.out.println(BLACK_BOLD_BRIGHT + "\n\nGeef je eerste gok" + ANSI_CYAN); gok1 = invoer.nextInt(); System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je tweede gok" + ANSI_CYAN); gok2 = invoer.nextInt(); System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je derde gok" + ANSI_CYAN); gok3 = invoer.nextInt(); System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je vierde gok" + ANSI_CYAN); gok4 = invoer.nextInt(); beurt++; // hierboven geef ik aan dat je 4 gokken (cijfers van 1 tot 6) in moet voeren en // elke keer dat je dat doet wordt er 1 opgetelt bij je beurten. if (gok1 == code1) { zwart++; } else if (gok1 == code2 || gok1 == code3 || gok1 == code4) { wit++; } if (gok2 == code2) { zwart++; } else if (gok2 == code1 || gok2 == code3 || gok2 == code4) { wit++; } if (gok3 == code3) { zwart++; } else if (gok3 == code1 || gok3 == code2 || gok3 == code4) { wit++; } if (gok4 == code4) { zwart++; } else if (gok4 == code1 || gok4 == code2 || gok4 == code3) { wit++; } if (zwart == 4) { System.out.println(ANSI_YELLOW + "Je hebt gewonnen!!" + ANSI_RESET); winnaar = true; // hier wordt gecheckt of je 4 keer een zwarte, dus een goede heb gehaald en als // dat zo is dan wordt er uitgeprint dat je gewonnen hebt. } if (gok1 == code1 || gok2 == code2 || gok3 == code3 || gok4 == code4) { wit = 0; } if (zwart < 4) { System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Aantal " + BLACK_BOLD + "zwarten: " + WHITE_BOLD_BRIGHT + zwart); System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Aantal " + WHITE_BOLD + "witte: " + WHITE_BOLD_BRIGHT + wit); System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Je zit op je " + WHITE_BOLD_BRIGHT + beurt + "e" + ANSI_RESET + " beurt"); wit = 0; zwart = 0; } // hier geeft hij na elke beurt aan hoeveel zwarten en hoeveel witte je goed // hebt geraden. if (beurt == 10) { System.out.println(RED_BOLD_BRIGHT + "\nHelaas je beurten zijn op"); // hier wordt gecheckt of je 10 beurten heb gebruikt en als dat zo is dan geeft // hij aan dat je beurten op zijn en dan kun je niet meer verder spelen. } } } }
AlecPeters2312/Portfolio-Website-2
downloads/MasterMind.java
1,881
// hier geeft hij na elke beurt aan hoeveel zwarten en hoeveel witte je goed
line_comment
nl
package mastermind; import java.util.Random; import java.util.Scanner; import java.util.concurrent.TimeUnit; public class MasterMind { public static final String BLACK_BOLD_BRIGHT = "\033[1;90m"; public static final String WHITE_BOLD_BRIGHT = "\033[1;97m"; public static final String BLUE_BOLD_BRIGHT = "\033[1;94m"; public static final String RED_BOLD_BRIGHT = "\033[1;91m"; public static final String GREEN_BOLD_BRIGHT = "\033[1;92m"; public static final String BLACK_BOLD = "\033[1;30m"; public static final String WHITE_BOLD = "\033[1;37m"; public static final String ANSI_CYAN = "\u001B[36m"; public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_YELLOW = "\u001B[33m"; // hierboven zie je de kleurcodes die je kunt toepassen bij tekst om het een // kleur te geven. public static void main(String[] args) throws InterruptedException { Scanner invoer = new Scanner(System.in); System.out.println(BLUE_BOLD_BRIGHT + "Hier komt wat uitleg"); TimeUnit.MILLISECONDS.sleep(600); System.out.println(BLACK_BOLD + "\nZwart" + BLUE_BOLD_BRIGHT + " = goede plek"); TimeUnit.MILLISECONDS.sleep(600); System.out.println(WHITE_BOLD + "Wit" + BLUE_BOLD_BRIGHT + " = erin, verkeerde plek"); TimeUnit.MILLISECONDS.sleep(600); System.out.println("Niks = nummer er niet in"); TimeUnit.MILLISECONDS.sleep(600); System.out.println("Geef een getal van 1 tot 6"); TimeUnit.MILLISECONDS.sleep(600); System.out.println("Je krijgt 10 beurten"); TimeUnit.MILLISECONDS.sleep(600); System.out.println(GREEN_BOLD_BRIGHT + "Veel plezier en succes met raden!" + ANSI_RESET); TimeUnit.MILLISECONDS.sleep(600); // hierboven geef ik wat uitleg over het spel met 600 miliseconden ertussen // voordat de volgende regel afgedrukt wordt. int gok1, gok2, gok3, gok4, zwart = 0, wit = 0, beurt = 0; boolean winnaar = false; Random rand = new Random(); int code1 = rand.nextInt(6) + 1; int code2 = rand.nextInt(6) + 1; int code3 = rand.nextInt(6) + 1; int code4 = rand.nextInt(6) + 1; System.out.println("" + code1 + code2 + code3 + code4); // hierboven heb ik gezorgd dat de integers code 1 tot 4 een random getal tot de // 6 hebben en beginnen bij 1. while (beurt < 10 && !winnaar) { System.out.println(BLACK_BOLD_BRIGHT + "\n\nGeef je eerste gok" + ANSI_CYAN); gok1 = invoer.nextInt(); System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je tweede gok" + ANSI_CYAN); gok2 = invoer.nextInt(); System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je derde gok" + ANSI_CYAN); gok3 = invoer.nextInt(); System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je vierde gok" + ANSI_CYAN); gok4 = invoer.nextInt(); beurt++; // hierboven geef ik aan dat je 4 gokken (cijfers van 1 tot 6) in moet voeren en // elke keer dat je dat doet wordt er 1 opgetelt bij je beurten. if (gok1 == code1) { zwart++; } else if (gok1 == code2 || gok1 == code3 || gok1 == code4) { wit++; } if (gok2 == code2) { zwart++; } else if (gok2 == code1 || gok2 == code3 || gok2 == code4) { wit++; } if (gok3 == code3) { zwart++; } else if (gok3 == code1 || gok3 == code2 || gok3 == code4) { wit++; } if (gok4 == code4) { zwart++; } else if (gok4 == code1 || gok4 == code2 || gok4 == code3) { wit++; } if (zwart == 4) { System.out.println(ANSI_YELLOW + "Je hebt gewonnen!!" + ANSI_RESET); winnaar = true; // hier wordt gecheckt of je 4 keer een zwarte, dus een goede heb gehaald en als // dat zo is dan wordt er uitgeprint dat je gewonnen hebt. } if (gok1 == code1 || gok2 == code2 || gok3 == code3 || gok4 == code4) { wit = 0; } if (zwart < 4) { System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Aantal " + BLACK_BOLD + "zwarten: " + WHITE_BOLD_BRIGHT + zwart); System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Aantal " + WHITE_BOLD + "witte: " + WHITE_BOLD_BRIGHT + wit); System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Je zit op je " + WHITE_BOLD_BRIGHT + beurt + "e" + ANSI_RESET + " beurt"); wit = 0; zwart = 0; } // hier geeft<SUF> // hebt geraden. if (beurt == 10) { System.out.println(RED_BOLD_BRIGHT + "\nHelaas je beurten zijn op"); // hier wordt gecheckt of je 10 beurten heb gebruikt en als dat zo is dan geeft // hij aan dat je beurten op zijn en dan kun je niet meer verder spelen. } } } }
True
False
1,603