index
int64 1
4.82k
| file_id
stringlengths 6
9
| content
stringlengths 240
14.6k
| repo
stringlengths 9
82
| path
stringlengths 8
129
| token_length
int64 72
3.85k
| original_comment
stringlengths 13
1.35k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 142
14.6k
| Excluded
bool 1
class | file-tokens-Qwen/Qwen2-7B
int64 64
3.93k
| comment-tokens-Qwen/Qwen2-7B
int64 4
476
| file-tokens-bigcode/starcoder2-7b
int64 74
3.98k
| comment-tokens-bigcode/starcoder2-7b
int64 4
458
| file-tokens-google/codegemma-7b
int64 56
3.99k
| comment-tokens-google/codegemma-7b
int64 4
472
| file-tokens-ibm-granite/granite-8b-code-base
int64 74
3.98k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 4
458
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 77
4.07k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 4
496
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,030 | 172967_3 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hellotvxlet;
import org.havi.ui.*;
import java.awt.*;
import org.dvb.ui.*;
/**
*
* @author student
*/
public class Sprite extends HComponent {
private Image spaceship;
private MediaTracker mtrack;
//plaats en lovatie instellen in de constructor
public Sprite(String file, int x, int y)
{
spaceship = this.getToolkit().getImage(file);
mtrack = new MediaTracker(this);
mtrack.addImage(spaceship, 0);
try
{
mtrack.waitForAll(); // wacht tot alle bitmaps geladen zijn
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap
}
//paint methode overschrijven
public void paint(Graphics g)
{
g.drawImage(spaceship, 0, 0, null);
}
public void Verplaats(int x, int y)
{
this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this));
}
}
| MTA-Digital-Broadcast-2/K-De-Maeyer-Didier-Schuddinck-Sam-Project-MHP | Didier De Maeyer/blz47/Oef1/HelloTVXlet/src/hellotvxlet/Sprite.java | 367 | // wacht tot alle bitmaps geladen zijn | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hellotvxlet;
import org.havi.ui.*;
import java.awt.*;
import org.dvb.ui.*;
/**
*
* @author student
*/
public class Sprite extends HComponent {
private Image spaceship;
private MediaTracker mtrack;
//plaats en lovatie instellen in de constructor
public Sprite(String file, int x, int y)
{
spaceship = this.getToolkit().getImage(file);
mtrack = new MediaTracker(this);
mtrack.addImage(spaceship, 0);
try
{
mtrack.waitForAll(); // wacht tot<SUF>
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap
}
//paint methode overschrijven
public void paint(Graphics g)
{
g.drawImage(spaceship, 0, 0, null);
}
public void Verplaats(int x, int y)
{
this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this));
}
}
| false | 271 | 10 | 313 | 11 | 330 | 8 | 313 | 11 | 369 | 10 | false | false | false | false | false | true |
600 | 11641_4 | import java.util.ArrayList;_x000D_
_x000D_
/**_x000D_
* Presentation houdt de slides in de presentatie bij._x000D_
* <p>_x000D_
* In the Presentation's world, page numbers go from 0 to n-1 * <p>_x000D_
* This program is distributed under the terms of the accompanying_x000D_
* COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_
* Please read it. Your use of the software constitutes acceptance_x000D_
* of the terms in the COPYRIGHT.txt file._x000D_
* @author Ian F. Darwin, [email protected]_x000D_
* @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn_x000D_
* @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman_x000D_
* @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_
* @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_
*/_x000D_
_x000D_
// Verandering: Presentation wordt een Observable_x000D_
public class Presentation {_x000D_
private String showTitle; // de titel van de presentatie_x000D_
private ArrayList<Slide> showList = null; // een ArrayList met de Slides_x000D_
private int currentSlideNumber = 0; // het slidenummer van de huidige Slide_x000D_
// Verandering: we kennen slideViewComponent niet meer direct_x000D_
// private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides_x000D_
_x000D_
public Presentation() {_x000D_
// Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut_x000D_
//slideViewComponent = null;_x000D_
clear();_x000D_
}_x000D_
_x000D_
// Methode die wordt gebruikt door de Controller_x000D_
// om te bepalen wat er getoond wordt._x000D_
public int getSize() {_x000D_
return showList.size();_x000D_
}_x000D_
_x000D_
public String getTitle() {_x000D_
return showTitle;_x000D_
}_x000D_
_x000D_
public void setTitle(String nt) {_x000D_
showTitle = nt;_x000D_
}_x000D_
_x000D_
// Verandering: deze methode hebben we niet meer nodig_x000D_
// public void setShowView(SlideViewerComponent slideViewerComponent) {_x000D_
// this.slideViewComponent = slideViewerComponent;_x000D_
// }_x000D_
_x000D_
// geef het nummer van de huidige slide_x000D_
public int getSlideNumber() {_x000D_
return currentSlideNumber;_x000D_
}_x000D_
_x000D_
// verander het huidige-slide-nummer en laat het aan het window weten._x000D_
public void setSlideNumber(int number) {_x000D_
currentSlideNumber = number;_x000D_
// Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon_x000D_
//if (slideViewComponent != null) {_x000D_
// slideViewComponent.update(this, getCurrentSlide());_x000D_
//}_x000D_
}_x000D_
_x000D_
// Verwijder de presentatie, om klaar te zijn voor de volgende_x000D_
void clear() {_x000D_
showList = new ArrayList<Slide>();_x000D_
setTitle("New presentation");_x000D_
setSlideNumber(-1);_x000D_
}_x000D_
_x000D_
// Voeg een slide toe aan de presentatie_x000D_
public void append(Slide slide) {_x000D_
showList.add(slide);_x000D_
}_x000D_
_x000D_
// Geef een slide met een bepaald slidenummer_x000D_
public Slide getSlide(int number) {_x000D_
if (number < 0 || number >= getSize()){_x000D_
return null;_x000D_
}_x000D_
return (Slide)showList.get(number);_x000D_
}_x000D_
_x000D_
// Geef de huidige Slide_x000D_
public Slide getCurrentSlide() {_x000D_
return getSlide(currentSlideNumber);_x000D_
}_x000D_
}_x000D_
| GertSallaerts/jabbertest | Presentation.java | 935 | // het slidenummer van de huidige Slide_x000D_ | line_comment | nl | import java.util.ArrayList;_x000D_
_x000D_
/**_x000D_
* Presentation houdt de slides in de presentatie bij._x000D_
* <p>_x000D_
* In the Presentation's world, page numbers go from 0 to n-1 * <p>_x000D_
* This program is distributed under the terms of the accompanying_x000D_
* COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_
* Please read it. Your use of the software constitutes acceptance_x000D_
* of the terms in the COPYRIGHT.txt file._x000D_
* @author Ian F. Darwin, [email protected]_x000D_
* @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn_x000D_
* @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman_x000D_
* @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_
* @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_
*/_x000D_
_x000D_
// Verandering: Presentation wordt een Observable_x000D_
public class Presentation {_x000D_
private String showTitle; // de titel van de presentatie_x000D_
private ArrayList<Slide> showList = null; // een ArrayList met de Slides_x000D_
private int currentSlideNumber = 0; // het slidenummer<SUF>
// Verandering: we kennen slideViewComponent niet meer direct_x000D_
// private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides_x000D_
_x000D_
public Presentation() {_x000D_
// Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut_x000D_
//slideViewComponent = null;_x000D_
clear();_x000D_
}_x000D_
_x000D_
// Methode die wordt gebruikt door de Controller_x000D_
// om te bepalen wat er getoond wordt._x000D_
public int getSize() {_x000D_
return showList.size();_x000D_
}_x000D_
_x000D_
public String getTitle() {_x000D_
return showTitle;_x000D_
}_x000D_
_x000D_
public void setTitle(String nt) {_x000D_
showTitle = nt;_x000D_
}_x000D_
_x000D_
// Verandering: deze methode hebben we niet meer nodig_x000D_
// public void setShowView(SlideViewerComponent slideViewerComponent) {_x000D_
// this.slideViewComponent = slideViewerComponent;_x000D_
// }_x000D_
_x000D_
// geef het nummer van de huidige slide_x000D_
public int getSlideNumber() {_x000D_
return currentSlideNumber;_x000D_
}_x000D_
_x000D_
// verander het huidige-slide-nummer en laat het aan het window weten._x000D_
public void setSlideNumber(int number) {_x000D_
currentSlideNumber = number;_x000D_
// Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon_x000D_
//if (slideViewComponent != null) {_x000D_
// slideViewComponent.update(this, getCurrentSlide());_x000D_
//}_x000D_
}_x000D_
_x000D_
// Verwijder de presentatie, om klaar te zijn voor de volgende_x000D_
void clear() {_x000D_
showList = new ArrayList<Slide>();_x000D_
setTitle("New presentation");_x000D_
setSlideNumber(-1);_x000D_
}_x000D_
_x000D_
// Voeg een slide toe aan de presentatie_x000D_
public void append(Slide slide) {_x000D_
showList.add(slide);_x000D_
}_x000D_
_x000D_
// Geef een slide met een bepaald slidenummer_x000D_
public Slide getSlide(int number) {_x000D_
if (number < 0 || number >= getSize()){_x000D_
return null;_x000D_
}_x000D_
return (Slide)showList.get(number);_x000D_
}_x000D_
_x000D_
// Geef de huidige Slide_x000D_
public Slide getCurrentSlide() {_x000D_
return getSlide(currentSlideNumber);_x000D_
}_x000D_
}_x000D_
| false | 1,280 | 17 | 1,460 | 19 | 1,393 | 16 | 1,460 | 19 | 1,552 | 20 | false | false | false | false | false | true |
645 | 69594_0 | package AbsentieLijst.userInterfaceLaag;_x000D_
_x000D_
import AbsentieLijst.*;_x000D_
import javafx.collections.FXCollections;_x000D_
import javafx.collections.ObservableList;_x000D_
import javafx.event.ActionEvent;_x000D_
import javafx.fxml.FXMLLoader;_x000D_
import javafx.scene.Parent;_x000D_
import javafx.scene.Scene;_x000D_
import javafx.scene.control.Button;_x000D_
import javafx.scene.control.ComboBox;_x000D_
import javafx.scene.control.DatePicker;_x000D_
import javafx.scene.control.Label;_x000D_
import javafx.scene.image.Image;_x000D_
import javafx.stage.Modality;_x000D_
import javafx.stage.Stage;_x000D_
_x000D_
import java.sql.Time;_x000D_
import java.time.LocalDate;_x000D_
import java.util.ArrayList;_x000D_
import java.util.HashMap;_x000D_
_x000D_
public class ToekomstigAfmeldenController {_x000D_
public Button ButtonOpslaan;_x000D_
public Button ButtonAnnuleren;_x000D_
public DatePicker DatePickerDate;_x000D_
public ComboBox ComboBoxReden;_x000D_
public static ArrayList<Afspraak> afGmeld = new ArrayList<>();_x000D_
public Button overzicht;_x000D_
public Label label;_x000D_
public ComboBox tijd;_x000D_
_x000D_
School HU = School.getSchool();_x000D_
ObservableList<String> options =_x000D_
FXCollections.observableArrayList(_x000D_
"Bruiloft",_x000D_
"Tandarts afspraak",_x000D_
"Begravenis", "Wegens corona.", "Overig"_x000D_
);_x000D_
_x000D_
_x000D_
public void initialize() {_x000D_
ComboBoxReden.setItems(options);_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
public void ActionOpslaan(ActionEvent actionEvent) {_x000D_
if (DatePickerDate.getValue() != null && ComboBoxReden != null) {_x000D_
LocalDate datum = DatePickerDate.getValue();_x000D_
Object time = tijd.getValue();_x000D_
try {_x000D_
for (Klas klas : HU.getKlassen()) {_x000D_
for (Student student : klas.getStudenten()) {_x000D_
if (student.getisIngelogd()) {_x000D_
HashMap<String, Les> alleLessen = klas.getLessen();_x000D_
for (String lesNaam : alleLessen.keySet()) {_x000D_
if (alleLessen.get(lesNaam).getDatum().equals(datum)) {_x000D_
alleLessen.get(lesNaam).setAbsent(student, " met reden:"+" "+(String) ComboBoxReden.getValue()); //afgemeld_lijst in de les_x000D_
student.setAfgemeld("Vooraf afgemeld: " + alleLessen.get(lesNaam).getDatum() + " " + alleLessen.get(lesNaam).getLescode() + " met als reden: " + ComboBoxReden.getValue()); //afgemeld overzicht student._x000D_
Button source = (Button) actionEvent.getSource();_x000D_
Stage stage = (Stage) source.getScene().getWindow();_x000D_
stage.close();_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
} catch (Exception e) {_x000D_
label.setText("ddddd");_x000D_
}_x000D_
} else label.setText("Je moet Datum en reden kiezen");_x000D_
}_x000D_
_x000D_
public void ActionAnnuleren(ActionEvent actionEvent) {_x000D_
Button source = (Button) actionEvent.getSource();_x000D_
Stage stage = (Stage) source.getScene().getWindow();_x000D_
stage.close();_x000D_
}_x000D_
_x000D_
public void DatapickerOnAction(ActionEvent actionEvent) {_x000D_
ObservableList<String> lessen = FXCollections.observableArrayList();_x000D_
for (Klas klas : HU.getKlassen()) {_x000D_
for (Student student : klas.getStudenten()) {_x000D_
if (student.getisIngelogd()) {_x000D_
ArrayList<String> les = new ArrayList<>();_x000D_
_x000D_
HashMap<String, Les> alleLessen = klas.getLessen();_x000D_
for (Les lesNaam : alleLessen.values())_x000D_
if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {_x000D_
// for (String les1 : alleLessen.keySet()) {_x000D_
les.add(lesNaam.getNaam());_x000D_
lessen.addAll(les);_x000D_
tijd.setItems(lessen);_x000D_
}_x000D_
_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
| HBO-ICT-GP-SD/Laatsteversie | AbsentieLijst/src/AbsentieLijst/userInterfaceLaag/ToekomstigAfmeldenController.java | 1,160 | //afgemeld_lijst in de les_x000D_ | line_comment | nl | package AbsentieLijst.userInterfaceLaag;_x000D_
_x000D_
import AbsentieLijst.*;_x000D_
import javafx.collections.FXCollections;_x000D_
import javafx.collections.ObservableList;_x000D_
import javafx.event.ActionEvent;_x000D_
import javafx.fxml.FXMLLoader;_x000D_
import javafx.scene.Parent;_x000D_
import javafx.scene.Scene;_x000D_
import javafx.scene.control.Button;_x000D_
import javafx.scene.control.ComboBox;_x000D_
import javafx.scene.control.DatePicker;_x000D_
import javafx.scene.control.Label;_x000D_
import javafx.scene.image.Image;_x000D_
import javafx.stage.Modality;_x000D_
import javafx.stage.Stage;_x000D_
_x000D_
import java.sql.Time;_x000D_
import java.time.LocalDate;_x000D_
import java.util.ArrayList;_x000D_
import java.util.HashMap;_x000D_
_x000D_
public class ToekomstigAfmeldenController {_x000D_
public Button ButtonOpslaan;_x000D_
public Button ButtonAnnuleren;_x000D_
public DatePicker DatePickerDate;_x000D_
public ComboBox ComboBoxReden;_x000D_
public static ArrayList<Afspraak> afGmeld = new ArrayList<>();_x000D_
public Button overzicht;_x000D_
public Label label;_x000D_
public ComboBox tijd;_x000D_
_x000D_
School HU = School.getSchool();_x000D_
ObservableList<String> options =_x000D_
FXCollections.observableArrayList(_x000D_
"Bruiloft",_x000D_
"Tandarts afspraak",_x000D_
"Begravenis", "Wegens corona.", "Overig"_x000D_
);_x000D_
_x000D_
_x000D_
public void initialize() {_x000D_
ComboBoxReden.setItems(options);_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
public void ActionOpslaan(ActionEvent actionEvent) {_x000D_
if (DatePickerDate.getValue() != null && ComboBoxReden != null) {_x000D_
LocalDate datum = DatePickerDate.getValue();_x000D_
Object time = tijd.getValue();_x000D_
try {_x000D_
for (Klas klas : HU.getKlassen()) {_x000D_
for (Student student : klas.getStudenten()) {_x000D_
if (student.getisIngelogd()) {_x000D_
HashMap<String, Les> alleLessen = klas.getLessen();_x000D_
for (String lesNaam : alleLessen.keySet()) {_x000D_
if (alleLessen.get(lesNaam).getDatum().equals(datum)) {_x000D_
alleLessen.get(lesNaam).setAbsent(student, " met reden:"+" "+(String) ComboBoxReden.getValue()); //afgemeld_lijst in<SUF>
student.setAfgemeld("Vooraf afgemeld: " + alleLessen.get(lesNaam).getDatum() + " " + alleLessen.get(lesNaam).getLescode() + " met als reden: " + ComboBoxReden.getValue()); //afgemeld overzicht student._x000D_
Button source = (Button) actionEvent.getSource();_x000D_
Stage stage = (Stage) source.getScene().getWindow();_x000D_
stage.close();_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
} catch (Exception e) {_x000D_
label.setText("ddddd");_x000D_
}_x000D_
} else label.setText("Je moet Datum en reden kiezen");_x000D_
}_x000D_
_x000D_
public void ActionAnnuleren(ActionEvent actionEvent) {_x000D_
Button source = (Button) actionEvent.getSource();_x000D_
Stage stage = (Stage) source.getScene().getWindow();_x000D_
stage.close();_x000D_
}_x000D_
_x000D_
public void DatapickerOnAction(ActionEvent actionEvent) {_x000D_
ObservableList<String> lessen = FXCollections.observableArrayList();_x000D_
for (Klas klas : HU.getKlassen()) {_x000D_
for (Student student : klas.getStudenten()) {_x000D_
if (student.getisIngelogd()) {_x000D_
ArrayList<String> les = new ArrayList<>();_x000D_
_x000D_
HashMap<String, Les> alleLessen = klas.getLessen();_x000D_
for (Les lesNaam : alleLessen.values())_x000D_
if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {_x000D_
// for (String les1 : alleLessen.keySet()) {_x000D_
les.add(lesNaam.getNaam());_x000D_
lessen.addAll(les);_x000D_
tijd.setItems(lessen);_x000D_
}_x000D_
_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
| false | 1,461 | 16 | 1,586 | 17 | 1,603 | 16 | 1,586 | 17 | 1,762 | 17 | false | false | false | false | false | true |
4,470 | 18288_9 | /*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage 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.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server;
import de._13ducks.cor.debug.UltimateDebug;
import de._13ducks.cor.game.server.movement.ServerMoveManager;
import de._13ducks.cor.networks.server.ServerNetController;
import de._13ducks.cor.game.Building;
import de._13ducks.cor.game.Unit;
import de._13ducks.cor.game.NetPlayer.races;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import de._13ducks.cor.game.Core;
import de._13ducks.cor.game.NetPlayer;
import de._13ducks.cor.game.server.movement.ServerAttackManager;
/**
* Der Server-Kern
*
* Startet einen Server mit den dazugehörigen Server-Modulen etc...
*
* Erzeugt ein seperates Logfile (server_log.txt)
*
* @author tfg
*/
public class ServerCore extends Core {
ServerCore.InnerServer rgi;
ServerNetController servNet;
ServerMapModule mapMod;
ServerGameController gamectrl;
ServerStatistics sstat; //Statistik
ServerMoveManager smoveman;
public boolean ready; // gibt an, ob das Spiel gestartet werden soll.
public ServerCore(boolean debug, String Mapname) {
debugmode = debug;
rgi = new ServerCore.InnerServer();
initLogger();
rgi.logger("[Core] Reading config...");
if (debugmode) {
System.out.println("Configuration:");
}
// Konfigurationsdatei lesen
cfgvalues = new HashMap();
File cfgFile = new File("server_cfg.txt");
try {
FileReader cfgReader = new FileReader(cfgFile);
BufferedReader reader = new BufferedReader(cfgReader);
String zeile = null;
int i = 0; // Anzahl der Durchläufe zählen
while ((zeile = reader.readLine()) != null) {
// Liest Zeile fuer Zeile, jetzt auswerten und in Variablen
// schreiben
int indexgleich = zeile.indexOf('='); // Istgleich suchen
if (indexgleich == -1) {
} else {
String v1 = zeile.substring(0, indexgleich); // Vor dem =
// rauschneiden
String v2 = zeile.substring(indexgleich + 1); // Nach dem
// =
// rausschneiden
System.out.println(v1 + " = " + v2);
cfgvalues.put(v1, v2);
if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen
rgi.logger("[Core-Log] " + v1 + "=" + v2);
}
}
}
reader.close();
} catch (FileNotFoundException e1) {
// cfg-Datei nicht gefunden - inakzeptabel!
rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one...");
try {
cfgFile.createNewFile();
} catch (IOException ex) {
System.out.print("Error creating server_cfg.txt .");
}
//rgi.shutdown(1);
} catch (IOException e2) {
// Inakzeptabel
e2.printStackTrace();
rgi.logger("[Core-ERROR] Critical I/O Error");
rgi.shutdown(1);
}
if ("true".equals(cfgvalues.get("ultimateDebug"))) {
UltimateDebug udb = UltimateDebug.getInstance();
udb.authorizeDebug(this, rgi);
}
// Läuft als Server
rgi.logger("[CoreInit]: Starting server mode...");
// Module laden
rgi.logger("[CoreInit]: Loading modules...");
rgi.logger("[CoreInit]: Loading gamecontroller");
gamectrl = new ServerGameController(rgi);
// Netzwerk
rgi.logger("[CoreInit]: Loading serverNetController");
servNet = new ServerNetController(rgi, this);
rgi.logger("[CoreInit]: Loading serverMapmodul");
mapMod = new ServerMapModule(rgi);
rgi.logger("[CoreInit]: Loading serverStatistics");
sstat = new ServerStatistics(rgi);
rgi.logger("[CoreInit]: Loading serverMoveManager");
smoveman = new ServerMoveManager();
// Alle Module geladen, starten
rgi.initInner();
rgi.logger("[Core]: Initializing modules...");
mapMod.initModule();
rgi.logger("[Core]: Init done, starting Server...");
Thread t = new Thread(servNet);
t.start();
rgi.logger("[Core]: Server running");
try {
// Auf Startsignal warten
while (!this.ready) {
Thread.sleep(1000);
}
// Jetzt darf niemand mehr rein
servNet.closeAcception();
// Zufallsvölker bestimmen und allen Clients mitteilen:
for (NetPlayer p : this.gamectrl.playerList) {
if (p.lobbyRace == races.random) {
if (Math.rint(Math.random()) == 1) {
p.lobbyRace = 1;
this.servNet.broadcastString(("91" + p.nickName), (byte) 14);
} else {
p.lobbyRace = 2;
this.servNet.broadcastString(("92" + p.nickName), (byte) 14);
}
}
}
// Clients vorbereiten
servNet.loadGame();
// Warte darauf, das alle soweit sind
waitForStatus(1);
// Spiel laden
mapMod.loadMap(Mapname);
waitForStatus(2);
// Game vorbereiten
servNet.initGame((byte) 8);
// Starteinheiten & Gebäude an das gewählte Volk anpassen:
for (NetPlayer player : this.gamectrl.playerList) {
// Gebäude:
for (Building building : this.rgi.netmap.buildingList) {
if (building.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
building.performUpgrade(rgi, 1001);
} else if (player.lobbyRace == races.human) {
building.performUpgrade(rgi, 1);
}
}
}
// Einheiten:
for (Unit unit : this.rgi.netmap.unitList) {
if (unit.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
// 401=human worker, 1401=undead worker
if (unit.getDescTypeId() == 401) {
unit.performUpgrade(rgi, 1401);
}
// 402=human scout, 1402=undead mage
if (unit.getDescTypeId() == 402) {
unit.performUpgrade(rgi, 1402);
}
} else if (player.lobbyRace == races.human) {
// 1401=undead worker, 401=human worker
if (unit.getDescTypeId() == 1401) {
unit.performUpgrade(rgi, 401);
}
// 1402=undead mage, 402=human scout
if (unit.getDescTypeId() == 1402) {
unit.performUpgrade(rgi, 402);
}
}
}
}
}
waitForStatus(3);
servNet.startGame();
} catch (InterruptedException ex) {
}
}
/**
* Synchronisierte Funktipon zum Strings senden
* wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat
* @param s - zu sendender String
* @param cmdid - command-id
*/
public synchronized void broadcastStringSynchronized(String s, byte cmdid) {
s += "\0";
this.servNet.broadcastString(s, cmdid);
}
private void waitForStatus(int status) throws InterruptedException {
while (true) {
Thread.sleep(50);
boolean go = true;
for (ServerNetController.ServerHandler servhan : servNet.clientconnection) {
if (servhan.loadStatus < status) {
go = false;
break;
}
}
if (go) {
break;
}
}
}
@Override
public void initLogger() {
if (!logOFF) {
// Erstellt ein neues Logfile
try {
FileWriter logcreator = new FileWriter("server_log.txt");
logcreator.close();
} catch (IOException ex) {
// Warscheinlich darf man das nicht, den Adminmodus emfehlen
JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
rgi.shutdown(2);
}
}
}
public class InnerServer extends Core.CoreInner {
public ServerNetController netctrl;
public ServerMapModule netmap;
public ServerGameController game;
public ServerStatistics serverstats;
String lastlog = "";
public ServerMoveManager moveMan;
public ServerAttackManager atkMan;
@Override
public void initInner() {
super.initInner();
// Server-Referenz initialisiern:
Server.setInnerServer(this);
netctrl = servNet;
netmap = mapMod;
game = gamectrl;
serverstats = sstat;
moveMan = smoveman;
atkMan = new ServerAttackManager();
}
@Override
public void logger(String x) {
if (!logOFF) {
if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern
lastlog = x;
// Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die
// log-Datei
try {
FileWriter logwriter = new FileWriter("server_log.txt", true);
String temp = String.format("%tc", new Date()) + " - " + x + "\n";
logwriter.append(temp);
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
@Override
public void logger(Throwable t) {
if (!logOFF) {
// Nimmt Exceptions an und schreibt den Stacktrace ins
// logfile
try {
if (debugmode) {
System.out.println("ERROR!!!! More info in logfile...");
}
FileWriter logwriter = new FileWriter("server_log.txt", true);
logwriter.append('\n' + String.format("%tc", new Date()) + " - ");
logwriter.append("[JavaError]: " + t.toString() + '\n');
StackTraceElement[] errorArray;
errorArray = t.getStackTrace();
for (int i = 0; i < errorArray.length; i++) {
logwriter.append(" " + errorArray[i].toString() + '\n');
}
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
}
| tfg13/Centuries-of-Rage | src/de/_13ducks/cor/game/server/ServerCore.java | 3,501 | // Alle Module geladen, starten | line_comment | nl | /*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage 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.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server;
import de._13ducks.cor.debug.UltimateDebug;
import de._13ducks.cor.game.server.movement.ServerMoveManager;
import de._13ducks.cor.networks.server.ServerNetController;
import de._13ducks.cor.game.Building;
import de._13ducks.cor.game.Unit;
import de._13ducks.cor.game.NetPlayer.races;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import de._13ducks.cor.game.Core;
import de._13ducks.cor.game.NetPlayer;
import de._13ducks.cor.game.server.movement.ServerAttackManager;
/**
* Der Server-Kern
*
* Startet einen Server mit den dazugehörigen Server-Modulen etc...
*
* Erzeugt ein seperates Logfile (server_log.txt)
*
* @author tfg
*/
public class ServerCore extends Core {
ServerCore.InnerServer rgi;
ServerNetController servNet;
ServerMapModule mapMod;
ServerGameController gamectrl;
ServerStatistics sstat; //Statistik
ServerMoveManager smoveman;
public boolean ready; // gibt an, ob das Spiel gestartet werden soll.
public ServerCore(boolean debug, String Mapname) {
debugmode = debug;
rgi = new ServerCore.InnerServer();
initLogger();
rgi.logger("[Core] Reading config...");
if (debugmode) {
System.out.println("Configuration:");
}
// Konfigurationsdatei lesen
cfgvalues = new HashMap();
File cfgFile = new File("server_cfg.txt");
try {
FileReader cfgReader = new FileReader(cfgFile);
BufferedReader reader = new BufferedReader(cfgReader);
String zeile = null;
int i = 0; // Anzahl der Durchläufe zählen
while ((zeile = reader.readLine()) != null) {
// Liest Zeile fuer Zeile, jetzt auswerten und in Variablen
// schreiben
int indexgleich = zeile.indexOf('='); // Istgleich suchen
if (indexgleich == -1) {
} else {
String v1 = zeile.substring(0, indexgleich); // Vor dem =
// rauschneiden
String v2 = zeile.substring(indexgleich + 1); // Nach dem
// =
// rausschneiden
System.out.println(v1 + " = " + v2);
cfgvalues.put(v1, v2);
if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen
rgi.logger("[Core-Log] " + v1 + "=" + v2);
}
}
}
reader.close();
} catch (FileNotFoundException e1) {
// cfg-Datei nicht gefunden - inakzeptabel!
rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one...");
try {
cfgFile.createNewFile();
} catch (IOException ex) {
System.out.print("Error creating server_cfg.txt .");
}
//rgi.shutdown(1);
} catch (IOException e2) {
// Inakzeptabel
e2.printStackTrace();
rgi.logger("[Core-ERROR] Critical I/O Error");
rgi.shutdown(1);
}
if ("true".equals(cfgvalues.get("ultimateDebug"))) {
UltimateDebug udb = UltimateDebug.getInstance();
udb.authorizeDebug(this, rgi);
}
// Läuft als Server
rgi.logger("[CoreInit]: Starting server mode...");
// Module laden
rgi.logger("[CoreInit]: Loading modules...");
rgi.logger("[CoreInit]: Loading gamecontroller");
gamectrl = new ServerGameController(rgi);
// Netzwerk
rgi.logger("[CoreInit]: Loading serverNetController");
servNet = new ServerNetController(rgi, this);
rgi.logger("[CoreInit]: Loading serverMapmodul");
mapMod = new ServerMapModule(rgi);
rgi.logger("[CoreInit]: Loading serverStatistics");
sstat = new ServerStatistics(rgi);
rgi.logger("[CoreInit]: Loading serverMoveManager");
smoveman = new ServerMoveManager();
// Alle Module<SUF>
rgi.initInner();
rgi.logger("[Core]: Initializing modules...");
mapMod.initModule();
rgi.logger("[Core]: Init done, starting Server...");
Thread t = new Thread(servNet);
t.start();
rgi.logger("[Core]: Server running");
try {
// Auf Startsignal warten
while (!this.ready) {
Thread.sleep(1000);
}
// Jetzt darf niemand mehr rein
servNet.closeAcception();
// Zufallsvölker bestimmen und allen Clients mitteilen:
for (NetPlayer p : this.gamectrl.playerList) {
if (p.lobbyRace == races.random) {
if (Math.rint(Math.random()) == 1) {
p.lobbyRace = 1;
this.servNet.broadcastString(("91" + p.nickName), (byte) 14);
} else {
p.lobbyRace = 2;
this.servNet.broadcastString(("92" + p.nickName), (byte) 14);
}
}
}
// Clients vorbereiten
servNet.loadGame();
// Warte darauf, das alle soweit sind
waitForStatus(1);
// Spiel laden
mapMod.loadMap(Mapname);
waitForStatus(2);
// Game vorbereiten
servNet.initGame((byte) 8);
// Starteinheiten & Gebäude an das gewählte Volk anpassen:
for (NetPlayer player : this.gamectrl.playerList) {
// Gebäude:
for (Building building : this.rgi.netmap.buildingList) {
if (building.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
building.performUpgrade(rgi, 1001);
} else if (player.lobbyRace == races.human) {
building.performUpgrade(rgi, 1);
}
}
}
// Einheiten:
for (Unit unit : this.rgi.netmap.unitList) {
if (unit.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
// 401=human worker, 1401=undead worker
if (unit.getDescTypeId() == 401) {
unit.performUpgrade(rgi, 1401);
}
// 402=human scout, 1402=undead mage
if (unit.getDescTypeId() == 402) {
unit.performUpgrade(rgi, 1402);
}
} else if (player.lobbyRace == races.human) {
// 1401=undead worker, 401=human worker
if (unit.getDescTypeId() == 1401) {
unit.performUpgrade(rgi, 401);
}
// 1402=undead mage, 402=human scout
if (unit.getDescTypeId() == 1402) {
unit.performUpgrade(rgi, 402);
}
}
}
}
}
waitForStatus(3);
servNet.startGame();
} catch (InterruptedException ex) {
}
}
/**
* Synchronisierte Funktipon zum Strings senden
* wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat
* @param s - zu sendender String
* @param cmdid - command-id
*/
public synchronized void broadcastStringSynchronized(String s, byte cmdid) {
s += "\0";
this.servNet.broadcastString(s, cmdid);
}
private void waitForStatus(int status) throws InterruptedException {
while (true) {
Thread.sleep(50);
boolean go = true;
for (ServerNetController.ServerHandler servhan : servNet.clientconnection) {
if (servhan.loadStatus < status) {
go = false;
break;
}
}
if (go) {
break;
}
}
}
@Override
public void initLogger() {
if (!logOFF) {
// Erstellt ein neues Logfile
try {
FileWriter logcreator = new FileWriter("server_log.txt");
logcreator.close();
} catch (IOException ex) {
// Warscheinlich darf man das nicht, den Adminmodus emfehlen
JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
rgi.shutdown(2);
}
}
}
public class InnerServer extends Core.CoreInner {
public ServerNetController netctrl;
public ServerMapModule netmap;
public ServerGameController game;
public ServerStatistics serverstats;
String lastlog = "";
public ServerMoveManager moveMan;
public ServerAttackManager atkMan;
@Override
public void initInner() {
super.initInner();
// Server-Referenz initialisiern:
Server.setInnerServer(this);
netctrl = servNet;
netmap = mapMod;
game = gamectrl;
serverstats = sstat;
moveMan = smoveman;
atkMan = new ServerAttackManager();
}
@Override
public void logger(String x) {
if (!logOFF) {
if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern
lastlog = x;
// Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die
// log-Datei
try {
FileWriter logwriter = new FileWriter("server_log.txt", true);
String temp = String.format("%tc", new Date()) + " - " + x + "\n";
logwriter.append(temp);
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
@Override
public void logger(Throwable t) {
if (!logOFF) {
// Nimmt Exceptions an und schreibt den Stacktrace ins
// logfile
try {
if (debugmode) {
System.out.println("ERROR!!!! More info in logfile...");
}
FileWriter logwriter = new FileWriter("server_log.txt", true);
logwriter.append('\n' + String.format("%tc", new Date()) + " - ");
logwriter.append("[JavaError]: " + t.toString() + '\n');
StackTraceElement[] errorArray;
errorArray = t.getStackTrace();
for (int i = 0; i < errorArray.length; i++) {
logwriter.append(" " + errorArray[i].toString() + '\n');
}
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
}
| false | 2,732 | 8 | 3,026 | 9 | 3,095 | 6 | 3,026 | 9 | 3,534 | 8 | false | false | false | false | false | true |
3,832 | 169507_0 | package nl.njtromp.adventofcode_2020;
import java.util.Arrays;
public class Infi {
static long aantalPakjes(long lengteZijkant) {
return
3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal
4 * sommatie(lengteZijkant) + // Schuine zijden (4 halve driehoeken)
2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven)
}
private static long sommatie(long n) {
return (n-1)*n/2;
}
private static long bepaalLengte(long aantalInwoners) {
long lengte = 1;
while (aantalPakjes(lengte) < aantalInwoners) {
lengte++;
}
return lengte;
}
public static void main(String[] args) {
long lengte = bepaalLengte(17_493_412);
System.out.printf("De minimale lengte van een zijde is: %d\n", lengte);
long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L};
System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8);
}
}
| njtromp/AdventOfCode-2020 | src/main/java/nl/njtromp/adventofcode_2020/Infi.java | 436 | // Schuine zijden (4 halve driehoeken) | line_comment | nl | package nl.njtromp.adventofcode_2020;
import java.util.Arrays;
public class Infi {
static long aantalPakjes(long lengteZijkant) {
return
3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal
4 * sommatie(lengteZijkant) + // Schuine zijden<SUF>
2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven)
}
private static long sommatie(long n) {
return (n-1)*n/2;
}
private static long bepaalLengte(long aantalInwoners) {
long lengte = 1;
while (aantalPakjes(lengte) < aantalInwoners) {
lengte++;
}
return lengte;
}
public static void main(String[] args) {
long lengte = bepaalLengte(17_493_412);
System.out.printf("De minimale lengte van een zijde is: %d\n", lengte);
long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L};
System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8);
}
}
| false | 416 | 15 | 461 | 17 | 420 | 12 | 461 | 17 | 465 | 14 | false | false | false | false | false | true |
808 | 152641_17 | package intecbrussel.be.Vaccination;_x000D_
_x000D_
import java.util.*;_x000D_
import java.util.stream.Collectors;_x000D_
_x000D_
public class AnimalShelter {_x000D_
private List<Animal> animals;_x000D_
private int animalId;_x000D_
_x000D_
public AnimalShelter() {_x000D_
this.animals = new ArrayList<>();_x000D_
this.animalId = 1;_x000D_
}_x000D_
_x000D_
public List<Animal> getAnimals() {_x000D_
return animals;_x000D_
}_x000D_
_x000D_
public void setAnimals(List<Animal> animals) {_x000D_
this.animals = animals;_x000D_
}_x000D_
_x000D_
public int getAnimalId() {_x000D_
return animalId;_x000D_
}_x000D_
_x000D_
public void setAnimalId(int animalId) {_x000D_
this.animalId = animalId;_x000D_
}_x000D_
//1_x000D_
public void printAnimals(){_x000D_
for (Animal animal : animals){_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
}_x000D_
// sorteert de dieren volgens hun natuurlijke volgorde, dit is volgens hun animalNumber._x000D_
//2_x000D_
public void sortAnimals(){_x000D_
animals.sort(Comparator.comparing(Animal::getAnimalNumber));_x000D_
}_x000D_
//sorteert de dieren op naam_x000D_
//3_x000D_
public void sortAnimalsByName(){_x000D_
animals.sort(Comparator.comparing(Animal::getName));_x000D_
}_x000D_
// sorteert de dieren op leeftijd_x000D_
//4_x000D_
public void sortAnimalsByAge(){_x000D_
animals.sort(Comparator.comparing(Animal::getAge));_x000D_
}_x000D_
//print alle dieren af die niet gevaccineert zijn voor een opgegeven ziekte_x000D_
//5_x000D_
public void printAnimalsNotVaccinated(Disease disease){_x000D_
List<Animal> notVaccinated = animals.stream().filter(animal -> animal.getIsVaccinated().getOrDefault(disease, false)).collect(Collectors.toList());_x000D_
for (Animal animal : notVaccinated){_x000D_
System.out.println(animal.getName()+" is not vaccinated "+disease.name());_x000D_
}_x000D_
}_x000D_
//zoek dier op dierennummer_x000D_
//6_x000D_
public Animal findAnimal(int animalNumber) {_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAnimalNumber() == animalNumber){_x000D_
return animal;_x000D_
}_x000D_
}_x000D_
return null;_x000D_
// return animals.stream().filter(animal -> animal.getAnimalNumber()==animalNumber).findFirst();_x000D_
}_x000D_
_x000D_
//zoek dier op dierennaam_x000D_
//7_x000D_
public Optional<Animal> findAnimal(String name){_x000D_
return animals.stream().filter(animal -> animal.getName().equalsIgnoreCase(name)).findFirst();_x000D_
_x000D_
}_x000D_
// behandel opgegeven dier_x000D_
//8_x000D_
public void treatAnimal(int animalNumber){_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAnimalNumber()==animalNumber){_x000D_
System.out.println("treat animal by number: "+animal.getAnimalNumber()+animal.getIsVaccinated());_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
//System.out.println("animal with number "+animalNumber+"not found");_x000D_
/* animals.stream()_x000D_
.sorted(Comparator.comparingInt(Animal::getAnimalNumber))_x000D_
.forEach(animal -> System.out.println(_x000D_
"Animal number: "+animal.getAnimalNumber()+_x000D_
"| name: "+animal.getName()+_x000D_
"| age: "+animal.getAge()+_x000D_
"| is clean? "+animal.getIsVaccinated()_x000D_
));///////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_
/*Optional<Animal> optionalAnimal = findAnimal(animalNumber);_x000D_
if (optionalAnimal.isPresent()){_x000D_
Animal animal = optionalAnimal.get();_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}else {_x000D_
System.out.println("animal met number "+animalNumber+"not found");_x000D_
}*/_x000D_
}_x000D_
//behandel opgegeven dier_x000D_
//9_x000D_
public void treatAnimal(String name){_x000D_
for (Animal animal : animals){_x000D_
if (animal.getName()==name){_x000D_
System.out.println("treat animal by name: "+animal.getName()+animal.getIsVaccinated());_x000D_
_x000D_
}_x000D_
}_x000D_
/*animals.stream()_x000D_
.sorted(Comparator.comparing(Animal::getName))_x000D_
.forEach(animal -> System.out.println(_x000D_
"name: "+animal.getName()+_x000D_
"| animal number: "+animal.getAnimalNumber()+_x000D_
"| age: "+animal.getAge()+_x000D_
"| is clean? "+animal.getIsVaccinated()_x000D_
));/////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_
/* Optional<Animal> optionalAnimal = findAnimal(name);_x000D_
if (optionalAnimal.isPresent()){_x000D_
Animal animal = optionalAnimal.get();_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}else {_x000D_
System.out.println("animal met name "+name+ "not found");_x000D_
}*/_x000D_
_x000D_
}_x000D_
//behandel alle dieren_x000D_
//10_x000D_
public void treatAllAnimals(){_x000D_
for (Animal animal : animals){_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
_x000D_
}_x000D_
//geef het oudste dier terug_x000D_
//11_x000D_
public Animal findOldestAnimal() throws NoSuchElementException {_x000D_
if (animals.isEmpty()) {_x000D_
throw new NoSuchElementException("No animal found in this list");_x000D_
}_x000D_
Animal oldestAnimal = animals.get(0);_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAge() > oldestAnimal.getAge()){_x000D_
oldestAnimal = animal;_x000D_
//System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
}_x000D_
return oldestAnimal;_x000D_
_x000D_
}_x000D_
_x000D_
// geef het aantal dieren terug_x000D_
//12_x000D_
public int countAnimals(){_x000D_
if (animals != null){_x000D_
return animals.size();_x000D_
}else {_x000D_
return 0;_x000D_
}_x000D_
}_x000D_
_x000D_
//voeg een dier toe aan de lijst van animals_x000D_
//13_x000D_
public void addAnimal(Animal animal) throws IllegalArgumentException{_x000D_
if (animal != null){_x000D_
animal.setAnimalNumber(animalId);//toewijzen de nummer animal_x000D_
animals.add(animal);//add de animal to de list_x000D_
animalId++;//verhoog de animal id_x000D_
}else {_x000D_
throw new IllegalArgumentException("Can not add null animal to de list");_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
| JananJavdan/Vaccination | Vaccination/src/main/java/intecbrussel/be/Vaccination/AnimalShelter.java | 2,073 | //toewijzen de nummer animal_x000D_ | line_comment | nl | package intecbrussel.be.Vaccination;_x000D_
_x000D_
import java.util.*;_x000D_
import java.util.stream.Collectors;_x000D_
_x000D_
public class AnimalShelter {_x000D_
private List<Animal> animals;_x000D_
private int animalId;_x000D_
_x000D_
public AnimalShelter() {_x000D_
this.animals = new ArrayList<>();_x000D_
this.animalId = 1;_x000D_
}_x000D_
_x000D_
public List<Animal> getAnimals() {_x000D_
return animals;_x000D_
}_x000D_
_x000D_
public void setAnimals(List<Animal> animals) {_x000D_
this.animals = animals;_x000D_
}_x000D_
_x000D_
public int getAnimalId() {_x000D_
return animalId;_x000D_
}_x000D_
_x000D_
public void setAnimalId(int animalId) {_x000D_
this.animalId = animalId;_x000D_
}_x000D_
//1_x000D_
public void printAnimals(){_x000D_
for (Animal animal : animals){_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
}_x000D_
// sorteert de dieren volgens hun natuurlijke volgorde, dit is volgens hun animalNumber._x000D_
//2_x000D_
public void sortAnimals(){_x000D_
animals.sort(Comparator.comparing(Animal::getAnimalNumber));_x000D_
}_x000D_
//sorteert de dieren op naam_x000D_
//3_x000D_
public void sortAnimalsByName(){_x000D_
animals.sort(Comparator.comparing(Animal::getName));_x000D_
}_x000D_
// sorteert de dieren op leeftijd_x000D_
//4_x000D_
public void sortAnimalsByAge(){_x000D_
animals.sort(Comparator.comparing(Animal::getAge));_x000D_
}_x000D_
//print alle dieren af die niet gevaccineert zijn voor een opgegeven ziekte_x000D_
//5_x000D_
public void printAnimalsNotVaccinated(Disease disease){_x000D_
List<Animal> notVaccinated = animals.stream().filter(animal -> animal.getIsVaccinated().getOrDefault(disease, false)).collect(Collectors.toList());_x000D_
for (Animal animal : notVaccinated){_x000D_
System.out.println(animal.getName()+" is not vaccinated "+disease.name());_x000D_
}_x000D_
}_x000D_
//zoek dier op dierennummer_x000D_
//6_x000D_
public Animal findAnimal(int animalNumber) {_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAnimalNumber() == animalNumber){_x000D_
return animal;_x000D_
}_x000D_
}_x000D_
return null;_x000D_
// return animals.stream().filter(animal -> animal.getAnimalNumber()==animalNumber).findFirst();_x000D_
}_x000D_
_x000D_
//zoek dier op dierennaam_x000D_
//7_x000D_
public Optional<Animal> findAnimal(String name){_x000D_
return animals.stream().filter(animal -> animal.getName().equalsIgnoreCase(name)).findFirst();_x000D_
_x000D_
}_x000D_
// behandel opgegeven dier_x000D_
//8_x000D_
public void treatAnimal(int animalNumber){_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAnimalNumber()==animalNumber){_x000D_
System.out.println("treat animal by number: "+animal.getAnimalNumber()+animal.getIsVaccinated());_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
//System.out.println("animal with number "+animalNumber+"not found");_x000D_
/* animals.stream()_x000D_
.sorted(Comparator.comparingInt(Animal::getAnimalNumber))_x000D_
.forEach(animal -> System.out.println(_x000D_
"Animal number: "+animal.getAnimalNumber()+_x000D_
"| name: "+animal.getName()+_x000D_
"| age: "+animal.getAge()+_x000D_
"| is clean? "+animal.getIsVaccinated()_x000D_
));///////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_
/*Optional<Animal> optionalAnimal = findAnimal(animalNumber);_x000D_
if (optionalAnimal.isPresent()){_x000D_
Animal animal = optionalAnimal.get();_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}else {_x000D_
System.out.println("animal met number "+animalNumber+"not found");_x000D_
}*/_x000D_
}_x000D_
//behandel opgegeven dier_x000D_
//9_x000D_
public void treatAnimal(String name){_x000D_
for (Animal animal : animals){_x000D_
if (animal.getName()==name){_x000D_
System.out.println("treat animal by name: "+animal.getName()+animal.getIsVaccinated());_x000D_
_x000D_
}_x000D_
}_x000D_
/*animals.stream()_x000D_
.sorted(Comparator.comparing(Animal::getName))_x000D_
.forEach(animal -> System.out.println(_x000D_
"name: "+animal.getName()+_x000D_
"| animal number: "+animal.getAnimalNumber()+_x000D_
"| age: "+animal.getAge()+_x000D_
"| is clean? "+animal.getIsVaccinated()_x000D_
));/////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_
/* Optional<Animal> optionalAnimal = findAnimal(name);_x000D_
if (optionalAnimal.isPresent()){_x000D_
Animal animal = optionalAnimal.get();_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}else {_x000D_
System.out.println("animal met name "+name+ "not found");_x000D_
}*/_x000D_
_x000D_
}_x000D_
//behandel alle dieren_x000D_
//10_x000D_
public void treatAllAnimals(){_x000D_
for (Animal animal : animals){_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
_x000D_
}_x000D_
//geef het oudste dier terug_x000D_
//11_x000D_
public Animal findOldestAnimal() throws NoSuchElementException {_x000D_
if (animals.isEmpty()) {_x000D_
throw new NoSuchElementException("No animal found in this list");_x000D_
}_x000D_
Animal oldestAnimal = animals.get(0);_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAge() > oldestAnimal.getAge()){_x000D_
oldestAnimal = animal;_x000D_
//System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
}_x000D_
return oldestAnimal;_x000D_
_x000D_
}_x000D_
_x000D_
// geef het aantal dieren terug_x000D_
//12_x000D_
public int countAnimals(){_x000D_
if (animals != null){_x000D_
return animals.size();_x000D_
}else {_x000D_
return 0;_x000D_
}_x000D_
}_x000D_
_x000D_
//voeg een dier toe aan de lijst van animals_x000D_
//13_x000D_
public void addAnimal(Animal animal) throws IllegalArgumentException{_x000D_
if (animal != null){_x000D_
animal.setAnimalNumber(animalId);//toewijzen de<SUF>
animals.add(animal);//add de animal to de list_x000D_
animalId++;//verhoog de animal id_x000D_
}else {_x000D_
throw new IllegalArgumentException("Can not add null animal to de list");_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
| false | 2,629 | 15 | 2,846 | 16 | 2,850 | 15 | 2,846 | 16 | 3,229 | 16 | false | false | false | false | false | true |
3,819 | 27626_0 | package semisplay;
public interface SearchTree<E extends Comparable<E>> extends Iterable<E> {
/** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit.
* @return true als de sleutel effectief toegevoegd werd. */
boolean add(E e);
/** Zoek de gegeven sleutel op in de boom.
* @return true als de sleutel gevonden werd. */
boolean contains(E e);
/** Verwijder de gegeven sleutel uit de boom.
* @return true als de sleutel gevonden en verwijderd werd. */
boolean remove(E e);
/** @return het aantal sleutels in de boom. */
int size();
/** @return de diepte van de boom. */
int depth();
}
| nielsdos/Semisplay-tree | src/semisplay/SearchTree.java | 203 | /** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit.
* @return true als de sleutel effectief toegevoegd werd. */ | block_comment | nl | package semisplay;
public interface SearchTree<E extends Comparable<E>> extends Iterable<E> {
/** Voeg de gegeven<SUF>*/
boolean add(E e);
/** Zoek de gegeven sleutel op in de boom.
* @return true als de sleutel gevonden werd. */
boolean contains(E e);
/** Verwijder de gegeven sleutel uit de boom.
* @return true als de sleutel gevonden en verwijderd werd. */
boolean remove(E e);
/** @return het aantal sleutels in de boom. */
int size();
/** @return de diepte van de boom. */
int depth();
}
| false | 182 | 43 | 207 | 45 | 184 | 36 | 207 | 45 | 217 | 44 | false | false | false | false | false | true |
646 | 172943_2 | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList();
}
/**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.currentTimeMillis();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec.";
}
}
/**
* override van toString methode. Geeft alle tijdsperiode weer.
*/
public String toString() {
StringBuilder buffer = new StringBuilder();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
}
| HDauven/S32JSF3 | JSF31_w04_KochFractalFX-startup/JSF31KochFractalFX - startup/src/timeutil/TimeStamp.java | 1,267 | /**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/ | block_comment | nl | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList();
}
/**
* zet begintijdstip. gebruik<SUF>*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.currentTimeMillis();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec.";
}
}
/**
* override van toString methode. Geeft alle tijdsperiode weer.
*/
public String toString() {
StringBuilder buffer = new StringBuilder();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
}
| false | 1,079 | 32 | 1,174 | 30 | 1,116 | 25 | 1,174 | 30 | 1,285 | 32 | false | false | false | false | false | true |
2,480 | 35814_3 | import java.io.File;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class MP1 {
Random generator;
String userName;
String inputFileName;
String delimiters = " \t,;.?!-:@[](){}_*/";
String[] stopWordsArray = {"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours",
"yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its",
"itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that",
"these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having",
"do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while",
"of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before",
"after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again",
"further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each",
"few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than",
"too", "very", "s", "t", "can", "will", "just", "don", "should", "now"};
void initialRandomGenerator(String seed) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("SHA");
messageDigest.update(seed.toLowerCase().trim().getBytes());
byte[] seedMD5 = messageDigest.digest();
long longSeed = 0;
for (int i = 0; i < seedMD5.length; i++) {
longSeed += ((long) seedMD5[i] & 0xffL) << (8 * i);
}
this.generator = new Random(longSeed);
}
Integer[] getIndexes() throws NoSuchAlgorithmException {
Integer n = 10000;
Integer number_of_lines = 50000;
Integer[] ret = new Integer[n];
this.initialRandomGenerator(this.userName);
for (int i = 0; i < n; i++) {
ret[i] = generator.nextInt(number_of_lines);
}
return ret;
}
public MP1(String userName, String inputFileName) {
this.userName = userName;
this.inputFileName = inputFileName;
}
public String[] process() throws Exception {
String[] ret = new String[20];
//TODO
// read input file
String line;
try (
InputStream fis = new FileInputStream(this.inputFileName);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
) {
int i=0;
/* begin Code B */
String regel=""; //debug
regel="A._B._een_twee(drie)vier_(vijf)"; //debug
/* code1 */ String[] result = regel.split("[\\s_()]"); // split op whitespace, of '_' of '(' of ')'
// resultaat zit nu in een Array van strings
//print het aantal elementen in de array //debug
System.out.println(result.length); //debug
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
/*eind code B */
// zie nog https://d396qusza40orc.cloudfront.net/cloudapplications/mps/mp1/MP1_Instructions.pdf
/* begin code A*/
while ((line = br.readLine()) != null) {
// Deal with the line
// nog "nod code A verwerken voor de variable line"
// dit nog vervangen
if (i<20) {
ret[i] = line;
} i++;
// dit nog vervangen
}
/* einde code A*/
}
return ret;
}
public static void main(String[] args) throws Exception {
if (args.length < 1){
System.out.println("MP1 <User ID>");
}
else {
String userName = args[0];
String inputFileName = "./input.txt";
MP1 mp = new MP1(userName, inputFileName);
String[] topItems = mp.process();
for (String item: topItems){
System.out.println(item);
}
}
}
}
| cx1964/cx1964BladMuziek | Klassiek/Chopin_Frédéric/MP1.v002.java | 1,466 | // resultaat zit nu in een Array van strings | line_comment | nl | import java.io.File;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class MP1 {
Random generator;
String userName;
String inputFileName;
String delimiters = " \t,;.?!-:@[](){}_*/";
String[] stopWordsArray = {"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours",
"yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its",
"itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that",
"these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having",
"do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while",
"of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before",
"after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again",
"further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each",
"few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than",
"too", "very", "s", "t", "can", "will", "just", "don", "should", "now"};
void initialRandomGenerator(String seed) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("SHA");
messageDigest.update(seed.toLowerCase().trim().getBytes());
byte[] seedMD5 = messageDigest.digest();
long longSeed = 0;
for (int i = 0; i < seedMD5.length; i++) {
longSeed += ((long) seedMD5[i] & 0xffL) << (8 * i);
}
this.generator = new Random(longSeed);
}
Integer[] getIndexes() throws NoSuchAlgorithmException {
Integer n = 10000;
Integer number_of_lines = 50000;
Integer[] ret = new Integer[n];
this.initialRandomGenerator(this.userName);
for (int i = 0; i < n; i++) {
ret[i] = generator.nextInt(number_of_lines);
}
return ret;
}
public MP1(String userName, String inputFileName) {
this.userName = userName;
this.inputFileName = inputFileName;
}
public String[] process() throws Exception {
String[] ret = new String[20];
//TODO
// read input file
String line;
try (
InputStream fis = new FileInputStream(this.inputFileName);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
) {
int i=0;
/* begin Code B */
String regel=""; //debug
regel="A._B._een_twee(drie)vier_(vijf)"; //debug
/* code1 */ String[] result = regel.split("[\\s_()]"); // split op whitespace, of '_' of '(' of ')'
// resultaat zit<SUF>
//print het aantal elementen in de array //debug
System.out.println(result.length); //debug
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
/*eind code B */
// zie nog https://d396qusza40orc.cloudfront.net/cloudapplications/mps/mp1/MP1_Instructions.pdf
/* begin code A*/
while ((line = br.readLine()) != null) {
// Deal with the line
// nog "nod code A verwerken voor de variable line"
// dit nog vervangen
if (i<20) {
ret[i] = line;
} i++;
// dit nog vervangen
}
/* einde code A*/
}
return ret;
}
public static void main(String[] args) throws Exception {
if (args.length < 1){
System.out.println("MP1 <User ID>");
}
else {
String userName = args[0];
String inputFileName = "./input.txt";
MP1 mp = new MP1(userName, inputFileName);
String[] topItems = mp.process();
for (String item: topItems){
System.out.println(item);
}
}
}
}
| false | 1,190 | 11 | 1,280 | 11 | 1,358 | 9 | 1,280 | 11 | 1,496 | 12 | false | false | false | false | false | true |
1,117 | 18183_3 | import java.awt.Rectangle;_x000D_
import java.awt.Graphics;_x000D_
import java.awt.image.BufferedImage;_x000D_
import java.awt.image.ImageObserver;_x000D_
import java.io.File;_x000D_
import javax.imageio.ImageIO;_x000D_
import java.io.IOException;_x000D_
_x000D_
_x000D_
/** De klasse voor een Bitmap item_x000D_
* <P>_x000D_
* This program is distributed under the terms of the accompanying_x000D_
* COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_
* Please read it. Your use of the software constitutes acceptance_x000D_
* of the terms in the COPYRIGHT.txt file._x000D_
* @author Ian F. Darwin, [email protected]_x000D_
* @version $Id: BitmapItem.java,v 1.1 2002/12/17 Gert Florijn_x000D_
* @version $Id: BitmapItem.java,v 1.2 2003/12/17 Sylvia Stuurman_x000D_
* @version $Id: BitmapItem.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_
* @version $Id: BitmapItem.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_
*/_x000D_
_x000D_
public class BitmapItem extends SlideItem {_x000D_
private BufferedImage bufferedImage;_x000D_
private String imageName;_x000D_
_x000D_
// level staat voor het item-level; name voor de naam van het bestand met het plaatje_x000D_
public BitmapItem(int level, String name) {_x000D_
super(level);_x000D_
imageName = name;_x000D_
try {_x000D_
bufferedImage = ImageIO.read(new File(imageName));_x000D_
}_x000D_
catch (IOException e) {_x000D_
System.err.println("Bestand " + imageName + " niet gevonden") ;_x000D_
}_x000D_
}_x000D_
_x000D_
// Een leeg bitmap-item_x000D_
public BitmapItem() {_x000D_
this(0, null);_x000D_
}_x000D_
_x000D_
// geef de bestandsnaam van het plaatje_x000D_
public String getName() {_x000D_
return imageName;_x000D_
}_x000D_
_x000D_
// geef de bounding box van het plaatje_x000D_
public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) {_x000D_
return new Rectangle((int) (myStyle.indent * scale), 0,_x000D_
(int) (bufferedImage.getWidth(observer) * scale),_x000D_
((int) (myStyle.leading * scale)) + (int) (bufferedImage.getHeight(observer) * scale));_x000D_
}_x000D_
_x000D_
// teken het plaatje_x000D_
public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) {_x000D_
int width = x + (int) (myStyle.indent * scale);_x000D_
int height = y + (int) (myStyle.leading * scale);_x000D_
g.drawImage(bufferedImage, width, height,(int) (bufferedImage.getWidth(observer)*scale),_x000D_
(int) (bufferedImage.getHeight(observer)*scale), observer);_x000D_
}_x000D_
_x000D_
public String toString() {_x000D_
return "BitmapItem[" + getLevel() + "," + imageName + "]";_x000D_
}_x000D_
}_x000D_
| MichielMertens/OU_JP_MM_EVB | src/BitmapItem.java | 794 | // geef de bestandsnaam van het plaatje_x000D_ | line_comment | nl | import java.awt.Rectangle;_x000D_
import java.awt.Graphics;_x000D_
import java.awt.image.BufferedImage;_x000D_
import java.awt.image.ImageObserver;_x000D_
import java.io.File;_x000D_
import javax.imageio.ImageIO;_x000D_
import java.io.IOException;_x000D_
_x000D_
_x000D_
/** De klasse voor een Bitmap item_x000D_
* <P>_x000D_
* This program is distributed under the terms of the accompanying_x000D_
* COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_
* Please read it. Your use of the software constitutes acceptance_x000D_
* of the terms in the COPYRIGHT.txt file._x000D_
* @author Ian F. Darwin, [email protected]_x000D_
* @version $Id: BitmapItem.java,v 1.1 2002/12/17 Gert Florijn_x000D_
* @version $Id: BitmapItem.java,v 1.2 2003/12/17 Sylvia Stuurman_x000D_
* @version $Id: BitmapItem.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_
* @version $Id: BitmapItem.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_
*/_x000D_
_x000D_
public class BitmapItem extends SlideItem {_x000D_
private BufferedImage bufferedImage;_x000D_
private String imageName;_x000D_
_x000D_
// level staat voor het item-level; name voor de naam van het bestand met het plaatje_x000D_
public BitmapItem(int level, String name) {_x000D_
super(level);_x000D_
imageName = name;_x000D_
try {_x000D_
bufferedImage = ImageIO.read(new File(imageName));_x000D_
}_x000D_
catch (IOException e) {_x000D_
System.err.println("Bestand " + imageName + " niet gevonden") ;_x000D_
}_x000D_
}_x000D_
_x000D_
// Een leeg bitmap-item_x000D_
public BitmapItem() {_x000D_
this(0, null);_x000D_
}_x000D_
_x000D_
// geef de<SUF>
public String getName() {_x000D_
return imageName;_x000D_
}_x000D_
_x000D_
// geef de bounding box van het plaatje_x000D_
public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) {_x000D_
return new Rectangle((int) (myStyle.indent * scale), 0,_x000D_
(int) (bufferedImage.getWidth(observer) * scale),_x000D_
((int) (myStyle.leading * scale)) + (int) (bufferedImage.getHeight(observer) * scale));_x000D_
}_x000D_
_x000D_
// teken het plaatje_x000D_
public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) {_x000D_
int width = x + (int) (myStyle.indent * scale);_x000D_
int height = y + (int) (myStyle.leading * scale);_x000D_
g.drawImage(bufferedImage, width, height,(int) (bufferedImage.getWidth(observer)*scale),_x000D_
(int) (bufferedImage.getHeight(observer)*scale), observer);_x000D_
}_x000D_
_x000D_
public String toString() {_x000D_
return "BitmapItem[" + getLevel() + "," + imageName + "]";_x000D_
}_x000D_
}_x000D_
| false | 1,028 | 19 | 1,152 | 20 | 1,141 | 17 | 1,152 | 20 | 1,232 | 20 | false | false | false | false | false | true |
839 | 57662_0 | package servlets;_x000D_
_x000D_
import java.io.IOException;_x000D_
import java.sql.Connection;_x000D_
import java.util.ArrayList;_x000D_
_x000D_
import javax.servlet.RequestDispatcher;_x000D_
import javax.servlet.ServletException;_x000D_
import javax.servlet.http.HttpServlet;_x000D_
import javax.servlet.http.HttpServletRequest;_x000D_
import javax.servlet.http.HttpServletResponse;_x000D_
_x000D_
import database.ConnectDBProduct;_x000D_
import domeinklassen.Product;_x000D_
_x000D_
public class ProductServlet extends HttpServlet{_x000D_
private static final long serialVersionUID = 1L;_x000D_
_x000D_
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {_x000D_
_x000D_
Connection con = (Connection)req.getSession().getAttribute("verbinding");_x000D_
String knop = req.getParameter("knop");_x000D_
_x000D_
ConnectDBProduct conn = new ConnectDBProduct(con); _x000D_
ArrayList<Product> deVoorraad = conn.getProducten();_x000D_
RequestDispatcher rd = req.getRequestDispatcher("product.jsp"); //stuur bij default naar voorraadoverzicht_x000D_
_x000D_
//forward voorraadlijst naar de overzicht-pagina._x000D_
if(knop.equals("overzicht")){_x000D_
if(deVoorraad.size() == 0){_x000D_
req.setAttribute("msg", "Geen producten beschikbaar!");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("voorraadlijst", deVoorraad);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
}_x000D_
} _x000D_
//forward lijst producten onder min voorraad_x000D_
else if (knop.equals("OnderVoorraad")){_x000D_
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_
if(ondermin.size() == 0){_x000D_
req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("voorraadlijst", ondermin);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
}_x000D_
}_x000D_
//bestel producten onder min voorraad_x000D_
else if(knop.equals("WerkVoorraadBij")){_x000D_
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_
if(ondermin.size() == 0){_x000D_
req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_
}_x000D_
else{_x000D_
rd = req.getRequestDispatcher("nieuwebestelling.jsp");_x000D_
req.setAttribute("stap1", "Done");_x000D_
req.setAttribute("teBestellenProducten", ondermin);_x000D_
}_x000D_
}_x000D_
//maak een nieuw product aan_x000D_
else if(knop.equals("nieuw")){_x000D_
String nm = req.getParameter("naam");_x000D_
String ma = req.getParameter("minaantal");_x000D_
String eh = req.getParameter("eenheid");_x000D_
String pps = req.getParameter("pps");_x000D_
ArrayList<String> velden = new ArrayList<String>();_x000D_
velden.add(nm); velden.add(ma); velden.add(eh); velden.add("pps");_x000D_
_x000D_
//check of nodige velden in zijn gevuld (artikelnummer bestaat niet meer omdat de database die straks gaat aanmaken)_x000D_
boolean allesIngevuld = true;_x000D_
for(String s : velden){_x000D_
if(s.equals("")){_x000D_
allesIngevuld = false;_x000D_
req.setAttribute("error", "Vul alle velden in!");_x000D_
break;_x000D_
}_x000D_
}_x000D_
//als gegevens ingevuld_x000D_
if(allesIngevuld){ _x000D_
try{ //check voor geldige nummers_x000D_
//maak product aan in database en haal op_x000D_
Product nieuw = conn.nieuwProduct(nm, Integer.parseInt(ma), eh, Double.parseDouble(pps));_x000D_
//stuur toString() van nieuwe product terug_x000D_
String terug = "Nieuw product aangemaakt: " + nieuw.toString();_x000D_
req.setAttribute("msg", terug);_x000D_
}_x000D_
catch(Exception ex){_x000D_
System.out.println(ex);_x000D_
req.setAttribute("error", "Voer geldige nummers in!");_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
//zoek product op naam of artikelnummer_x000D_
else if(knop.equals("zoek")){_x000D_
String nm = req.getParameter("zoeknaam");_x000D_
String eh = req.getParameter("zoekeenheid");_x000D_
String anr = req.getParameter("zoeknummer"); _x000D_
ArrayList<Product> terug = new ArrayList<Product>();_x000D_
//check welke zoekterm er in is gevoerd_x000D_
if(!anr.equals("")){_x000D_
//check voor geldig artikelnummer (int)_x000D_
try{_x000D_
int nummer = Integer.parseInt(anr);_x000D_
terug.add(conn.zoekProduct(nummer));_x000D_
}catch(NumberFormatException e){_x000D_
req.setAttribute("error", "Vul een geldig artikelnummer in!");_x000D_
}_x000D_
}_x000D_
if(!nm.equals("")){_x000D_
for(Product p : conn.zoekProductNaam(nm)){_x000D_
terug.add(p);_x000D_
}_x000D_
} _x000D_
if(!eh.equals("")){_x000D_
for(Product p : conn.zoekProductEenheid(eh)){_x000D_
terug.add(p);_x000D_
}_x000D_
} _x000D_
else{_x000D_
req.setAttribute("error", "Vul een zoekcriterium in!");_x000D_
}_x000D_
if(terug.size() == 0){_x000D_
req.setAttribute("zoekmsg", "Geen producten gevonden met ingevulde criteria");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("zoekmsg", "Product(en) gevonden!"); _x000D_
req.setAttribute("arraygevonden", terug); _x000D_
}_x000D_
}_x000D_
_x000D_
//wijzig gezochte product_x000D_
else if(knop.equals("wijzig")){_x000D_
String productnummer = req.getParameter("product");_x000D_
Product hetProduct = conn.zoekProduct(Integer.parseInt(productnummer));_x000D_
req.setAttribute("product", hetProduct);_x000D_
rd = req.getRequestDispatcher("wijzigproduct.jsp");_x000D_
} _x000D_
else if(knop.equals("verwijder")){_x000D_
String p = req.getParameter("product");_x000D_
if(conn.verwijderProduct(Integer.parseInt(p))){_x000D_
req.setAttribute("msg", "Product met succes verwijderd.");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("error", "Kon product niet verwijderen!");_x000D_
}_x000D_
deVoorraad = conn.getProducten();_x000D_
req.setAttribute("voorraadlijst", deVoorraad);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
} _x000D_
rd.forward(req, resp); _x000D_
}_x000D_
} | Jfeurich/Themaopdracht2 | Themaopdracht/src/servlets/ProductServlet.java | 1,844 | //stuur bij default naar voorraadoverzicht_x000D_ | line_comment | nl | package servlets;_x000D_
_x000D_
import java.io.IOException;_x000D_
import java.sql.Connection;_x000D_
import java.util.ArrayList;_x000D_
_x000D_
import javax.servlet.RequestDispatcher;_x000D_
import javax.servlet.ServletException;_x000D_
import javax.servlet.http.HttpServlet;_x000D_
import javax.servlet.http.HttpServletRequest;_x000D_
import javax.servlet.http.HttpServletResponse;_x000D_
_x000D_
import database.ConnectDBProduct;_x000D_
import domeinklassen.Product;_x000D_
_x000D_
public class ProductServlet extends HttpServlet{_x000D_
private static final long serialVersionUID = 1L;_x000D_
_x000D_
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {_x000D_
_x000D_
Connection con = (Connection)req.getSession().getAttribute("verbinding");_x000D_
String knop = req.getParameter("knop");_x000D_
_x000D_
ConnectDBProduct conn = new ConnectDBProduct(con); _x000D_
ArrayList<Product> deVoorraad = conn.getProducten();_x000D_
RequestDispatcher rd = req.getRequestDispatcher("product.jsp"); //stuur bij<SUF>
_x000D_
//forward voorraadlijst naar de overzicht-pagina._x000D_
if(knop.equals("overzicht")){_x000D_
if(deVoorraad.size() == 0){_x000D_
req.setAttribute("msg", "Geen producten beschikbaar!");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("voorraadlijst", deVoorraad);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
}_x000D_
} _x000D_
//forward lijst producten onder min voorraad_x000D_
else if (knop.equals("OnderVoorraad")){_x000D_
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_
if(ondermin.size() == 0){_x000D_
req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("voorraadlijst", ondermin);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
}_x000D_
}_x000D_
//bestel producten onder min voorraad_x000D_
else if(knop.equals("WerkVoorraadBij")){_x000D_
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_
if(ondermin.size() == 0){_x000D_
req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_
}_x000D_
else{_x000D_
rd = req.getRequestDispatcher("nieuwebestelling.jsp");_x000D_
req.setAttribute("stap1", "Done");_x000D_
req.setAttribute("teBestellenProducten", ondermin);_x000D_
}_x000D_
}_x000D_
//maak een nieuw product aan_x000D_
else if(knop.equals("nieuw")){_x000D_
String nm = req.getParameter("naam");_x000D_
String ma = req.getParameter("minaantal");_x000D_
String eh = req.getParameter("eenheid");_x000D_
String pps = req.getParameter("pps");_x000D_
ArrayList<String> velden = new ArrayList<String>();_x000D_
velden.add(nm); velden.add(ma); velden.add(eh); velden.add("pps");_x000D_
_x000D_
//check of nodige velden in zijn gevuld (artikelnummer bestaat niet meer omdat de database die straks gaat aanmaken)_x000D_
boolean allesIngevuld = true;_x000D_
for(String s : velden){_x000D_
if(s.equals("")){_x000D_
allesIngevuld = false;_x000D_
req.setAttribute("error", "Vul alle velden in!");_x000D_
break;_x000D_
}_x000D_
}_x000D_
//als gegevens ingevuld_x000D_
if(allesIngevuld){ _x000D_
try{ //check voor geldige nummers_x000D_
//maak product aan in database en haal op_x000D_
Product nieuw = conn.nieuwProduct(nm, Integer.parseInt(ma), eh, Double.parseDouble(pps));_x000D_
//stuur toString() van nieuwe product terug_x000D_
String terug = "Nieuw product aangemaakt: " + nieuw.toString();_x000D_
req.setAttribute("msg", terug);_x000D_
}_x000D_
catch(Exception ex){_x000D_
System.out.println(ex);_x000D_
req.setAttribute("error", "Voer geldige nummers in!");_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
//zoek product op naam of artikelnummer_x000D_
else if(knop.equals("zoek")){_x000D_
String nm = req.getParameter("zoeknaam");_x000D_
String eh = req.getParameter("zoekeenheid");_x000D_
String anr = req.getParameter("zoeknummer"); _x000D_
ArrayList<Product> terug = new ArrayList<Product>();_x000D_
//check welke zoekterm er in is gevoerd_x000D_
if(!anr.equals("")){_x000D_
//check voor geldig artikelnummer (int)_x000D_
try{_x000D_
int nummer = Integer.parseInt(anr);_x000D_
terug.add(conn.zoekProduct(nummer));_x000D_
}catch(NumberFormatException e){_x000D_
req.setAttribute("error", "Vul een geldig artikelnummer in!");_x000D_
}_x000D_
}_x000D_
if(!nm.equals("")){_x000D_
for(Product p : conn.zoekProductNaam(nm)){_x000D_
terug.add(p);_x000D_
}_x000D_
} _x000D_
if(!eh.equals("")){_x000D_
for(Product p : conn.zoekProductEenheid(eh)){_x000D_
terug.add(p);_x000D_
}_x000D_
} _x000D_
else{_x000D_
req.setAttribute("error", "Vul een zoekcriterium in!");_x000D_
}_x000D_
if(terug.size() == 0){_x000D_
req.setAttribute("zoekmsg", "Geen producten gevonden met ingevulde criteria");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("zoekmsg", "Product(en) gevonden!"); _x000D_
req.setAttribute("arraygevonden", terug); _x000D_
}_x000D_
}_x000D_
_x000D_
//wijzig gezochte product_x000D_
else if(knop.equals("wijzig")){_x000D_
String productnummer = req.getParameter("product");_x000D_
Product hetProduct = conn.zoekProduct(Integer.parseInt(productnummer));_x000D_
req.setAttribute("product", hetProduct);_x000D_
rd = req.getRequestDispatcher("wijzigproduct.jsp");_x000D_
} _x000D_
else if(knop.equals("verwijder")){_x000D_
String p = req.getParameter("product");_x000D_
if(conn.verwijderProduct(Integer.parseInt(p))){_x000D_
req.setAttribute("msg", "Product met succes verwijderd.");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("error", "Kon product niet verwijderen!");_x000D_
}_x000D_
deVoorraad = conn.getProducten();_x000D_
req.setAttribute("voorraadlijst", deVoorraad);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
} _x000D_
rd.forward(req, resp); _x000D_
}_x000D_
} | false | 2,350 | 18 | 2,680 | 19 | 2,527 | 18 | 2,680 | 19 | 3,025 | 19 | false | false | false | false | false | true |
804 | 203327_6 | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/MainActivity.java | 1,848 | // Instellen van de opties van het menu | line_comment | nl | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van<SUF>
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} | false | 1,238 | 10 | 1,486 | 10 | 1,550 | 10 | 1,486 | 10 | 1,781 | 10 | false | false | false | false | false | true |
1,508 | 37934_2 | package nl.sbdeveloper.leastslack;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LeastSlack {
private static final Pattern pattern = Pattern.compile("(\\d+)[ \\t]+(\\d+)");
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Geef een bestandsnaam mee!");
System.exit(0);
return;
}
URL resource = LeastSlack.class.getClassLoader().getResource(args[0]);
if (resource == null) {
System.out.println("De meegegeven bestandsnaam bestaat niet!");
System.exit(0);
return;
}
Scanner fileScanner = new Scanner(resource.openStream());
JobShop shop = new JobShop();
int jobs = 0;
int machines = 0;
int lowestMachine = Integer.MAX_VALUE;
boolean wasFirstLine;
int currentJob = 0;
Matcher matcher;
while (fileScanner.hasNextLine()) {
matcher = pattern.matcher(fileScanner.nextLine());
wasFirstLine = false;
if (jobs != 0 && machines != 0) {
Job job = new Job(currentJob);
shop.getJobs().add(job);
}
while (matcher.find()) {
if (jobs == 0 || machines == 0) {
jobs = Integer.parseInt(matcher.group(1));
machines = Integer.parseInt(matcher.group(2));
wasFirstLine = true;
break;
} else {
int id = Integer.parseInt(matcher.group(1));
int duration = Integer.parseInt(matcher.group(2));
if (id < lowestMachine) lowestMachine = id;
Task task = new Task(id, duration);
int finalCurrentJob = currentJob;
Optional<Job> jobOpt = shop.getJobs().stream().filter(j -> j.getId() == finalCurrentJob).findFirst();
if (jobOpt.isEmpty()) break;
jobOpt.get().getTasks().add(task);
}
}
if (!wasFirstLine) currentJob++;
}
fileScanner.close();
//////////////////////////////////
shop.getJobs().forEach(Job::calculateEarliestStart);
shop.getJobs().stream().max(Comparator.comparing(Job::calculateTotalDuration))
.ifPresent(job -> shop.getJobs().forEach(j -> j.calculateLatestStart(job.calculateTotalDuration())));
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
//TODO Fix dat hij de earliest start update als een taak begint die langer duurt dan de earliest start van een taak op de machine
//TODO In het huidige voorbeeld start Job 1 op Machine 0 (ES van 40, tijd 40) en heeft Job 2 op Machine 0 een ES van 60. Machine 0 is bezet tot 80, wat betekent dat die van Machine 0 moet updaten naar 80.
// int loop = 0;
int time = 0;
// while (loop < 40) {
while (!shop.isAllJobsDone()) {
// loop++;
System.out.println("------START------");
List<Job> conflictedJobs = new ArrayList<>();
int smallestTaskDuration = Integer.MAX_VALUE;
Map<Integer, Integer> foundTaskDurations = new HashMap<>(); //Key = machine ID, value = duration
for (Map.Entry<Job, Task> pair : shop.getTasksWithEarliestTimeNow(time)) {
if (foundTaskDurations.containsKey(pair.getValue().getMachineID())) { //Er is al een task met een kleinere slack gestart, er was dus een conflict op dit tijdstip!
pair.getValue().setEarliestStart(foundTaskDurations.get(pair.getValue().getMachineID()));
conflictedJobs.add(pair.getKey());
continue;
}
System.out.println("Job " + pair.getKey().getId() + " wordt uitgevoerd op machine " + pair.getValue().getMachineID() + ".");
pair.getValue().setDone(true);
pair.getKey().setBeginTime(time);
foundTaskDurations.put(pair.getValue().getMachineID(), pair.getValue().getDuration());
if (pair.getValue().getDuration() < smallestTaskDuration) smallestTaskDuration = pair.getValue().getDuration();
}
for (Job job : conflictedJobs) {
job.calculateEarliestStart();
}
if (!conflictedJobs.isEmpty()) {
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
}
if (smallestTaskDuration == Integer.MAX_VALUE) smallestTaskDuration = 1; //Als er op dit tijdstip geen taken draaien, tellen we er 1 bij op tot we weer wat vinden.
time += smallestTaskDuration;
for (Job j : shop.getJobs()) {
if (j.getEndTime() == 0 && j.hasAllTasksDone()) j.setEndTime(time);
}
System.out.println("Time: " + time);
}
for (Job j : shop.getJobs()) {
System.out.println(j.getId() + "\t" + j.getBeginTime() + "\t" + j.getEndTime());
}
}
}
| SBDPlugins/LeastSlackTime-OSM | src/main/java/nl/sbdeveloper/leastslack/LeastSlack.java | 1,705 | // int loop = 0; | line_comment | nl | package nl.sbdeveloper.leastslack;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LeastSlack {
private static final Pattern pattern = Pattern.compile("(\\d+)[ \\t]+(\\d+)");
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Geef een bestandsnaam mee!");
System.exit(0);
return;
}
URL resource = LeastSlack.class.getClassLoader().getResource(args[0]);
if (resource == null) {
System.out.println("De meegegeven bestandsnaam bestaat niet!");
System.exit(0);
return;
}
Scanner fileScanner = new Scanner(resource.openStream());
JobShop shop = new JobShop();
int jobs = 0;
int machines = 0;
int lowestMachine = Integer.MAX_VALUE;
boolean wasFirstLine;
int currentJob = 0;
Matcher matcher;
while (fileScanner.hasNextLine()) {
matcher = pattern.matcher(fileScanner.nextLine());
wasFirstLine = false;
if (jobs != 0 && machines != 0) {
Job job = new Job(currentJob);
shop.getJobs().add(job);
}
while (matcher.find()) {
if (jobs == 0 || machines == 0) {
jobs = Integer.parseInt(matcher.group(1));
machines = Integer.parseInt(matcher.group(2));
wasFirstLine = true;
break;
} else {
int id = Integer.parseInt(matcher.group(1));
int duration = Integer.parseInt(matcher.group(2));
if (id < lowestMachine) lowestMachine = id;
Task task = new Task(id, duration);
int finalCurrentJob = currentJob;
Optional<Job> jobOpt = shop.getJobs().stream().filter(j -> j.getId() == finalCurrentJob).findFirst();
if (jobOpt.isEmpty()) break;
jobOpt.get().getTasks().add(task);
}
}
if (!wasFirstLine) currentJob++;
}
fileScanner.close();
//////////////////////////////////
shop.getJobs().forEach(Job::calculateEarliestStart);
shop.getJobs().stream().max(Comparator.comparing(Job::calculateTotalDuration))
.ifPresent(job -> shop.getJobs().forEach(j -> j.calculateLatestStart(job.calculateTotalDuration())));
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
//TODO Fix dat hij de earliest start update als een taak begint die langer duurt dan de earliest start van een taak op de machine
//TODO In het huidige voorbeeld start Job 1 op Machine 0 (ES van 40, tijd 40) en heeft Job 2 op Machine 0 een ES van 60. Machine 0 is bezet tot 80, wat betekent dat die van Machine 0 moet updaten naar 80.
// int loop<SUF>
int time = 0;
// while (loop < 40) {
while (!shop.isAllJobsDone()) {
// loop++;
System.out.println("------START------");
List<Job> conflictedJobs = new ArrayList<>();
int smallestTaskDuration = Integer.MAX_VALUE;
Map<Integer, Integer> foundTaskDurations = new HashMap<>(); //Key = machine ID, value = duration
for (Map.Entry<Job, Task> pair : shop.getTasksWithEarliestTimeNow(time)) {
if (foundTaskDurations.containsKey(pair.getValue().getMachineID())) { //Er is al een task met een kleinere slack gestart, er was dus een conflict op dit tijdstip!
pair.getValue().setEarliestStart(foundTaskDurations.get(pair.getValue().getMachineID()));
conflictedJobs.add(pair.getKey());
continue;
}
System.out.println("Job " + pair.getKey().getId() + " wordt uitgevoerd op machine " + pair.getValue().getMachineID() + ".");
pair.getValue().setDone(true);
pair.getKey().setBeginTime(time);
foundTaskDurations.put(pair.getValue().getMachineID(), pair.getValue().getDuration());
if (pair.getValue().getDuration() < smallestTaskDuration) smallestTaskDuration = pair.getValue().getDuration();
}
for (Job job : conflictedJobs) {
job.calculateEarliestStart();
}
if (!conflictedJobs.isEmpty()) {
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
}
if (smallestTaskDuration == Integer.MAX_VALUE) smallestTaskDuration = 1; //Als er op dit tijdstip geen taken draaien, tellen we er 1 bij op tot we weer wat vinden.
time += smallestTaskDuration;
for (Job j : shop.getJobs()) {
if (j.getEndTime() == 0 && j.hasAllTasksDone()) j.setEndTime(time);
}
System.out.println("Time: " + time);
}
for (Job j : shop.getJobs()) {
System.out.println(j.getId() + "\t" + j.getBeginTime() + "\t" + j.getEndTime());
}
}
}
| false | 1,320 | 8 | 1,492 | 8 | 1,539 | 8 | 1,492 | 8 | 1,719 | 8 | false | false | false | false | false | true |
1,356 | 4744_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(), 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-2dook | DemoWorld.java | 3,194 | // 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(), 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();
}
}
| false | 3,419 | 24 | 3,459 | 24 | 3,455 | 20 | 3,459 | 24 | 3,542 | 25 | false | false | false | false | false | true |
2,193 | 55393_3 | /*
* SPDX-FileCopyrightText: 2021 Atos
* SPDX-License-Identifier: EUPL-1.2+
*/
package net.atos.client.zgw.drc.model;
import static net.atos.client.zgw.shared.util.DateTimeUtil.DATE_TIME_FORMAT_WITH_MILLISECONDS;
import java.net.URI;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.UUID;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.json.bind.annotation.JsonbProperty;
import javax.json.bind.annotation.JsonbTransient;
import net.atos.client.zgw.shared.model.Vertrouwelijkheidaanduiding;
import net.atos.client.zgw.shared.util.URIUtil;
/**
*
*/
public abstract class AbstractEnkelvoudigInformatieobject {
public static final int IDENTIFICATIE_MAX_LENGTH = 40;
public static final int TITEL_MAX_LENGTH = 200;
public static final int BESTANDSNAAM_MAX_LENGTH = 255;
public static final int FORMAAT_MAX_LENGTH = 255;
public static final int AUTEUR_MAX_LENGTH = 200;
public static final int BESCHRIJVING_MAX_LENGTH = 1000;
/**
* URL-referentie naar dit object. Dit is de unieke identificatie en locatie van dit object.
*/
private URI url;
/**
* Een binnen een gegeven context ondubbelzinnige referentie naar het INFORMATIEOBJECT.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#IDENTIFICATIE_MAX_LENGTH}
*/
private String identificatie;
/**
* Het RSIN van de Niet-natuurlijk persoon zijnde de organisatie die het informatieobject heeft gecreeerd of heeft ontvangen
* en als eerste in een samenwerkingsketen heeft vastgelegd.
*/
private String bronorganisatie;
/**
* Een datum of een gebeurtenis in de levenscyclus van het INFORMATIEOBJECT
*/
private LocalDate creatiedatum;
/**
* De naam waaronder het INFORMATIEOBJECT formeel bekend is.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#TITEL_MAX_LENGTH}
*/
private String titel;
/**
* Aanduiding van de mate waarin het INFORMATIEOBJECT voor de openbaarheid bestemd is
*/
private Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding;
/**
* De persoon of organisatie die in de eerste plaats verantwoordelijk is voor het creeren van de inhoud van het INFORMATIEOBJECT
* maxLength: {@link AbstractEnkelvoudigInformatieobject#AUTEUR_MAX_LENGTH}
*/
private String auteur;
/**
* Aanduiding van de stand van zaken van een INFORMATIEOBJECT.
* De waarden ''in bewerking'' en ''ter vaststelling'' komen niet voor als het attribuut `ontvangstdatum` van een waarde is voorzien.
* Wijziging van de Status in ''gearchiveerd'' impliceert dat het informatieobject een duurzaam, niet-wijzigbaar Formaat dient te hebben
*/
private InformatieobjectStatus status;
/**
* Het "Media Type" (voorheen "MIME type") voor de wijze waaropde inhoud van het INFORMATIEOBJECT is vastgelegd in een computerbestand.
* Voorbeeld: `application/msword`. Zie: https://www.iana.org/assignments/media-types/media-types.xhtml
* maxLength: {@link AbstractEnkelvoudigInformatieobject#FORMAAT_MAX_LENGTH}
*/
private String formaat;
/**
* Een ISO 639-2/B taalcode waarin de inhoud van het INFORMATIEOBJECT is vastgelegd.
* Voorbeeld: `nld`. Zie: https://www.iso.org/standard/4767.html
* maxLength: 3
* minLength: 3
*/
private String taal;
/**
* Het (automatische) versienummer van het INFORMATIEOBJECT.
* Deze begint bij 1 als het INFORMATIEOBJECT aangemaakt wordt.
*/
private Integer versie;
/**
* Een datumtijd in ISO8601 formaat waarop deze versie van het INFORMATIEOBJECT is aangemaakt of gewijzigd.
*/
@JsonbDateFormat(DATE_TIME_FORMAT_WITH_MILLISECONDS)
private ZonedDateTime beginRegistratie;
/**
* De naam van het fysieke bestand waarin de inhoud van het informatieobject is vastgelegd, inclusief extensie.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#BESTANDSNAAM_MAX_LENGTH}
*/
private String bestandsnaam;
/**
* Aantal bytes dat de inhoud van INFORMATIEOBJECT in beslag neemt.
*/
private Long bestandsomvang;
/**
* De URL waarmee de inhoud van het INFORMATIEOBJECT op te vragen
*/
private URI link;
/**
* Een generieke beschrijving van de inhoud van het INFORMATIEOBJECT.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#BESCHRIJVING_MAX_LENGTH}
*/
private String beschrijving;
/**
* De datum waarop het INFORMATIEOBJECT ontvangen is.
* Verplicht te registreren voor INFORMATIEOBJECTen die van buiten de zaakbehandelende organisatie(s) ontvangen zijn.
* Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn
* waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt.
*/
@JsonbProperty(nillable = true)
private LocalDate ontvangstdatum;
/**
* De datum waarop het INFORMATIEOBJECT verzonden is, zoals deze op het INFORMATIEOBJECT vermeld is.
* Dit geldt voor zowel inkomende als uitgaande INFORMATIEOBJECTen.
* Eenzelfde informatieobject kan niet tegelijk inkomend en uitgaand zijn.
* Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn
* waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt.
*/
@JsonbProperty(nillable = true)
private LocalDate verzenddatum;
/**
* Indicatie of er beperkingen gelden aangaande het gebruik van het informatieobject anders dan raadpleging.
* Dit veld mag `null` zijn om aan te geven dat de indicatie nog niet bekend is.
* Als de indicatie gezet is, dan kan je de gebruiksrechten die van toepassing zijn raadplegen via de GEBRUIKSRECHTen resource.
*/
private Boolean indicatieGebruiksrecht;
/**
* Aanduiding van de rechtskracht van een informatieobject.
* Mag niet van een waarde zijn voorzien als de `status` de waarde 'in bewerking' of 'ter vaststelling' heeft.
*/
private Ondertekening ondertekening;
/**
* Uitdrukking van mate van volledigheid en onbeschadigd zijn van digitaal bestand.
*/
private Integriteit integriteit;
/**
* URL-referentie naar het INFORMATIEOBJECTTYPE (in de Catalogi API).
*/
private URI informatieobjecttype;
/**
* Geeft aan of het document gelocked is. Alleen als een document gelocked is, mogen er aanpassingen gemaakt worden.
*/
private Boolean locked;
public URI getUrl() {
return url;
}
public void setUrl(final URI url) {
this.url = url;
}
public String getIdentificatie() {
return identificatie;
}
public void setIdentificatie(final String identificatie) {
this.identificatie = identificatie;
}
public String getBronorganisatie() {
return bronorganisatie;
}
public void setBronorganisatie(final String bronorganisatie) {
this.bronorganisatie = bronorganisatie;
}
public LocalDate getCreatiedatum() {
return creatiedatum;
}
public void setCreatiedatum(final LocalDate creatiedatum) {
this.creatiedatum = creatiedatum;
}
public String getTitel() {
return titel;
}
public void setTitel(final String titel) {
this.titel = titel;
}
public Vertrouwelijkheidaanduiding getVertrouwelijkheidaanduiding() {
return vertrouwelijkheidaanduiding;
}
public void setVertrouwelijkheidaanduiding(final Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding) {
this.vertrouwelijkheidaanduiding = vertrouwelijkheidaanduiding;
}
public String getAuteur() {
return auteur;
}
public void setAuteur(final String auteur) {
this.auteur = auteur;
}
public InformatieobjectStatus getStatus() {
return status;
}
public void setStatus(final InformatieobjectStatus status) {
this.status = status;
}
public String getFormaat() {
return formaat;
}
public void setFormaat(final String formaat) {
this.formaat = formaat;
}
public String getTaal() {
return taal;
}
public void setTaal(final String taal) {
this.taal = taal;
}
public Integer getVersie() {
return versie;
}
public void setVersie(final Integer versie) {
this.versie = versie;
}
public ZonedDateTime getBeginRegistratie() {
return beginRegistratie;
}
public void setBeginRegistratie(final ZonedDateTime beginRegistratie) {
this.beginRegistratie = beginRegistratie;
}
public String getBestandsnaam() {
return bestandsnaam;
}
public void setBestandsnaam(final String bestandsnaam) {
this.bestandsnaam = bestandsnaam;
}
public Long getBestandsomvang() {
return bestandsomvang;
}
public void setBestandsomvang(final Long bestandsomvang) {
this.bestandsomvang = bestandsomvang;
}
public URI getLink() {
return link;
}
public void setLink(final URI link) {
this.link = link;
}
public String getBeschrijving() {
return beschrijving;
}
public void setBeschrijving(final String beschrijving) {
this.beschrijving = beschrijving;
}
public LocalDate getOntvangstdatum() {
return ontvangstdatum;
}
public void setOntvangstdatum(final LocalDate ontvangstdatum) {
this.ontvangstdatum = ontvangstdatum;
}
public LocalDate getVerzenddatum() {
return verzenddatum;
}
public void setVerzenddatum(final LocalDate verzenddatum) {
this.verzenddatum = verzenddatum;
}
public Boolean getIndicatieGebruiksrecht() {
return indicatieGebruiksrecht;
}
public void setIndicatieGebruiksrecht(final Boolean indicatieGebruiksrecht) {
this.indicatieGebruiksrecht = indicatieGebruiksrecht;
}
public Ondertekening getOndertekening() {
if (ondertekening != null && ondertekening.getDatum() == null && ondertekening.getSoort() == null) {
return null;
}
return ondertekening;
}
public void setOndertekening(final Ondertekening ondertekening) {
this.ondertekening = ondertekening;
}
public Integriteit getIntegriteit() {
return integriteit;
}
public void setIntegriteit(final Integriteit integriteit) {
this.integriteit = integriteit;
}
public URI getInformatieobjecttype() {
return informatieobjecttype;
}
public void setInformatieobjecttype(final URI informatieobjecttype) {
this.informatieobjecttype = informatieobjecttype;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(final Boolean locked) {
this.locked = locked;
}
@JsonbTransient
public UUID getUUID() {
return URIUtil.parseUUIDFromResourceURI(url);
}
@JsonbTransient
public UUID getInformatieobjectTypeUUID() {
return URIUtil.parseUUIDFromResourceURI(informatieobjecttype);
}
}
| bartlukens/zaakafhandelcomponent | src/main/java/net/atos/client/zgw/drc/model/AbstractEnkelvoudigInformatieobject.java | 3,539 | /**
* Het RSIN van de Niet-natuurlijk persoon zijnde de organisatie die het informatieobject heeft gecreeerd of heeft ontvangen
* en als eerste in een samenwerkingsketen heeft vastgelegd.
*/ | block_comment | nl | /*
* SPDX-FileCopyrightText: 2021 Atos
* SPDX-License-Identifier: EUPL-1.2+
*/
package net.atos.client.zgw.drc.model;
import static net.atos.client.zgw.shared.util.DateTimeUtil.DATE_TIME_FORMAT_WITH_MILLISECONDS;
import java.net.URI;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.UUID;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.json.bind.annotation.JsonbProperty;
import javax.json.bind.annotation.JsonbTransient;
import net.atos.client.zgw.shared.model.Vertrouwelijkheidaanduiding;
import net.atos.client.zgw.shared.util.URIUtil;
/**
*
*/
public abstract class AbstractEnkelvoudigInformatieobject {
public static final int IDENTIFICATIE_MAX_LENGTH = 40;
public static final int TITEL_MAX_LENGTH = 200;
public static final int BESTANDSNAAM_MAX_LENGTH = 255;
public static final int FORMAAT_MAX_LENGTH = 255;
public static final int AUTEUR_MAX_LENGTH = 200;
public static final int BESCHRIJVING_MAX_LENGTH = 1000;
/**
* URL-referentie naar dit object. Dit is de unieke identificatie en locatie van dit object.
*/
private URI url;
/**
* Een binnen een gegeven context ondubbelzinnige referentie naar het INFORMATIEOBJECT.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#IDENTIFICATIE_MAX_LENGTH}
*/
private String identificatie;
/**
* Het RSIN van<SUF>*/
private String bronorganisatie;
/**
* Een datum of een gebeurtenis in de levenscyclus van het INFORMATIEOBJECT
*/
private LocalDate creatiedatum;
/**
* De naam waaronder het INFORMATIEOBJECT formeel bekend is.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#TITEL_MAX_LENGTH}
*/
private String titel;
/**
* Aanduiding van de mate waarin het INFORMATIEOBJECT voor de openbaarheid bestemd is
*/
private Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding;
/**
* De persoon of organisatie die in de eerste plaats verantwoordelijk is voor het creeren van de inhoud van het INFORMATIEOBJECT
* maxLength: {@link AbstractEnkelvoudigInformatieobject#AUTEUR_MAX_LENGTH}
*/
private String auteur;
/**
* Aanduiding van de stand van zaken van een INFORMATIEOBJECT.
* De waarden ''in bewerking'' en ''ter vaststelling'' komen niet voor als het attribuut `ontvangstdatum` van een waarde is voorzien.
* Wijziging van de Status in ''gearchiveerd'' impliceert dat het informatieobject een duurzaam, niet-wijzigbaar Formaat dient te hebben
*/
private InformatieobjectStatus status;
/**
* Het "Media Type" (voorheen "MIME type") voor de wijze waaropde inhoud van het INFORMATIEOBJECT is vastgelegd in een computerbestand.
* Voorbeeld: `application/msword`. Zie: https://www.iana.org/assignments/media-types/media-types.xhtml
* maxLength: {@link AbstractEnkelvoudigInformatieobject#FORMAAT_MAX_LENGTH}
*/
private String formaat;
/**
* Een ISO 639-2/B taalcode waarin de inhoud van het INFORMATIEOBJECT is vastgelegd.
* Voorbeeld: `nld`. Zie: https://www.iso.org/standard/4767.html
* maxLength: 3
* minLength: 3
*/
private String taal;
/**
* Het (automatische) versienummer van het INFORMATIEOBJECT.
* Deze begint bij 1 als het INFORMATIEOBJECT aangemaakt wordt.
*/
private Integer versie;
/**
* Een datumtijd in ISO8601 formaat waarop deze versie van het INFORMATIEOBJECT is aangemaakt of gewijzigd.
*/
@JsonbDateFormat(DATE_TIME_FORMAT_WITH_MILLISECONDS)
private ZonedDateTime beginRegistratie;
/**
* De naam van het fysieke bestand waarin de inhoud van het informatieobject is vastgelegd, inclusief extensie.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#BESTANDSNAAM_MAX_LENGTH}
*/
private String bestandsnaam;
/**
* Aantal bytes dat de inhoud van INFORMATIEOBJECT in beslag neemt.
*/
private Long bestandsomvang;
/**
* De URL waarmee de inhoud van het INFORMATIEOBJECT op te vragen
*/
private URI link;
/**
* Een generieke beschrijving van de inhoud van het INFORMATIEOBJECT.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#BESCHRIJVING_MAX_LENGTH}
*/
private String beschrijving;
/**
* De datum waarop het INFORMATIEOBJECT ontvangen is.
* Verplicht te registreren voor INFORMATIEOBJECTen die van buiten de zaakbehandelende organisatie(s) ontvangen zijn.
* Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn
* waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt.
*/
@JsonbProperty(nillable = true)
private LocalDate ontvangstdatum;
/**
* De datum waarop het INFORMATIEOBJECT verzonden is, zoals deze op het INFORMATIEOBJECT vermeld is.
* Dit geldt voor zowel inkomende als uitgaande INFORMATIEOBJECTen.
* Eenzelfde informatieobject kan niet tegelijk inkomend en uitgaand zijn.
* Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn
* waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt.
*/
@JsonbProperty(nillable = true)
private LocalDate verzenddatum;
/**
* Indicatie of er beperkingen gelden aangaande het gebruik van het informatieobject anders dan raadpleging.
* Dit veld mag `null` zijn om aan te geven dat de indicatie nog niet bekend is.
* Als de indicatie gezet is, dan kan je de gebruiksrechten die van toepassing zijn raadplegen via de GEBRUIKSRECHTen resource.
*/
private Boolean indicatieGebruiksrecht;
/**
* Aanduiding van de rechtskracht van een informatieobject.
* Mag niet van een waarde zijn voorzien als de `status` de waarde 'in bewerking' of 'ter vaststelling' heeft.
*/
private Ondertekening ondertekening;
/**
* Uitdrukking van mate van volledigheid en onbeschadigd zijn van digitaal bestand.
*/
private Integriteit integriteit;
/**
* URL-referentie naar het INFORMATIEOBJECTTYPE (in de Catalogi API).
*/
private URI informatieobjecttype;
/**
* Geeft aan of het document gelocked is. Alleen als een document gelocked is, mogen er aanpassingen gemaakt worden.
*/
private Boolean locked;
public URI getUrl() {
return url;
}
public void setUrl(final URI url) {
this.url = url;
}
public String getIdentificatie() {
return identificatie;
}
public void setIdentificatie(final String identificatie) {
this.identificatie = identificatie;
}
public String getBronorganisatie() {
return bronorganisatie;
}
public void setBronorganisatie(final String bronorganisatie) {
this.bronorganisatie = bronorganisatie;
}
public LocalDate getCreatiedatum() {
return creatiedatum;
}
public void setCreatiedatum(final LocalDate creatiedatum) {
this.creatiedatum = creatiedatum;
}
public String getTitel() {
return titel;
}
public void setTitel(final String titel) {
this.titel = titel;
}
public Vertrouwelijkheidaanduiding getVertrouwelijkheidaanduiding() {
return vertrouwelijkheidaanduiding;
}
public void setVertrouwelijkheidaanduiding(final Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding) {
this.vertrouwelijkheidaanduiding = vertrouwelijkheidaanduiding;
}
public String getAuteur() {
return auteur;
}
public void setAuteur(final String auteur) {
this.auteur = auteur;
}
public InformatieobjectStatus getStatus() {
return status;
}
public void setStatus(final InformatieobjectStatus status) {
this.status = status;
}
public String getFormaat() {
return formaat;
}
public void setFormaat(final String formaat) {
this.formaat = formaat;
}
public String getTaal() {
return taal;
}
public void setTaal(final String taal) {
this.taal = taal;
}
public Integer getVersie() {
return versie;
}
public void setVersie(final Integer versie) {
this.versie = versie;
}
public ZonedDateTime getBeginRegistratie() {
return beginRegistratie;
}
public void setBeginRegistratie(final ZonedDateTime beginRegistratie) {
this.beginRegistratie = beginRegistratie;
}
public String getBestandsnaam() {
return bestandsnaam;
}
public void setBestandsnaam(final String bestandsnaam) {
this.bestandsnaam = bestandsnaam;
}
public Long getBestandsomvang() {
return bestandsomvang;
}
public void setBestandsomvang(final Long bestandsomvang) {
this.bestandsomvang = bestandsomvang;
}
public URI getLink() {
return link;
}
public void setLink(final URI link) {
this.link = link;
}
public String getBeschrijving() {
return beschrijving;
}
public void setBeschrijving(final String beschrijving) {
this.beschrijving = beschrijving;
}
public LocalDate getOntvangstdatum() {
return ontvangstdatum;
}
public void setOntvangstdatum(final LocalDate ontvangstdatum) {
this.ontvangstdatum = ontvangstdatum;
}
public LocalDate getVerzenddatum() {
return verzenddatum;
}
public void setVerzenddatum(final LocalDate verzenddatum) {
this.verzenddatum = verzenddatum;
}
public Boolean getIndicatieGebruiksrecht() {
return indicatieGebruiksrecht;
}
public void setIndicatieGebruiksrecht(final Boolean indicatieGebruiksrecht) {
this.indicatieGebruiksrecht = indicatieGebruiksrecht;
}
public Ondertekening getOndertekening() {
if (ondertekening != null && ondertekening.getDatum() == null && ondertekening.getSoort() == null) {
return null;
}
return ondertekening;
}
public void setOndertekening(final Ondertekening ondertekening) {
this.ondertekening = ondertekening;
}
public Integriteit getIntegriteit() {
return integriteit;
}
public void setIntegriteit(final Integriteit integriteit) {
this.integriteit = integriteit;
}
public URI getInformatieobjecttype() {
return informatieobjecttype;
}
public void setInformatieobjecttype(final URI informatieobjecttype) {
this.informatieobjecttype = informatieobjecttype;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(final Boolean locked) {
this.locked = locked;
}
@JsonbTransient
public UUID getUUID() {
return URIUtil.parseUUIDFromResourceURI(url);
}
@JsonbTransient
public UUID getInformatieobjectTypeUUID() {
return URIUtil.parseUUIDFromResourceURI(informatieobjecttype);
}
}
| false | 2,944 | 54 | 3,230 | 66 | 3,088 | 51 | 3,231 | 66 | 3,615 | 60 | false | false | false | false | false | true |
644 | 44589_2 | package nl.han.ica.oopd.waterworld;
import nl.han.ica.oopg.collision.ICollidableWithGameObjects;
import nl.han.ica.oopg.objects.GameObject;
import nl.han.ica.oopg.sound.Sound;
import processing.core.PGraphics;
import java.util.List;
/**
* @author Ralph Niels
* Bel-klasse
*/
public class Bubble extends GameObject implements ICollidableWithGameObjects {
private final Sound popSound;
private WaterWorld world;
private int bubbleSize;
/**
* Constructor
*
* @param bubbleSize Afmeting van de bel
* @param world Referentie naar de wereld
* @param popSound Geluid dat moet klinken als de bel knapt
*/
public Bubble(int bubbleSize, WaterWorld world, Sound popSound) {
this.bubbleSize = bubbleSize;
this.popSound = popSound;
this.world = world;
setySpeed(-bubbleSize / 10f);
/* De volgende regels zijn in een zelfgekend object nodig
om collisiondetectie mogelijk te maken.
*/
setHeight(bubbleSize);
setWidth(bubbleSize);
}
@Override
public void update() {
if (getY() <= 100) {
world.deleteGameObject(this);
}
}
@Override
public void draw(PGraphics g) {
g.ellipseMode(g.CORNER); // Omdat cirkel anders vanuit midden wordt getekend en dat problemen geeft bij collisiondetectie
g.stroke(0, 50, 200, 100);
g.fill(0, 50, 200, 50);
g.ellipse(getX(), getY(), bubbleSize, bubbleSize);
}
@Override
public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) {
for (GameObject g : collidedGameObjects) {
if (g instanceof Swordfish) {
popSound.rewind();
popSound.play();
world.deleteGameObject(this);
world.increaseBubblesPopped();
}
}
}
}
| HANICA/waterworld | src/main/java/nl/han/ica/oopd/waterworld/Bubble.java | 586 | /* De volgende regels zijn in een zelfgekend object nodig
om collisiondetectie mogelijk te maken.
*/ | block_comment | nl | package nl.han.ica.oopd.waterworld;
import nl.han.ica.oopg.collision.ICollidableWithGameObjects;
import nl.han.ica.oopg.objects.GameObject;
import nl.han.ica.oopg.sound.Sound;
import processing.core.PGraphics;
import java.util.List;
/**
* @author Ralph Niels
* Bel-klasse
*/
public class Bubble extends GameObject implements ICollidableWithGameObjects {
private final Sound popSound;
private WaterWorld world;
private int bubbleSize;
/**
* Constructor
*
* @param bubbleSize Afmeting van de bel
* @param world Referentie naar de wereld
* @param popSound Geluid dat moet klinken als de bel knapt
*/
public Bubble(int bubbleSize, WaterWorld world, Sound popSound) {
this.bubbleSize = bubbleSize;
this.popSound = popSound;
this.world = world;
setySpeed(-bubbleSize / 10f);
/* De volgende regels<SUF>*/
setHeight(bubbleSize);
setWidth(bubbleSize);
}
@Override
public void update() {
if (getY() <= 100) {
world.deleteGameObject(this);
}
}
@Override
public void draw(PGraphics g) {
g.ellipseMode(g.CORNER); // Omdat cirkel anders vanuit midden wordt getekend en dat problemen geeft bij collisiondetectie
g.stroke(0, 50, 200, 100);
g.fill(0, 50, 200, 50);
g.ellipse(getX(), getY(), bubbleSize, bubbleSize);
}
@Override
public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) {
for (GameObject g : collidedGameObjects) {
if (g instanceof Swordfish) {
popSound.rewind();
popSound.play();
world.deleteGameObject(this);
world.increaseBubblesPopped();
}
}
}
}
| false | 474 | 28 | 520 | 30 | 527 | 25 | 520 | 30 | 600 | 32 | false | false | false | false | false | true |
1,020 | 209269_11 | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} | MRoeland/KoalaExpress | app/src/main/java/be/ehb/koalaexpress/CheckoutActivity.java | 1,762 | // 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan | line_comment | nl | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden<SUF>
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} | false | 1,227 | 25 | 1,446 | 29 | 1,477 | 23 | 1,446 | 29 | 1,708 | 26 | false | false | false | false | false | true |
4,291 | 19807_8 | package rekenen;
import rekenen.plugins.Plugin;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* PEER TUTORING
* P2W3
*/
public class Rekenmachine {
private final int MAX_AANTAL_PLUGINS = 10;
private Plugin[] ingeladenPlugins;
private int aantalPlugins;
private StringBuilder log;
private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd MMMM yyyy hh:mm:ss.SSSS");
public Rekenmachine() {
this.ingeladenPlugins = new Plugin[MAX_AANTAL_PLUGINS];
aantalPlugins = 0;
initLog();
}
public void installeer(Plugin teInstallerenPlugin) {
//Opgave 2.1.a
// Simpele oplossing:
boolean isInstalled = false;
for (int i = 0; i < aantalPlugins; i++) {
if (ingeladenPlugins[i].getCommand().equals(teInstallerenPlugin.getCommand())) {
isInstalled = true;
break;
}
}
if (!isInstalled)
ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin;
// Java 8 Streams oplossing:
/*
Arrays.stream(ingeladenPlugins) -> maakt van de array een Stream
.filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())) -> gooi de elementen die null zijn en waarvan het commando niet hetzelfde is weg
findAny() -> geef mij eender welk element dat de stream overleeft heeft, geencapsuleerd in een Optional (we zijn namelijk niet zeker dat er een is)
.isPresent() -> is er een element dat de filter overleefd heeft?
*/
// if (!Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())).findAny().isPresent() && aantalPlugins < MAX_AANTAL_PLUGINS) {
// ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin;
// }
}
public double bereken(String command, double x, double y) {
//Opgave 2.1.b
// Simpele oplossing:
Plugin plugin = null;
for (int i = 0; i < aantalPlugins; i++) {
if(ingeladenPlugins[i].getCommand().equals(command.trim())){
plugin = ingeladenPlugins[i];
break;
}
}
if(plugin!= null){
double result = plugin.bereken(x,y);
log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.getAuteur()));
return result;
} else {
System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command));
return Double.POSITIVE_INFINITY;
}
// Java 8 Streams:
// Optional<Plugin> plugin = Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(command.trim())).findAny();
// if (plugin.isPresent()) {
// double result = plugin.get().bereken(x, y);
// log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.get().getAuteur()));
// return result;
// } else {
// System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command));
// return Double.POSITIVE_INFINITY;
// }
}
@Override
public String toString() {
//Opgave 2.1c
// Simpele oplossing:
String result = "Geïnstalleerde Plugins:";
for (int i = 0; i < aantalPlugins; i++) {
result += " " + ingeladenPlugins[i].getCommand();
}
return result;
// Java 8 Streams:
/*
.map(p -> " " + p.getCommand()) -> maak van elk object in de stream (dus van elke plugin) een nieuw object. Dit object is " " + het commando van de plugin.
.collect(Collectors.joining("")) -> .collect haalt alle elementen in de stream bij elkaar. Collectors.joining("") plakt al de elementen aan elkaar.
*/
// return "Geïnstalleerde Plugins:" + Arrays.stream(ingeladenPlugins).filter(p -> p != null).map(p -> " " + p.getCommand()).collect(Collectors.joining(""));
}
public String getLog() {
String result = log.toString();
initLog();
return result;
}
private void initLog() {
this.log = new StringBuilder();
this.log.append("==== LOG ====");
}
}
| sgentens/Peer-Tutoring-Sessie7 | Sessie7/src/rekenen/Rekenmachine.java | 1,405 | // double result = plugin.get().bereken(x, y); | line_comment | nl | package rekenen;
import rekenen.plugins.Plugin;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* PEER TUTORING
* P2W3
*/
public class Rekenmachine {
private final int MAX_AANTAL_PLUGINS = 10;
private Plugin[] ingeladenPlugins;
private int aantalPlugins;
private StringBuilder log;
private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd MMMM yyyy hh:mm:ss.SSSS");
public Rekenmachine() {
this.ingeladenPlugins = new Plugin[MAX_AANTAL_PLUGINS];
aantalPlugins = 0;
initLog();
}
public void installeer(Plugin teInstallerenPlugin) {
//Opgave 2.1.a
// Simpele oplossing:
boolean isInstalled = false;
for (int i = 0; i < aantalPlugins; i++) {
if (ingeladenPlugins[i].getCommand().equals(teInstallerenPlugin.getCommand())) {
isInstalled = true;
break;
}
}
if (!isInstalled)
ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin;
// Java 8 Streams oplossing:
/*
Arrays.stream(ingeladenPlugins) -> maakt van de array een Stream
.filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())) -> gooi de elementen die null zijn en waarvan het commando niet hetzelfde is weg
findAny() -> geef mij eender welk element dat de stream overleeft heeft, geencapsuleerd in een Optional (we zijn namelijk niet zeker dat er een is)
.isPresent() -> is er een element dat de filter overleefd heeft?
*/
// if (!Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())).findAny().isPresent() && aantalPlugins < MAX_AANTAL_PLUGINS) {
// ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin;
// }
}
public double bereken(String command, double x, double y) {
//Opgave 2.1.b
// Simpele oplossing:
Plugin plugin = null;
for (int i = 0; i < aantalPlugins; i++) {
if(ingeladenPlugins[i].getCommand().equals(command.trim())){
plugin = ingeladenPlugins[i];
break;
}
}
if(plugin!= null){
double result = plugin.bereken(x,y);
log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.getAuteur()));
return result;
} else {
System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command));
return Double.POSITIVE_INFINITY;
}
// Java 8 Streams:
// Optional<Plugin> plugin = Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(command.trim())).findAny();
// if (plugin.isPresent()) {
// double result<SUF>
// log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.get().getAuteur()));
// return result;
// } else {
// System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command));
// return Double.POSITIVE_INFINITY;
// }
}
@Override
public String toString() {
//Opgave 2.1c
// Simpele oplossing:
String result = "Geïnstalleerde Plugins:";
for (int i = 0; i < aantalPlugins; i++) {
result += " " + ingeladenPlugins[i].getCommand();
}
return result;
// Java 8 Streams:
/*
.map(p -> " " + p.getCommand()) -> maak van elk object in de stream (dus van elke plugin) een nieuw object. Dit object is " " + het commando van de plugin.
.collect(Collectors.joining("")) -> .collect haalt alle elementen in de stream bij elkaar. Collectors.joining("") plakt al de elementen aan elkaar.
*/
// return "Geïnstalleerde Plugins:" + Arrays.stream(ingeladenPlugins).filter(p -> p != null).map(p -> " " + p.getCommand()).collect(Collectors.joining(""));
}
public String getLog() {
String result = log.toString();
initLog();
return result;
}
private void initLog() {
this.log = new StringBuilder();
this.log.append("==== LOG ====");
}
}
| false | 1,089 | 14 | 1,231 | 16 | 1,232 | 16 | 1,231 | 16 | 1,388 | 16 | false | false | false | false | false | true |
3,993 | 19056_6 | package bozels.gui.panels;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import bozels.gui.actions.BooleanValueSelectAction;
import bozels.gui.basicComponents.AutoJLabel;
import bozels.gui.basicComponents.ColorButton;
import bozels.gui.basicComponents.coloringTextField.DoubleValueTextField;
import bozels.gui.resourceModel.ResourceTracker;
import bozels.gui.resourceModel.guiColorModel.GUIColorModel;
import bozels.gui.resourceModel.localeConstant.LocaleConstant;
import bozels.physicsModel.material.Material;
import bozels.superModel.SuperModel;
import bozels.valueWrappers.Value;
import bozels.visualisatie.gameColorModel.GameColorModel;
/**
* Bozels
*
* Door:
* Pieter Vander Vennet
* 1ste Bachelor Informatica
* Universiteit Gent
*
*/
public class OneMaterialEditorPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final GUIColorModel colorSettings;
public OneMaterialEditorPanel(final SuperModel supM, final Material mat, boolean showBreakable) {
final ResourceTracker tracker = supM.getResourceModel();
colorSettings = supM.getResourceModel().getGuiColorModel();
// \\//\\//\\//\\ LABELS //\\//\\//\\//\\
JLabel density = new AutoJLabel(tracker, LocaleConstant.DENSITY);
JLabel restit = new AutoJLabel(tracker, LocaleConstant.RESTITUTION);
JLabel friction = new AutoJLabel(tracker, LocaleConstant.FRICTION);
JLabel color = new AutoJLabel(tracker, LocaleConstant.COLOR);
JLabel empty = new JLabel();
JLabel powerThrs = new AutoJLabel(tracker, LocaleConstant.POWER_THRESHOLD);
JLabel strength = new AutoJLabel(tracker, LocaleConstant.STRENGTH);
JLabel sleepingColor = new AutoJLabel(tracker, LocaleConstant.SLEEPING_COLOR);
// \\//\\//\\//\\ COlor chooser //\\//\\//\\//\\
GameColorModel cm = supM.getGameColorModel();
LocaleConstant name = mat.getMaterialName();
int key = mat.getColorKey();
JButton colorPicker = new ColorButton(supM, name, null, cm.getColorValue(key));
JButton sleepingColorPicker = new ColorButton(supM, name, null , cm.getSleepingColorValue(key));
// \\//\\//\\//\\ FIELDS //\\//\\//\\//\\
JTextField dens = createField(mat.getDensitValue());
JTextField rest = createField(mat.getRestitutionValue());
JTextField frict = createField(mat.getFrictionValue());
JTextField powThr = createField(mat.getPowerThresholdValue());
JTextField str = createField(mat.getStrengthValue());
// \\//\\//\\//\\ Checkbox //\\//\\//\\//\\
BooleanValueSelectAction sw = new BooleanValueSelectAction(mat.getCanBreak(),
LocaleConstant.BREAKABLE, tracker);
sw.getSwitchesWith().add(powThr);
sw.getSwitchesWith().add(str);
sw.revalidate();
JCheckBox breakable = new JCheckBox(sw);
// \\//\\//\\//\\ LAYOUT //\\//\\//\\//\\
GroupLayout l = new GroupLayout(this);
this.setLayout(l);
/*
* VERANTWOORDING:
*
* Hier een if-else voor de layout is inderdaad lelijk.
* Ik heb echter gekozen om deze hier te gebruiken,
* omdat op deze manier de layout van het linker- en rechterstuk dezelfde layout kunnen gebruiken.
*
* Op deze manier zullen de layouts altijd mooi samenblijven, hoewel dit minder elegant is naar
* klassenstructuur toe.
*
*/
if(showBreakable){
l.setHorizontalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.TRAILING,
density,restit, friction, color))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
dens, rest, frict, colorPicker))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(createPar(l, Alignment.TRAILING,
empty, powerThrs, strength, sleepingColor))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
breakable, powThr, str, sleepingColorPicker))
);
l.setVerticalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.BASELINE, density, dens, empty, breakable))
.addGroup(createPar(l, Alignment.BASELINE, restit, rest, powerThrs, powThr))
.addGroup(createPar(l, Alignment.BASELINE, friction, frict, strength, str))
.addGroup(createPar(l, Alignment.BASELINE, color, colorPicker, sleepingColor, sleepingColorPicker)
)
.addContainerGap()
);
}else{
l.setHorizontalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.TRAILING,
density,restit, friction, color))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
dens, rest, frict, colorPicker))
);
l.setVerticalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.BASELINE, density, dens))
.addGroup(createPar(l, Alignment.BASELINE, restit, rest))
.addGroup(createPar(l, Alignment.BASELINE, friction, frict))
.addGroup(createPar(l, Alignment.BASELINE, color, colorPicker))
.addContainerGap());
}
}
private ParallelGroup createPar(GroupLayout l, Alignment al, JComponent... components){
ParallelGroup group = l.createParallelGroup(al);
for (JComponent jComponent : components) {
group.addComponent(jComponent);
}
return group;
}
private DoubleValueTextField createField(Value<Double> val){
return new DoubleValueTextField(colorSettings, val, 0, 10000, 10000);
}
}
| pietervdvn/Bozels | src/bozels/gui/panels/OneMaterialEditorPanel.java | 1,960 | /*
* VERANTWOORDING:
*
* Hier een if-else voor de layout is inderdaad lelijk.
* Ik heb echter gekozen om deze hier te gebruiken,
* omdat op deze manier de layout van het linker- en rechterstuk dezelfde layout kunnen gebruiken.
*
* Op deze manier zullen de layouts altijd mooi samenblijven, hoewel dit minder elegant is naar
* klassenstructuur toe.
*
*/ | block_comment | nl | package bozels.gui.panels;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import bozels.gui.actions.BooleanValueSelectAction;
import bozels.gui.basicComponents.AutoJLabel;
import bozels.gui.basicComponents.ColorButton;
import bozels.gui.basicComponents.coloringTextField.DoubleValueTextField;
import bozels.gui.resourceModel.ResourceTracker;
import bozels.gui.resourceModel.guiColorModel.GUIColorModel;
import bozels.gui.resourceModel.localeConstant.LocaleConstant;
import bozels.physicsModel.material.Material;
import bozels.superModel.SuperModel;
import bozels.valueWrappers.Value;
import bozels.visualisatie.gameColorModel.GameColorModel;
/**
* Bozels
*
* Door:
* Pieter Vander Vennet
* 1ste Bachelor Informatica
* Universiteit Gent
*
*/
public class OneMaterialEditorPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final GUIColorModel colorSettings;
public OneMaterialEditorPanel(final SuperModel supM, final Material mat, boolean showBreakable) {
final ResourceTracker tracker = supM.getResourceModel();
colorSettings = supM.getResourceModel().getGuiColorModel();
// \\//\\//\\//\\ LABELS //\\//\\//\\//\\
JLabel density = new AutoJLabel(tracker, LocaleConstant.DENSITY);
JLabel restit = new AutoJLabel(tracker, LocaleConstant.RESTITUTION);
JLabel friction = new AutoJLabel(tracker, LocaleConstant.FRICTION);
JLabel color = new AutoJLabel(tracker, LocaleConstant.COLOR);
JLabel empty = new JLabel();
JLabel powerThrs = new AutoJLabel(tracker, LocaleConstant.POWER_THRESHOLD);
JLabel strength = new AutoJLabel(tracker, LocaleConstant.STRENGTH);
JLabel sleepingColor = new AutoJLabel(tracker, LocaleConstant.SLEEPING_COLOR);
// \\//\\//\\//\\ COlor chooser //\\//\\//\\//\\
GameColorModel cm = supM.getGameColorModel();
LocaleConstant name = mat.getMaterialName();
int key = mat.getColorKey();
JButton colorPicker = new ColorButton(supM, name, null, cm.getColorValue(key));
JButton sleepingColorPicker = new ColorButton(supM, name, null , cm.getSleepingColorValue(key));
// \\//\\//\\//\\ FIELDS //\\//\\//\\//\\
JTextField dens = createField(mat.getDensitValue());
JTextField rest = createField(mat.getRestitutionValue());
JTextField frict = createField(mat.getFrictionValue());
JTextField powThr = createField(mat.getPowerThresholdValue());
JTextField str = createField(mat.getStrengthValue());
// \\//\\//\\//\\ Checkbox //\\//\\//\\//\\
BooleanValueSelectAction sw = new BooleanValueSelectAction(mat.getCanBreak(),
LocaleConstant.BREAKABLE, tracker);
sw.getSwitchesWith().add(powThr);
sw.getSwitchesWith().add(str);
sw.revalidate();
JCheckBox breakable = new JCheckBox(sw);
// \\//\\//\\//\\ LAYOUT //\\//\\//\\//\\
GroupLayout l = new GroupLayout(this);
this.setLayout(l);
/*
* VERANTWOORDING:
<SUF>*/
if(showBreakable){
l.setHorizontalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.TRAILING,
density,restit, friction, color))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
dens, rest, frict, colorPicker))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(createPar(l, Alignment.TRAILING,
empty, powerThrs, strength, sleepingColor))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
breakable, powThr, str, sleepingColorPicker))
);
l.setVerticalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.BASELINE, density, dens, empty, breakable))
.addGroup(createPar(l, Alignment.BASELINE, restit, rest, powerThrs, powThr))
.addGroup(createPar(l, Alignment.BASELINE, friction, frict, strength, str))
.addGroup(createPar(l, Alignment.BASELINE, color, colorPicker, sleepingColor, sleepingColorPicker)
)
.addContainerGap()
);
}else{
l.setHorizontalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.TRAILING,
density,restit, friction, color))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
dens, rest, frict, colorPicker))
);
l.setVerticalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.BASELINE, density, dens))
.addGroup(createPar(l, Alignment.BASELINE, restit, rest))
.addGroup(createPar(l, Alignment.BASELINE, friction, frict))
.addGroup(createPar(l, Alignment.BASELINE, color, colorPicker))
.addContainerGap());
}
}
private ParallelGroup createPar(GroupLayout l, Alignment al, JComponent... components){
ParallelGroup group = l.createParallelGroup(al);
for (JComponent jComponent : components) {
group.addComponent(jComponent);
}
return group;
}
private DoubleValueTextField createField(Value<Double> val){
return new DoubleValueTextField(colorSettings, val, 0, 10000, 10000);
}
}
| false | 1,371 | 117 | 1,652 | 137 | 1,601 | 119 | 1,652 | 137 | 2,113 | 154 | false | false | false | false | false | true |
3,283 | 119538_0 | package nl.hanze.hive;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.spy;
public class HiveGameLogic {
//1c. Elke speler heeft aan het begin van het spel de beschikking over één
// bijenkoningin, twee spinnen, twee kevers, drie soldatenmieren en drie
// sprinkhanen in zijn eigen kleur.
@Test
void whenGameStartThenPlayerHaveACompleteDeck() {
HiveGame hiveGame = new HiveGame();
HashMap<Hive.Tile, Integer> playersDeck = hiveGame.getPlayersDeck(Hive.Player.WHITE);
assertEquals(playersDeck.get(Hive.Tile.QUEEN_BEE), 1);
assertEquals(playersDeck.get(Hive.Tile.SPIDER), 2);
assertEquals(playersDeck.get(Hive.Tile.BEETLE), 2);
assertEquals(playersDeck.get(Hive.Tile.SOLDIER_ANT), 3);
assertEquals(playersDeck.get(Hive.Tile.GRASSHOPPER), 3);
}
// 3. Spelverloop Wit heeft de eerste beurt.
@Test
void whenGameStartThenPlayersItsWhiteturn() {
HiveGame hiveGame = new HiveGame();
Hive.Player player = hiveGame.getCurrenPlayer();
assertEquals(Hive.Player.WHITE, player);
}
// 3 Tijdens zijn beurt kan een speler een steen spelen, een steen verplaatsen of
// passen; daarna is de tegenstander aan de beurt
@Test
void whenPlayerMakesAMoveThenGiveTurntoOppositePlayer() throws Hive.IllegalMove {
HiveGame hiveGame = new HiveGame();
hiveGame.play(Hive.Tile.GRASSHOPPER, 0, 0);
assertEquals(Hive.Player.BLACK, hiveGame.getCurrenPlayer());
}
// 3c Een speler wint als alle zes velden naast de bijenkoningin van de
//tegenstander bezet zijn
@Test
void whenPlayerBlacksQueenHisBeeIsSurroundedThenPlayerWhiteWins() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertTrue(hiveGame.isWinner(Hive.Player.WHITE));
}
@Test
void whenPlayerWhiteQueenHisBeeIsSurroundedThenPlayerBlackWins() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertTrue(hiveGame.isWinner(Hive.Player.BLACK));
}
@Test
void whenQueenBeeisNotSurroundedThereIsNoWinner() {
HiveGame hiveGame = spy(HiveGame.class);
for (Hive.Player player : Hive.Player.values()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, player, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertFalse(hiveGame.isWinner(player));
}
}
// 3d. Als beide spelers tegelijk zouden winnen is het in plaats daarvan een
//gelijkspel.
@Test
void whenBothPlayersHaveASurroundedQueenBeeThenItsADraw() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0);
for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r);
}
for (Hexagon neighbour : new Hexagon(1, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.BLACK, neighbour.q, neighbour.r);
}
assertTrue(hiveGame.isDraw());
}
@Test
void whenOnlyPlayerWhiteIsSurroundedThenItsNotaDraw() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0);
for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r);
}
assertFalse(hiveGame.isDraw());
}
}
| jparengkuan/Hive_TDD | src/test/java/nl/hanze/hive/HiveGameLogic.java | 2,099 | //1c. Elke speler heeft aan het begin van het spel de beschikking over één | line_comment | nl | package nl.hanze.hive;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.spy;
public class HiveGameLogic {
//1c. Elke<SUF>
// bijenkoningin, twee spinnen, twee kevers, drie soldatenmieren en drie
// sprinkhanen in zijn eigen kleur.
@Test
void whenGameStartThenPlayerHaveACompleteDeck() {
HiveGame hiveGame = new HiveGame();
HashMap<Hive.Tile, Integer> playersDeck = hiveGame.getPlayersDeck(Hive.Player.WHITE);
assertEquals(playersDeck.get(Hive.Tile.QUEEN_BEE), 1);
assertEquals(playersDeck.get(Hive.Tile.SPIDER), 2);
assertEquals(playersDeck.get(Hive.Tile.BEETLE), 2);
assertEquals(playersDeck.get(Hive.Tile.SOLDIER_ANT), 3);
assertEquals(playersDeck.get(Hive.Tile.GRASSHOPPER), 3);
}
// 3. Spelverloop Wit heeft de eerste beurt.
@Test
void whenGameStartThenPlayersItsWhiteturn() {
HiveGame hiveGame = new HiveGame();
Hive.Player player = hiveGame.getCurrenPlayer();
assertEquals(Hive.Player.WHITE, player);
}
// 3 Tijdens zijn beurt kan een speler een steen spelen, een steen verplaatsen of
// passen; daarna is de tegenstander aan de beurt
@Test
void whenPlayerMakesAMoveThenGiveTurntoOppositePlayer() throws Hive.IllegalMove {
HiveGame hiveGame = new HiveGame();
hiveGame.play(Hive.Tile.GRASSHOPPER, 0, 0);
assertEquals(Hive.Player.BLACK, hiveGame.getCurrenPlayer());
}
// 3c Een speler wint als alle zes velden naast de bijenkoningin van de
//tegenstander bezet zijn
@Test
void whenPlayerBlacksQueenHisBeeIsSurroundedThenPlayerWhiteWins() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertTrue(hiveGame.isWinner(Hive.Player.WHITE));
}
@Test
void whenPlayerWhiteQueenHisBeeIsSurroundedThenPlayerBlackWins() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertTrue(hiveGame.isWinner(Hive.Player.BLACK));
}
@Test
void whenQueenBeeisNotSurroundedThereIsNoWinner() {
HiveGame hiveGame = spy(HiveGame.class);
for (Hive.Player player : Hive.Player.values()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, player, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertFalse(hiveGame.isWinner(player));
}
}
// 3d. Als beide spelers tegelijk zouden winnen is het in plaats daarvan een
//gelijkspel.
@Test
void whenBothPlayersHaveASurroundedQueenBeeThenItsADraw() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0);
for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r);
}
for (Hexagon neighbour : new Hexagon(1, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.BLACK, neighbour.q, neighbour.r);
}
assertTrue(hiveGame.isDraw());
}
@Test
void whenOnlyPlayerWhiteIsSurroundedThenItsNotaDraw() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0);
for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r);
}
assertFalse(hiveGame.isDraw());
}
}
| false | 1,538 | 21 | 1,785 | 24 | 1,736 | 19 | 1,785 | 24 | 2,195 | 22 | false | false | false | false | false | true |
3,003 | 18201_15 | package novi.basics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static novi.basics.main2.*;
public class Game {
private char[] board;
private int maxRounds;
private Player player1;
private Player player2;
private int drawCount;
private Player activePlayer;
public Game(Player player1, Player player2) {
// speelbord opslaan (1 - 9)
// uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven
// zie demo project code voor de andere manier met de for loop
board = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9'};
// maximale aantal rondes opslaan
maxRounds = board.length;
this.player1 = player1;
this.player2 = player2;
drawCount = 0;
activePlayer = player1;
}
public void play() {
// opslaan hoeveel keer er gelijk spel is geweest
// -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is)
// speelbord tonen
printBoard();
// starten met de beurt (maximaal 9 beurten)
for (int round = 0; round < maxRounds; round++) {
// naam van de actieve speler opslaan
String activePlayerName = activePlayer.getName();
// actieve speler vragen om een veld te kiezen (1 - 9)
System.out.println(activePlayerName + ", please choose a field");
// gekozen veld van de actieve speler opslaan
int chosenField = PLAYERINPUT.nextInt();
int chosenIndex = chosenField - 1;
// als het veld bestaat
if (chosenIndex < 9 && chosenIndex >= 0) {
//als het veld leeg is, wanneer er geen token staat
if (board[chosenIndex] != player1.getToken() && board[chosenIndex] != player2.getToken()) {
// wanneer de speler een token op het bord kan plaatsen
// de token van de actieve speler op het gekozen veld plaatsen
board[chosenIndex] = activePlayer.getToken();
//player.score += 10;
// het nieuwe speelbord tonen
printBoard();
// als het spel gewonnen is
// tonen wie er gewonnen heeft (de actieve speler)
// de actieve speler krijgt een punt
// de scores van de spelers tonen
// wanneer we in de laatste beurt zijn en niemand gewonnen heeft
// aantal keer gelijk spel ophogen
// aantal keer gelijk spel tonen
// de beurt doorgeven aan de volgende speler (van speler wisselen)
// als de actieve speler, speler 1 is:
if (activePlayer == player1) {
PLAYERPOSITION.add(chosenField);
// maak de actieve speler, speler 2
activePlayer = player2;
}
// anders
else {
// maak de actieve speler weer speler 1
activePlayer = player1;
PLAYER2POSITION.add(chosenField);
}
} //of al bezet is
else {
maxRounds++;
System.out.println("this field is not available, choose another");
}
//versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField
/*if(board[chosenIndex] != '1' + chosenIndex) {
board[chosenIndex] = activePlayerToken;
}*/
}
// als het veld niet bestaat
else {
// het mamimale aantal beurten verhogen
maxRounds++;
// foutmelding tonen aan de speler
System.out.println("the chosen field does not exist, try again");
}
String result = chekWinner();
if (result.length() > 0) {
System.out.println(result);
}
// -- terug naar het begin van de volgende beurt
}
}
public void printBoard() {
for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) {
System.out.print(board[fieldIndex] + " ");
// als we het tweede veld geprint hebben of het vijfde veld geprint hebben
// dan gaan we naar de volgende regel
if (fieldIndex == 2 || fieldIndex == 5) {
System.out.println();
}
}
System.out.println();
}
public String chekWinner() {
List topRow = Arrays.asList(1, 2, 3);
List middleRow = Arrays.asList(4, 5, 6);
List bottomrow = Arrays.asList(7, 8, 9);
List leftColom = Arrays.asList(1, 4, 7);
List middleColom = Arrays.asList(2, 5, 8);
List rightColom = Arrays.asList(9, 6, 3);
List cross1 = Arrays.asList(1, 5, 9);
List cross2 = Arrays.asList(7, 5, 3);
List<List> winning = new ArrayList<List>();
winning.add(topRow);
winning.add(middleRow);
winning.add(bottomrow);
winning.add(leftColom);
winning.add(middleColom);
winning.add(rightColom);
winning.add(cross1);
winning.add(cross2);
for (List l : winning) {
if (PLAYERPOSITION.containsAll(l)) {
player1.addscore();
return player1.getName() + " score: " + player1.getScore() + "\n" + player2.getName() + " score: " + player2.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYER2POSITION.containsAll(l)) {
player2.addscore();
return player2.getName() + " score: " + player2.getScore() + "\n" + player1.getName() + " score: " + player1.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYERPOSITION.size() + PLAYER2POSITION.size() == 9) {
drawCount++;
return "drawcount is:" + drawCount;
}
}
return " ";
}
} | hogeschoolnovi/tic-tac-toe-vurgill | src/novi/basics/Game.java | 1,791 | // het nieuwe speelbord tonen | line_comment | nl | package novi.basics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static novi.basics.main2.*;
public class Game {
private char[] board;
private int maxRounds;
private Player player1;
private Player player2;
private int drawCount;
private Player activePlayer;
public Game(Player player1, Player player2) {
// speelbord opslaan (1 - 9)
// uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven
// zie demo project code voor de andere manier met de for loop
board = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9'};
// maximale aantal rondes opslaan
maxRounds = board.length;
this.player1 = player1;
this.player2 = player2;
drawCount = 0;
activePlayer = player1;
}
public void play() {
// opslaan hoeveel keer er gelijk spel is geweest
// -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is)
// speelbord tonen
printBoard();
// starten met de beurt (maximaal 9 beurten)
for (int round = 0; round < maxRounds; round++) {
// naam van de actieve speler opslaan
String activePlayerName = activePlayer.getName();
// actieve speler vragen om een veld te kiezen (1 - 9)
System.out.println(activePlayerName + ", please choose a field");
// gekozen veld van de actieve speler opslaan
int chosenField = PLAYERINPUT.nextInt();
int chosenIndex = chosenField - 1;
// als het veld bestaat
if (chosenIndex < 9 && chosenIndex >= 0) {
//als het veld leeg is, wanneer er geen token staat
if (board[chosenIndex] != player1.getToken() && board[chosenIndex] != player2.getToken()) {
// wanneer de speler een token op het bord kan plaatsen
// de token van de actieve speler op het gekozen veld plaatsen
board[chosenIndex] = activePlayer.getToken();
//player.score += 10;
// het nieuwe<SUF>
printBoard();
// als het spel gewonnen is
// tonen wie er gewonnen heeft (de actieve speler)
// de actieve speler krijgt een punt
// de scores van de spelers tonen
// wanneer we in de laatste beurt zijn en niemand gewonnen heeft
// aantal keer gelijk spel ophogen
// aantal keer gelijk spel tonen
// de beurt doorgeven aan de volgende speler (van speler wisselen)
// als de actieve speler, speler 1 is:
if (activePlayer == player1) {
PLAYERPOSITION.add(chosenField);
// maak de actieve speler, speler 2
activePlayer = player2;
}
// anders
else {
// maak de actieve speler weer speler 1
activePlayer = player1;
PLAYER2POSITION.add(chosenField);
}
} //of al bezet is
else {
maxRounds++;
System.out.println("this field is not available, choose another");
}
//versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField
/*if(board[chosenIndex] != '1' + chosenIndex) {
board[chosenIndex] = activePlayerToken;
}*/
}
// als het veld niet bestaat
else {
// het mamimale aantal beurten verhogen
maxRounds++;
// foutmelding tonen aan de speler
System.out.println("the chosen field does not exist, try again");
}
String result = chekWinner();
if (result.length() > 0) {
System.out.println(result);
}
// -- terug naar het begin van de volgende beurt
}
}
public void printBoard() {
for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) {
System.out.print(board[fieldIndex] + " ");
// als we het tweede veld geprint hebben of het vijfde veld geprint hebben
// dan gaan we naar de volgende regel
if (fieldIndex == 2 || fieldIndex == 5) {
System.out.println();
}
}
System.out.println();
}
public String chekWinner() {
List topRow = Arrays.asList(1, 2, 3);
List middleRow = Arrays.asList(4, 5, 6);
List bottomrow = Arrays.asList(7, 8, 9);
List leftColom = Arrays.asList(1, 4, 7);
List middleColom = Arrays.asList(2, 5, 8);
List rightColom = Arrays.asList(9, 6, 3);
List cross1 = Arrays.asList(1, 5, 9);
List cross2 = Arrays.asList(7, 5, 3);
List<List> winning = new ArrayList<List>();
winning.add(topRow);
winning.add(middleRow);
winning.add(bottomrow);
winning.add(leftColom);
winning.add(middleColom);
winning.add(rightColom);
winning.add(cross1);
winning.add(cross2);
for (List l : winning) {
if (PLAYERPOSITION.containsAll(l)) {
player1.addscore();
return player1.getName() + " score: " + player1.getScore() + "\n" + player2.getName() + " score: " + player2.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYER2POSITION.containsAll(l)) {
player2.addscore();
return player2.getName() + " score: " + player2.getScore() + "\n" + player1.getName() + " score: " + player1.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYERPOSITION.size() + PLAYER2POSITION.size() == 9) {
drawCount++;
return "drawcount is:" + drawCount;
}
}
return " ";
}
} | false | 1,489 | 9 | 1,620 | 11 | 1,578 | 7 | 1,620 | 11 | 1,815 | 9 | false | false | false | false | false | true |
4,283 | 44571_0 |
public class DataController {
private static DataController instance = null;
ModelDiagram md; // mogelijk meerdere diagrammen?
private DataController() {
}
public DataController getInstance() {
if(instance == null)
instance = new DataController();
return instance;
}
public ModelDiagram getModel() {
}
}
| senkz/PaF-Relationship-helper-for-usecases-and-UML | src/DataController.java | 99 | // mogelijk meerdere diagrammen? | line_comment | nl |
public class DataController {
private static DataController instance = null;
ModelDiagram md; // mogelijk meerdere<SUF>
private DataController() {
}
public DataController getInstance() {
if(instance == null)
instance = new DataController();
return instance;
}
public ModelDiagram getModel() {
}
}
| false | 72 | 8 | 88 | 9 | 93 | 6 | 88 | 9 | 106 | 9 | false | false | false | false | false | true |
3,470 | 79029_2 | package be;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.namespace.QName;
import com.exlibris.dps.IEWebServices;
import com.exlibris.dps.IEWebServices_Service;
import com.exlibris.dps.PermanentManagerWS;
import com.exlibris.dps.PermanentManagerWS_Service;
public class CreateMetadataEntry {
private IEWebServices ieWebServices;
private PermanentManagerWS pmWebServices;
public CreateMetadataEntry(String generalFileName, String metadataFileName) {
super();
}
private String readFile(String fileName) throws IOException {
File f = new File(fileName);
byte[] bytes = new byte[(int)f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(bytes);
return new String(bytes, "UTF-8");
}
public void soapCreateMetadataEntry(String generalFileName, String metadataFileName) {
try {
Thread.sleep(3000);
ieWebServices = new IEWebServices_Service(new URL(Handle.prop.getProperty("IE_WSDL_URL")),new QName("http://dps.exlibris.com/", "IEWebServices")).getIEWebServicesPort();
pmWebServices = new PermanentManagerWS_Service(new URL(Handle.prop.getProperty("PM_WSDL_URL")),new QName("http://dps.exlibris.com/", "PermanentManagerWS")).getPermanentManagerWSPort();
String generalXml = readFile(generalFileName);
String metadataXml = readFile(metadataFileName);
if(!metadataXml.contains("<xb:digital_entity_result") || !metadataFileName.equalsIgnoreCase("general.xml"))
{
Object[] parameters = new Object[] {generalXml, "", "descriptive",
"dc", metadataXml};
// String ret = (String) pmWebServices.storeMetadata(arg0, arg1, arg2, arg3);
// extractMid(ret, metadataFileName);
}
else {
throw new WrongFormatException("Het metadatabestand bevat de verkeerde informatie");
}
} catch (IOException e) {
System.err.println(e.toString());
} catch (InterruptedException e) {
System.err.println(e.toString());
}
}
public void extractMid(String result, String metadataFileName) throws IOException
{
if (!result.contains("error")) {
String REGEX = "<mid>(.*)</mid>";
Pattern p = Pattern.compile(REGEX);
Matcher items = p.matcher(result);
if (items.find()) {
String mid = items.group(1);
// PrintStream out = new PrintStream(System.out, true, "UTF-8");
// out.println(ret);
// Schrijf het resultaat naar een bestand. Het kan gebruikt worden om te zien of er geen foutmeldingen zijn opgetreden
// Maak file
FileWriter fstream = new FileWriter(metadataFileName + "_" + mid + ".out");
BufferedWriter outPut = new BufferedWriter(fstream);
// Schrijf de content
outPut.write(readFile(metadataFileName));
//Sluit de file
outPut.close();
} else {
throw new NotFoundException("Mid niet gevonden voor: " + result);
}
}
}
}
| libis/RosettaUpdater | src/be/CreateMetadataEntry.java | 1,031 | // Schrijf het resultaat naar een bestand. Het kan gebruikt worden om te zien of er geen foutmeldingen zijn opgetreden | line_comment | nl | package be;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.namespace.QName;
import com.exlibris.dps.IEWebServices;
import com.exlibris.dps.IEWebServices_Service;
import com.exlibris.dps.PermanentManagerWS;
import com.exlibris.dps.PermanentManagerWS_Service;
public class CreateMetadataEntry {
private IEWebServices ieWebServices;
private PermanentManagerWS pmWebServices;
public CreateMetadataEntry(String generalFileName, String metadataFileName) {
super();
}
private String readFile(String fileName) throws IOException {
File f = new File(fileName);
byte[] bytes = new byte[(int)f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(bytes);
return new String(bytes, "UTF-8");
}
public void soapCreateMetadataEntry(String generalFileName, String metadataFileName) {
try {
Thread.sleep(3000);
ieWebServices = new IEWebServices_Service(new URL(Handle.prop.getProperty("IE_WSDL_URL")),new QName("http://dps.exlibris.com/", "IEWebServices")).getIEWebServicesPort();
pmWebServices = new PermanentManagerWS_Service(new URL(Handle.prop.getProperty("PM_WSDL_URL")),new QName("http://dps.exlibris.com/", "PermanentManagerWS")).getPermanentManagerWSPort();
String generalXml = readFile(generalFileName);
String metadataXml = readFile(metadataFileName);
if(!metadataXml.contains("<xb:digital_entity_result") || !metadataFileName.equalsIgnoreCase("general.xml"))
{
Object[] parameters = new Object[] {generalXml, "", "descriptive",
"dc", metadataXml};
// String ret = (String) pmWebServices.storeMetadata(arg0, arg1, arg2, arg3);
// extractMid(ret, metadataFileName);
}
else {
throw new WrongFormatException("Het metadatabestand bevat de verkeerde informatie");
}
} catch (IOException e) {
System.err.println(e.toString());
} catch (InterruptedException e) {
System.err.println(e.toString());
}
}
public void extractMid(String result, String metadataFileName) throws IOException
{
if (!result.contains("error")) {
String REGEX = "<mid>(.*)</mid>";
Pattern p = Pattern.compile(REGEX);
Matcher items = p.matcher(result);
if (items.find()) {
String mid = items.group(1);
// PrintStream out = new PrintStream(System.out, true, "UTF-8");
// out.println(ret);
// Schrijf het<SUF>
// Maak file
FileWriter fstream = new FileWriter(metadataFileName + "_" + mid + ".out");
BufferedWriter outPut = new BufferedWriter(fstream);
// Schrijf de content
outPut.write(readFile(metadataFileName));
//Sluit de file
outPut.close();
} else {
throw new NotFoundException("Mid niet gevonden voor: " + result);
}
}
}
}
| false | 720 | 32 | 850 | 34 | 917 | 27 | 850 | 34 | 1,087 | 36 | false | false | false | false | false | true |
1,021 | 121263_0 | //bestandsnaam: Oef2.java //<-- uitzonderlijke zelf importerende bibliotheek (moet dus niet in staan feitelijk)
/**
*De klasse Oef2 is een java applicatie
*
*@author Sophie Moons
*@version 1,0
*/
import java.lang.*;
public class Oef2{
/**
*Dit is een main function, hier start het programma
*@param args -> hiermee kan een array meegegeven worden via command line
*/
public static void main(String args[])
{
String[] dagen={"zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"};
int h=1;
System.out.println("Data februari 2009:\n");
while (h<29) //28 dagen toen
{
for(int i=0;i<dagen.length;i++)
{
System.out.println(dagen[i]+" "+h+" februari");
h++;
}
}
}//einde main
}//einde program | MTA-Digital-Broadcast-2/A-Moons-Sophie-De-Cock-Nicolas-Project-MHP | Sophie Moons/Labo Java/blz19/Oef2.java | 263 | //bestandsnaam: Oef2.java //<-- uitzonderlijke zelf importerende bibliotheek (moet dus niet in staan feitelijk) | line_comment | nl | //bestandsnaam: Oef2.java<SUF>
/**
*De klasse Oef2 is een java applicatie
*
*@author Sophie Moons
*@version 1,0
*/
import java.lang.*;
public class Oef2{
/**
*Dit is een main function, hier start het programma
*@param args -> hiermee kan een array meegegeven worden via command line
*/
public static void main(String args[])
{
String[] dagen={"zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"};
int h=1;
System.out.println("Data februari 2009:\n");
while (h<29) //28 dagen toen
{
for(int i=0;i<dagen.length;i++)
{
System.out.println(dagen[i]+" "+h+" februari");
h++;
}
}
}//einde main
}//einde program | false | 222 | 35 | 275 | 41 | 233 | 31 | 275 | 41 | 270 | 37 | false | false | false | false | false | true |
4,029 | 18945_0 | package codefromvideo.mockito;_x000D_
_x000D_
import java.util.List;_x000D_
_x000D_
public class Winkelmand {_x000D_
_x000D_
public boolean voegProductToeAanWinkelmand(_x000D_
Sessie sessie,_x000D_
Product nieuwProduct) {_x000D_
List<Product> producten = sessie.getProducten();_x000D_
_x000D_
if (productZitNogNietInLijst(nieuwProduct, producten)) {_x000D_
producten.add(nieuwProduct);_x000D_
sessie.setProducten(producten);_x000D_
return true;_x000D_
} else {_x000D_
// product mag maar 1 keer in winkelmand zitten_x000D_
return false;_x000D_
}_x000D_
}_x000D_
_x000D_
private boolean productZitNogNietInLijst(Product nieuwProduct, List<Product> producten) {_x000D_
return producten.stream().noneMatch(p -> p.getNaam().equals(nieuwProduct.getNaam()));_x000D_
}_x000D_
}_x000D_
| praegus/intro-unittesten | src/main/java/codefromvideo/mockito/Winkelmand.java | 234 | // product mag maar 1 keer in winkelmand zitten_x000D_ | line_comment | nl | package codefromvideo.mockito;_x000D_
_x000D_
import java.util.List;_x000D_
_x000D_
public class Winkelmand {_x000D_
_x000D_
public boolean voegProductToeAanWinkelmand(_x000D_
Sessie sessie,_x000D_
Product nieuwProduct) {_x000D_
List<Product> producten = sessie.getProducten();_x000D_
_x000D_
if (productZitNogNietInLijst(nieuwProduct, producten)) {_x000D_
producten.add(nieuwProduct);_x000D_
sessie.setProducten(producten);_x000D_
return true;_x000D_
} else {_x000D_
// product mag<SUF>
return false;_x000D_
}_x000D_
}_x000D_
_x000D_
private boolean productZitNogNietInLijst(Product nieuwProduct, List<Product> producten) {_x000D_
return producten.stream().noneMatch(p -> p.getNaam().equals(nieuwProduct.getNaam()));_x000D_
}_x000D_
}_x000D_
| false | 341 | 19 | 372 | 24 | 361 | 18 | 372 | 24 | 397 | 22 | false | false | false | false | false | true |
4,597 | 10051_3 | /*
* Copyright 2007 Pieter De Rycke
*
* This file is part of JMTP.
*
* JTMP 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 3 of
* the License, or any later version.
*
* JMTP 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 LesserGeneral Public
* License along with JMTP. If not, see <http://www.gnu.org/licenses/>.
*/
package jmtp;
import java.math.BigInteger;
import java.util.Date;
import be.derycke.pieter.com.COMException;
import be.derycke.pieter.com.Guid;
import be.derycke.pieter.com.OleDate;
/**
*
* @author Pieter De Rycke
*/
class PortableDeviceObjectImplWin32 implements PortableDeviceObject {
protected PortableDeviceContentImplWin32 content;
protected PortableDevicePropertiesImplWin32 properties;
protected PortableDeviceKeyCollectionImplWin32 keyCollection;
protected PortableDeviceValuesImplWin32 values;
protected String objectID;
PortableDeviceObjectImplWin32(String objectID,
PortableDeviceContentImplWin32 content,
PortableDevicePropertiesImplWin32 properties) {
this.objectID = objectID;
this.content = content;
this.properties = properties;
try {
this.keyCollection = new PortableDeviceKeyCollectionImplWin32();
this.values = new PortableDeviceValuesImplWin32();
}
catch (COMException e) {
e.printStackTrace();
}
}
/**
* Een String property opvragen.
* @param key
* @return
*/
protected String retrieveStringValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getStringValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return null;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -> de string werd niet ingesteld
}
}
}
protected void changeStringValue(PropertyKey key, String value) {
try {
values.clear();
values.setStringValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected long retrieveLongValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getUnsignedIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return -1;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return -1;
}
}
}
protected void changeLongValue(PropertyKey key, long value) {
try {
values.clear();
values.setUnsignedIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected Date retrieveDateValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return new OleDate(properties.getValues(objectID, keyCollection).getFloatValue(key));
}
catch(COMException e) {
return null;
}
}
protected void changeDateValue(PropertyKey key, Date value) {
try {
values.clear();
values.setFloateValue(key, (float)new OleDate(value).toDouble());
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {}
}
protected boolean retrieveBooleanValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getBoolValue(key);
}
catch(COMException e) {
return false;
}
}
protected Guid retrieveGuidValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getGuidValue(key);
}
catch(COMException e) {
return null;
}
}
protected BigInteger retrieveBigIntegerValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getUnsignedLargeIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return new BigInteger("-1");
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -> de string werd niet ingesteld
}
}
}
protected void changeBigIntegerValue(PropertyKey key, BigInteger value) {
try {
values.clear();
values.setUnsignedLargeIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
public String getID() {
return objectID;
}
public String getName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_NAME);
}
public String getOriginalFileName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME);
}
public boolean canDelete() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_CAN_DELETE);
}
public boolean isHidden() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISHIDDEN);
}
public boolean isSystemObject() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISSYSTEM);
}
public Date getDateModified() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_MODIFIED);
}
public Date getDateCreated() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_CREATED);
}
public Date getDateAuthored() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_AUTHORED);
}
public PortableDeviceObject getParent() {
String parentID = retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID);
if(parentID != null)
return WPDImplWin32.convertToPortableDeviceObject(parentID, content, properties);
else
return null;
}
public BigInteger getSize() {
return retrieveBigIntegerValue(Win32WPDDefines.WPD_OBJECT_SIZE);
}
public String getPersistentUniqueIdentifier() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PERSISTENT_UNIQUE_ID);
}
public boolean isDrmProtected() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_IS_DRM_PROTECTED);
}
public String getSyncID() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID);
}
//TODO slechts tijdelijk de guids geven -> enum aanmaken
public Guid getFormat() {
return retrieveGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT);
}
public void setSyncID(String value) {
changeStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID, value);
}
public void delete() {
try {
PortableDevicePropVariantCollectionImplWin32 collection =
new PortableDevicePropVariantCollectionImplWin32();
collection.add(new PropVariant(this.objectID));
this.content.delete(Win32WPDDefines.PORTABLE_DEVICE_DELETE_NO_RECURSION, collection);
}
catch(COMException e) {
//TODO -> misschien een exception gooien?
e.printStackTrace();
}
}
@Override
public String toString() {
return objectID;
}
public boolean equals(Object o) {
if(o instanceof PortableDeviceObjectImplWin32) {
PortableDeviceObjectImplWin32 object = (PortableDeviceObjectImplWin32)o;
return object.objectID.equals(this.objectID);
}
else
return false;
}
}
| ultrah/jMTPe | source/java/src/jmtp/PortableDeviceObjectImplWin32.java | 2,931 | //comexception -> de string werd niet ingesteld | line_comment | nl | /*
* Copyright 2007 Pieter De Rycke
*
* This file is part of JMTP.
*
* JTMP 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 3 of
* the License, or any later version.
*
* JMTP 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 LesserGeneral Public
* License along with JMTP. If not, see <http://www.gnu.org/licenses/>.
*/
package jmtp;
import java.math.BigInteger;
import java.util.Date;
import be.derycke.pieter.com.COMException;
import be.derycke.pieter.com.Guid;
import be.derycke.pieter.com.OleDate;
/**
*
* @author Pieter De Rycke
*/
class PortableDeviceObjectImplWin32 implements PortableDeviceObject {
protected PortableDeviceContentImplWin32 content;
protected PortableDevicePropertiesImplWin32 properties;
protected PortableDeviceKeyCollectionImplWin32 keyCollection;
protected PortableDeviceValuesImplWin32 values;
protected String objectID;
PortableDeviceObjectImplWin32(String objectID,
PortableDeviceContentImplWin32 content,
PortableDevicePropertiesImplWin32 properties) {
this.objectID = objectID;
this.content = content;
this.properties = properties;
try {
this.keyCollection = new PortableDeviceKeyCollectionImplWin32();
this.values = new PortableDeviceValuesImplWin32();
}
catch (COMException e) {
e.printStackTrace();
}
}
/**
* Een String property opvragen.
* @param key
* @return
*/
protected String retrieveStringValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getStringValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return null;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -><SUF>
}
}
}
protected void changeStringValue(PropertyKey key, String value) {
try {
values.clear();
values.setStringValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected long retrieveLongValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getUnsignedIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return -1;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return -1;
}
}
}
protected void changeLongValue(PropertyKey key, long value) {
try {
values.clear();
values.setUnsignedIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected Date retrieveDateValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return new OleDate(properties.getValues(objectID, keyCollection).getFloatValue(key));
}
catch(COMException e) {
return null;
}
}
protected void changeDateValue(PropertyKey key, Date value) {
try {
values.clear();
values.setFloateValue(key, (float)new OleDate(value).toDouble());
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {}
}
protected boolean retrieveBooleanValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getBoolValue(key);
}
catch(COMException e) {
return false;
}
}
protected Guid retrieveGuidValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getGuidValue(key);
}
catch(COMException e) {
return null;
}
}
protected BigInteger retrieveBigIntegerValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getUnsignedLargeIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return new BigInteger("-1");
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -> de string werd niet ingesteld
}
}
}
protected void changeBigIntegerValue(PropertyKey key, BigInteger value) {
try {
values.clear();
values.setUnsignedLargeIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
public String getID() {
return objectID;
}
public String getName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_NAME);
}
public String getOriginalFileName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME);
}
public boolean canDelete() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_CAN_DELETE);
}
public boolean isHidden() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISHIDDEN);
}
public boolean isSystemObject() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISSYSTEM);
}
public Date getDateModified() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_MODIFIED);
}
public Date getDateCreated() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_CREATED);
}
public Date getDateAuthored() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_AUTHORED);
}
public PortableDeviceObject getParent() {
String parentID = retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID);
if(parentID != null)
return WPDImplWin32.convertToPortableDeviceObject(parentID, content, properties);
else
return null;
}
public BigInteger getSize() {
return retrieveBigIntegerValue(Win32WPDDefines.WPD_OBJECT_SIZE);
}
public String getPersistentUniqueIdentifier() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PERSISTENT_UNIQUE_ID);
}
public boolean isDrmProtected() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_IS_DRM_PROTECTED);
}
public String getSyncID() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID);
}
//TODO slechts tijdelijk de guids geven -> enum aanmaken
public Guid getFormat() {
return retrieveGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT);
}
public void setSyncID(String value) {
changeStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID, value);
}
public void delete() {
try {
PortableDevicePropVariantCollectionImplWin32 collection =
new PortableDevicePropVariantCollectionImplWin32();
collection.add(new PropVariant(this.objectID));
this.content.delete(Win32WPDDefines.PORTABLE_DEVICE_DELETE_NO_RECURSION, collection);
}
catch(COMException e) {
//TODO -> misschien een exception gooien?
e.printStackTrace();
}
}
@Override
public String toString() {
return objectID;
}
public boolean equals(Object o) {
if(o instanceof PortableDeviceObjectImplWin32) {
PortableDeviceObjectImplWin32 object = (PortableDeviceObjectImplWin32)o;
return object.objectID.equals(this.objectID);
}
else
return false;
}
}
| false | 2,127 | 10 | 2,491 | 12 | 2,732 | 11 | 2,491 | 12 | 3,051 | 11 | false | false | false | false | false | true |
1,380 | 70587_16 | package src;
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;
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-JustDylan23 | src/TileEngine.java | 2,422 | // Toevoegen aan onze lokale array. Makkelijk om de tile op te halen | line_comment | nl | package src;
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;
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<SUF>
// 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;
}
}
| false | 1,977 | 19 | 2,082 | 24 | 2,265 | 17 | 2,096 | 24 | 2,484 | 22 | false | false | false | false | false | true |
4,134 | 74020_0 | package Controller;
import Firebase.FirebaseActionObserver;
import Firebase.FirebaseGameObserver;
import Firebase.FirebaseGameService;
import com.google.cloud.firestore.DocumentChange;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import javafx.application.Platform;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FirebaseGameController implements FirebaseActionObserver {
private GameController gameCon;
private FirebaseGameService service;
private Map<String, FirebaseGameObserver> observers = new HashMap<>();
public FirebaseGameController(String gameName, GameController gameCon) {
this.gameCon = gameCon;
service = new FirebaseGameService(gameName);
turnActionListener(this);
}
private void placeAction(Map<String, Object> map) {
service.placeAction(getEventNumber(), map);
}
//Met 3 is het grootste aantal
private String getEventNumber(){
String id = String.valueOf(service.getLastestEventNumber());
StringBuilder str = new StringBuilder(id);
while(str.length() < 3) str.insert(0, "0");
return str.toString();
}
public void nextPhaseAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "phase");
map.put("id", "nextPhase");
map.put("action", "nextPhase");
placeAction(map);
}
public void buyCombiAction(int number) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "buy");
map.put("item", number);
placeAction(map);
}
public void addCombiAction(String race, String power) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "add");
map.put("race", race);
map.put("power", power);
placeAction(map);
}
public void attackAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "attack");
map.put("areaId", areaId);
placeAction(map);
}
public void addsFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "add");
map.put("areaId", areaId);
placeAction(map);
}
public void removeFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "remove");
map.put("areaId", areaId);
placeAction(map);
}
public void leavesFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "leaves");
map.put("areaId", areaId);
placeAction(map);
}
public void declineAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "decline");
map.put("action", "decline");
placeAction(map);
}
private void turnActionListener(final FirebaseActionObserver controller) {
service.actionListener(controller);
}
public void register(String id, FirebaseGameObserver observer) {
observers.put(id, observer);
}
@Override
public void update(QuerySnapshot qs) {
List<DocumentChange> updateList = qs.getDocumentChanges();
for (DocumentChange documentChange : updateList) {
DocumentSnapshot doc = documentChange.getDocument();
System.out.println("Id: " + doc.getId());
System.out.println(doc.getData());
Platform.runLater(() -> observers.get(doc.getString("division")).update(doc));
}
}
}
| realDragonium/SmallWorld3D | src/main/java/Controller/FirebaseGameController.java | 1,106 | //Met 3 is het grootste aantal | line_comment | nl | package Controller;
import Firebase.FirebaseActionObserver;
import Firebase.FirebaseGameObserver;
import Firebase.FirebaseGameService;
import com.google.cloud.firestore.DocumentChange;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import javafx.application.Platform;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FirebaseGameController implements FirebaseActionObserver {
private GameController gameCon;
private FirebaseGameService service;
private Map<String, FirebaseGameObserver> observers = new HashMap<>();
public FirebaseGameController(String gameName, GameController gameCon) {
this.gameCon = gameCon;
service = new FirebaseGameService(gameName);
turnActionListener(this);
}
private void placeAction(Map<String, Object> map) {
service.placeAction(getEventNumber(), map);
}
//Met 3<SUF>
private String getEventNumber(){
String id = String.valueOf(service.getLastestEventNumber());
StringBuilder str = new StringBuilder(id);
while(str.length() < 3) str.insert(0, "0");
return str.toString();
}
public void nextPhaseAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "phase");
map.put("id", "nextPhase");
map.put("action", "nextPhase");
placeAction(map);
}
public void buyCombiAction(int number) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "buy");
map.put("item", number);
placeAction(map);
}
public void addCombiAction(String race, String power) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "add");
map.put("race", race);
map.put("power", power);
placeAction(map);
}
public void attackAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "attack");
map.put("areaId", areaId);
placeAction(map);
}
public void addsFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "add");
map.put("areaId", areaId);
placeAction(map);
}
public void removeFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "remove");
map.put("areaId", areaId);
placeAction(map);
}
public void leavesFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "leaves");
map.put("areaId", areaId);
placeAction(map);
}
public void declineAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "decline");
map.put("action", "decline");
placeAction(map);
}
private void turnActionListener(final FirebaseActionObserver controller) {
service.actionListener(controller);
}
public void register(String id, FirebaseGameObserver observer) {
observers.put(id, observer);
}
@Override
public void update(QuerySnapshot qs) {
List<DocumentChange> updateList = qs.getDocumentChanges();
for (DocumentChange documentChange : updateList) {
DocumentSnapshot doc = documentChange.getDocument();
System.out.println("Id: " + doc.getId());
System.out.println(doc.getData());
Platform.runLater(() -> observers.get(doc.getString("division")).update(doc));
}
}
}
| false | 824 | 9 | 961 | 11 | 1,027 | 8 | 961 | 11 | 1,088 | 9 | false | false | false | false | false | true |
1,073 | 8369_0 | package be.jpendel.application;
import be.jpendel.domain.person.Person;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/* TODO : mark: PersonMapper en PersonDTO moeten volgens mij in de domain layer
*/
class PersonMapper {
private PersonMapper() {
}
static List<PersonDTO> map(Collection<Person> persons) {
return persons.stream().map(PersonMapper::map).collect(Collectors.toList());
}
static PersonDTO map(Person person) {
return PersonDTO.newBuilder()
.withUuid(person.getId())
.withFirstName(person.getFirstName())
.withLastName(person.getLastName())
.withBirthDate(person.getBirthDate())
.withPhone(person.getPhone())
.build();
}
}
| MarkDechamps/jpendel | application/src/main/java/be/jpendel/application/PersonMapper.java | 233 | /* TODO : mark: PersonMapper en PersonDTO moeten volgens mij in de domain layer
*/ | block_comment | nl | package be.jpendel.application;
import be.jpendel.domain.person.Person;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/* TODO : mark:<SUF>*/
class PersonMapper {
private PersonMapper() {
}
static List<PersonDTO> map(Collection<Person> persons) {
return persons.stream().map(PersonMapper::map).collect(Collectors.toList());
}
static PersonDTO map(Person person) {
return PersonDTO.newBuilder()
.withUuid(person.getId())
.withFirstName(person.getFirstName())
.withLastName(person.getLastName())
.withBirthDate(person.getBirthDate())
.withPhone(person.getPhone())
.build();
}
}
| false | 157 | 20 | 202 | 22 | 205 | 19 | 202 | 22 | 232 | 22 | false | false | false | false | false | true |
2,942 | 29048_15 | package pca;
import cern.colt.matrix.DoubleFactory2D;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.impl.DenseDoubleMatrix1D;
import cern.colt.matrix.linalg.Algebra;
import cern.jet.math.Functions;
import util.Log;
import util.Log.LogType;
import util.TimeCounter;
public class PCA {
protected int numComponents; /* Dimension of reduced data. */
protected DoubleMatrix2D data = null; /* Original data */
private DoubleMatrix2D reducedData = null; /* Data after PCA */
protected DoubleMatrix2D basis = null; /* Transformation matrix between sample and feature space. */
protected DoubleMatrix1D eigenValues = null; /* Eigen Values used for standard deviation */
private DoubleMatrix1D mean = null;
private boolean meanDirty = true;
private boolean dataLock = false; /* If the data already has been centered. */
public PCA() {
}
public PCA(int numComponents,
DoubleMatrix2D reducedData,
DoubleMatrix1D eigenValues,
DoubleMatrix1D mean) {
this.numComponents = numComponents;
this.reducedData = reducedData;
this.eigenValues = eigenValues;
this.mean = mean;
this.meanDirty = false;
this.dataLock = true;
}
/** Create a new PCA with the provided data, with one column = one sample. */
public PCA(DoubleMatrix2D data) {
this.data = data;
}
/** Add a new sample in the PCA. The first sample added decide the sample's size.
* If further add is done with a different size, an exception is throw.
*/
public void addSample(DoubleMatrix1D sample) {
if(dataLock)
throw new RuntimeException("Data already locked.");
if(data == null) {
/* Sub-optimal, involve 2 copies. */
data = DoubleFactory2D.dense.make(sample.toArray(), sample.size());
}
else {
if(data.rows() != sample.size())
throw new RuntimeException("Unexpected sample length.");
/* Sub-optimal, involve 3 copies. */
DoubleMatrix2D sample2d = DoubleFactory2D.dense.make(sample.toArray(), sample.size());
data = DoubleFactory2D.dense.appendColumns(data, sample2d).copy();
}
}
/** Compute the PCA and reduce the data. */
public void computePCA(int numComponents) {
TimeCounter t = new TimeCounter("PCA: computation of basis and reduced data.");
this.numComponents = numComponents;
Log.info(LogType.MODEL, "PCA computation with " + numComponents + " dimensions.");
centerData();
doComputeBasis();
/* Compute reduced data. */
reducedData = new Algebra().mult(data, basis.viewDice());
t.stop();
}
public boolean computationDone() {
return dataLock;
}
/** This method should compute the basis matrix and the eigenValue matrix. */
protected void doComputeBasis() {
/* This class need to be subclassed to implement a PCA method. */
assert(false);
}
/** @return the basis vector. */
public DoubleMatrix2D getBasis() {
assert basis != null;
return basis;
}
/** @return a vector of the feature space basis. */
public DoubleMatrix1D getBasisVector(int index) {
assert basis != null;
return basis.viewColumn(index);
}
/** @return one eigen value. */
public double getEigenValue(int index) {
ensureReducedData();
return eigenValues.get(index);
}
/** @return the number of component of the feature space. */
public int getNumComponents() {
ensureReducedData();
return numComponents;
}
/** @return the size of one sample. */
public int getSampleSize() {
if(data == null)
return 0;
return data.rows();
}
/** @return how many sample are stored. */
public int getSampleNumber() {
if(data == null)
return 0;
return data.columns();
}
/** @return one original sample. */
public DoubleMatrix1D getSample(int index) {
return data.viewColumn(index);
}
/** @return one of the reduced model. */
public DoubleMatrix1D getFeatureSample(int index) {
return reducedData.viewColumn(index).copy().assign(mean, Functions.plus);
}
/** @return a sample from the original data expressed in the feature space.
* @param index the index of the sample in the original data.
*/
public DoubleMatrix1D sampleToFeatureSpace(int index) {
return sampleToFeatureSpaceNoMean(data.viewColumn(index));
}
/** @return an arbitrary sample expressed in the feature space.
* @param sample the sample data. Length should be the same as the original data.
*/
public DoubleMatrix1D sampleToFeatureSpace(DoubleMatrix1D sample) {
ensureMean();
return sampleToFeatureSpaceNoMean(sample.copy().assign(mean, Functions.minus));
}
/** Internal sampleToFeatureSpace, for data that are already mean subtracted.
* @param sample the sample to convert.
*/
private DoubleMatrix1D sampleToFeatureSpaceNoMean(DoubleMatrix1D sample) {
ensureReducedData();
if(sample.size() != data.rows())
throw new IllegalArgumentException("Unexpected sample length.");
return new Algebra().mult(basis, sample);
}
/** @return an arbitrary sample expressed in the sample space.
* @param sample the sample data. Length should be the same as the feature space dimension.
*/
public DoubleMatrix1D sampleToSampleSpace(DoubleMatrix1D sample) {
if(sample.size() != numComponents)
throw new IllegalArgumentException("Unexpected sample length.");
ensureMean();
DoubleMatrix1D s_copy = sample.copy();
s_copy.assign(eigenValues, Functions.mult);
DoubleMatrix1D result = new Algebra().mult(reducedData, s_copy);
return result.assign(mean, Functions.plus);
}
/** Compute the error resulting for a projection to feature space and back for a sample.
* This could be used to test the membership of a sample to the feature space.
*/
public double errorMembership(DoubleMatrix1D sample) {
DoubleMatrix1D feat = sampleToFeatureSpace(sample);
DoubleMatrix1D back = sampleToSampleSpace(feat);
sample.assign(back, Functions.minus);
sample.assign(Functions.square);
return Math.sqrt(sample.zSum());
}
/** @return the mean sample. */
public DoubleMatrix1D getMean() {
ensureMean();
return mean;
}
@Override
public String toString() {
return "PCA: \n" + basis;
}
/** Update the mean sample of the original data. */
private void computeMean() {
Log.debug(LogType.MODEL, "PCA: compute mean sample.");
if(mean == null)
mean = new DenseDoubleMatrix1D(data.rows());
else
mean.assign(0.0);
for(int i = 0; i < data.rows(); i++) {
mean.set(i, data.viewRow(i).zSum() / data.columns());
}
meanDirty = false;
}
/** Subtract the mean from all samples. */
private void centerData() {
Log.debug(LogType.MODEL, "PCA: lock data.");
this.dataLock = true;
ensureMean();
for(int i = 0; i < data.columns(); i++)
data.viewColumn(i).assign(mean, Functions.minus);
}
/** If no explicit computeBasis call have been made with a numComponents,
* we compute the PCA with the same dimension as the original data. */
private void ensureReducedData() {
if(reducedData == null)
computePCA(data.rows());
}
/** Ensure that the mean is properly computed. */
private void ensureMean() {
if(meanDirty)
computeMean();
}
}
| hillday/3DMM | src/pca/PCA.java | 2,160 | /** @return one eigen value. */ | block_comment | nl | package pca;
import cern.colt.matrix.DoubleFactory2D;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.impl.DenseDoubleMatrix1D;
import cern.colt.matrix.linalg.Algebra;
import cern.jet.math.Functions;
import util.Log;
import util.Log.LogType;
import util.TimeCounter;
public class PCA {
protected int numComponents; /* Dimension of reduced data. */
protected DoubleMatrix2D data = null; /* Original data */
private DoubleMatrix2D reducedData = null; /* Data after PCA */
protected DoubleMatrix2D basis = null; /* Transformation matrix between sample and feature space. */
protected DoubleMatrix1D eigenValues = null; /* Eigen Values used for standard deviation */
private DoubleMatrix1D mean = null;
private boolean meanDirty = true;
private boolean dataLock = false; /* If the data already has been centered. */
public PCA() {
}
public PCA(int numComponents,
DoubleMatrix2D reducedData,
DoubleMatrix1D eigenValues,
DoubleMatrix1D mean) {
this.numComponents = numComponents;
this.reducedData = reducedData;
this.eigenValues = eigenValues;
this.mean = mean;
this.meanDirty = false;
this.dataLock = true;
}
/** Create a new PCA with the provided data, with one column = one sample. */
public PCA(DoubleMatrix2D data) {
this.data = data;
}
/** Add a new sample in the PCA. The first sample added decide the sample's size.
* If further add is done with a different size, an exception is throw.
*/
public void addSample(DoubleMatrix1D sample) {
if(dataLock)
throw new RuntimeException("Data already locked.");
if(data == null) {
/* Sub-optimal, involve 2 copies. */
data = DoubleFactory2D.dense.make(sample.toArray(), sample.size());
}
else {
if(data.rows() != sample.size())
throw new RuntimeException("Unexpected sample length.");
/* Sub-optimal, involve 3 copies. */
DoubleMatrix2D sample2d = DoubleFactory2D.dense.make(sample.toArray(), sample.size());
data = DoubleFactory2D.dense.appendColumns(data, sample2d).copy();
}
}
/** Compute the PCA and reduce the data. */
public void computePCA(int numComponents) {
TimeCounter t = new TimeCounter("PCA: computation of basis and reduced data.");
this.numComponents = numComponents;
Log.info(LogType.MODEL, "PCA computation with " + numComponents + " dimensions.");
centerData();
doComputeBasis();
/* Compute reduced data. */
reducedData = new Algebra().mult(data, basis.viewDice());
t.stop();
}
public boolean computationDone() {
return dataLock;
}
/** This method should compute the basis matrix and the eigenValue matrix. */
protected void doComputeBasis() {
/* This class need to be subclassed to implement a PCA method. */
assert(false);
}
/** @return the basis vector. */
public DoubleMatrix2D getBasis() {
assert basis != null;
return basis;
}
/** @return a vector of the feature space basis. */
public DoubleMatrix1D getBasisVector(int index) {
assert basis != null;
return basis.viewColumn(index);
}
/** @return one eigen<SUF>*/
public double getEigenValue(int index) {
ensureReducedData();
return eigenValues.get(index);
}
/** @return the number of component of the feature space. */
public int getNumComponents() {
ensureReducedData();
return numComponents;
}
/** @return the size of one sample. */
public int getSampleSize() {
if(data == null)
return 0;
return data.rows();
}
/** @return how many sample are stored. */
public int getSampleNumber() {
if(data == null)
return 0;
return data.columns();
}
/** @return one original sample. */
public DoubleMatrix1D getSample(int index) {
return data.viewColumn(index);
}
/** @return one of the reduced model. */
public DoubleMatrix1D getFeatureSample(int index) {
return reducedData.viewColumn(index).copy().assign(mean, Functions.plus);
}
/** @return a sample from the original data expressed in the feature space.
* @param index the index of the sample in the original data.
*/
public DoubleMatrix1D sampleToFeatureSpace(int index) {
return sampleToFeatureSpaceNoMean(data.viewColumn(index));
}
/** @return an arbitrary sample expressed in the feature space.
* @param sample the sample data. Length should be the same as the original data.
*/
public DoubleMatrix1D sampleToFeatureSpace(DoubleMatrix1D sample) {
ensureMean();
return sampleToFeatureSpaceNoMean(sample.copy().assign(mean, Functions.minus));
}
/** Internal sampleToFeatureSpace, for data that are already mean subtracted.
* @param sample the sample to convert.
*/
private DoubleMatrix1D sampleToFeatureSpaceNoMean(DoubleMatrix1D sample) {
ensureReducedData();
if(sample.size() != data.rows())
throw new IllegalArgumentException("Unexpected sample length.");
return new Algebra().mult(basis, sample);
}
/** @return an arbitrary sample expressed in the sample space.
* @param sample the sample data. Length should be the same as the feature space dimension.
*/
public DoubleMatrix1D sampleToSampleSpace(DoubleMatrix1D sample) {
if(sample.size() != numComponents)
throw new IllegalArgumentException("Unexpected sample length.");
ensureMean();
DoubleMatrix1D s_copy = sample.copy();
s_copy.assign(eigenValues, Functions.mult);
DoubleMatrix1D result = new Algebra().mult(reducedData, s_copy);
return result.assign(mean, Functions.plus);
}
/** Compute the error resulting for a projection to feature space and back for a sample.
* This could be used to test the membership of a sample to the feature space.
*/
public double errorMembership(DoubleMatrix1D sample) {
DoubleMatrix1D feat = sampleToFeatureSpace(sample);
DoubleMatrix1D back = sampleToSampleSpace(feat);
sample.assign(back, Functions.minus);
sample.assign(Functions.square);
return Math.sqrt(sample.zSum());
}
/** @return the mean sample. */
public DoubleMatrix1D getMean() {
ensureMean();
return mean;
}
@Override
public String toString() {
return "PCA: \n" + basis;
}
/** Update the mean sample of the original data. */
private void computeMean() {
Log.debug(LogType.MODEL, "PCA: compute mean sample.");
if(mean == null)
mean = new DenseDoubleMatrix1D(data.rows());
else
mean.assign(0.0);
for(int i = 0; i < data.rows(); i++) {
mean.set(i, data.viewRow(i).zSum() / data.columns());
}
meanDirty = false;
}
/** Subtract the mean from all samples. */
private void centerData() {
Log.debug(LogType.MODEL, "PCA: lock data.");
this.dataLock = true;
ensureMean();
for(int i = 0; i < data.columns(); i++)
data.viewColumn(i).assign(mean, Functions.minus);
}
/** If no explicit computeBasis call have been made with a numComponents,
* we compute the PCA with the same dimension as the original data. */
private void ensureReducedData() {
if(reducedData == null)
computePCA(data.rows());
}
/** Ensure that the mean is properly computed. */
private void ensureMean() {
if(meanDirty)
computeMean();
}
}
| false | 1,718 | 8 | 2,048 | 8 | 2,043 | 8 | 2,048 | 8 | 2,326 | 8 | false | false | false | false | false | true |
394 | 175634_1 | package gameEngine.ramses.events;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
public class EventQueueRoom {
//static class die een add en resolved event functie heeft.
//als een event word geadd word er bij alle eventHandlers gekeken of het hun event is. Zo ja activeer het.
//private static ArrayList<Event> _allEvents = new ArrayList<Event>();
public static void addQueueItem(Event event,EventDispatcher dispatcher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
ArrayList<ListenerItem> listListeners = dispatcher.getAllListeners();
EventDispatcher currentParent;
event.dispatcher = dispatcher;
event.caster = dispatcher;
callMethodsInListOfEvent(listListeners,event);
if(event.isBubbles()){
currentParent = dispatcher.getParentListener();
while(currentParent != null){
event.caster = currentParent;
listListeners = currentParent.getAllListeners();
callMethodsInListOfEvent(listListeners,event);
currentParent = currentParent.getParentListener();
}
}
}
private static void callMethodsInListOfEvent(ArrayList<ListenerItem> listToLoop, Event event) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
ListenerItem currentItem;
ArrayList<ListenerItem> list = listToLoop;
if(list.size() > 0){
for(int i = list.size() - 1; i >= 0 ; i--){
currentItem = list.get(i);
if(currentItem.getType() == event.getType()){
currentItem.getMethodData().getMethod().invoke(currentItem.getMethodData().getMethodHolder(), event);
}
}
}
}
}
| Darkfafi/JavaFrameworkRDP | src/gameEngine/ramses/events/EventQueueRoom.java | 475 | //als een event word geadd word er bij alle eventHandlers gekeken of het hun event is. Zo ja activeer het. | line_comment | nl | package gameEngine.ramses.events;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
public class EventQueueRoom {
//static class die een add en resolved event functie heeft.
//als een<SUF>
//private static ArrayList<Event> _allEvents = new ArrayList<Event>();
public static void addQueueItem(Event event,EventDispatcher dispatcher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
ArrayList<ListenerItem> listListeners = dispatcher.getAllListeners();
EventDispatcher currentParent;
event.dispatcher = dispatcher;
event.caster = dispatcher;
callMethodsInListOfEvent(listListeners,event);
if(event.isBubbles()){
currentParent = dispatcher.getParentListener();
while(currentParent != null){
event.caster = currentParent;
listListeners = currentParent.getAllListeners();
callMethodsInListOfEvent(listListeners,event);
currentParent = currentParent.getParentListener();
}
}
}
private static void callMethodsInListOfEvent(ArrayList<ListenerItem> listToLoop, Event event) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
ListenerItem currentItem;
ArrayList<ListenerItem> list = listToLoop;
if(list.size() > 0){
for(int i = list.size() - 1; i >= 0 ; i--){
currentItem = list.get(i);
if(currentItem.getType() == event.getType()){
currentItem.getMethodData().getMethod().invoke(currentItem.getMethodData().getMethodHolder(), event);
}
}
}
}
}
| false | 339 | 28 | 405 | 30 | 405 | 28 | 405 | 30 | 512 | 29 | false | false | false | false | false | true |
958 | 97801_0 | package gui.screens;
import domein.DomeinController;
import gui.company.CompanyCardComponent;
import gui.components.CustomMenu;
import gui.components.LanguageBundle;
import io.github.palexdev.materialfx.controls.MFXButton;
import io.github.palexdev.materialfx.controls.MFXCheckbox;
import io.github.palexdev.materialfx.controls.MFXScrollPane;
import io.github.palexdev.materialfx.controls.MFXSlider;
import javafx.geometry.Pos;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import resources.ResourceController;
import java.util.Locale;
public class SettingScreen extends MFXScrollPane {
private DomeinController dc;
private ResourceController rs;
private BorderPane root;
private CustomMenu menu;
private VBox pane = new VBox();
private ComboBox<String> languageComboBox;
private static Label title;
private static MFXCheckbox checkbox;
private static Label soundLabel;
private static Label languageLabel;
public SettingScreen(BorderPane root, CustomMenu menu, DomeinController dc, ResourceController rs) {
this.dc = dc;
pane.setAlignment(Pos.TOP_CENTER);
pane.setSpacing(200);
this.rs = rs;
this.root = root;
this.menu = menu;
this.setContent(pane);
this.setFitToHeight(true);
this.setFitToWidth(true);
setup();
}
public void setup() {
title = new Label(LanguageBundle.getString("SettingScreen_setting"));
title.getStyleClass().add("title");
soundLabel = new Label(LanguageBundle.getString("SettingScreen_sound"));
VBox layoutBox = new VBox();
MFXSlider slider = new MFXSlider();
slider.setMin(0);
slider.setMax(100);
slider.setValue(rs.getCurrentVolume()*100);
slider.setOnMouseReleased(e -> {
System.out.println(slider.getValue());
rs.changeVolume(slider.getValue());
});
languageLabel = new Label("Language");
languageComboBox = new ComboBox<>();
HBox.setHgrow(languageComboBox, Priority.ALWAYS);
languageComboBox.getItems().addAll("en", "nl");
languageComboBox.setValue("en");
// voeg een listener toe aan de ComboBox om de taal te wijzigen
languageComboBox.setOnAction(e -> switchLanguage());
layoutBox.setAlignment(Pos.CENTER);
checkbox = new MFXCheckbox(LanguageBundle.getString("SettingScreen_mute"));
checkbox.setSelected(rs.isMute());
checkbox.setOnAction(e -> rs.handleMute(checkbox.isSelected()));
layoutBox.setSpacing(20);
layoutBox.getChildren().addAll(soundLabel, slider, checkbox, languageLabel, languageComboBox);
pane.getChildren().addAll(title, layoutBox);
}
private void switchLanguage() {
Locale selectedLocale;
String selectedLanguage = languageComboBox.getValue();
if (selectedLanguage.equals("en")) {
selectedLocale = new Locale("en");
} else {
selectedLocale = new Locale("nl");
}
// Wijzig de taal in de hele applicatie
LanguageBundle.setLocale(selectedLocale);
//update taal van pagina waarop je staat
updateText();
/*LoginScreen.updateText();
MainScreen.updateText();
CompanyCardComponent.updateText();
NotificationScreen.updateText();
OrderScreen.updateText();
TransportDienstScreen.updateText();
RegisterScreen.updateText();
MyProductsScreen.updateText();*/
}
public static void updateText() {
title.setText(LanguageBundle.getString("SettingScreen_setting"));
checkbox.setText(LanguageBundle.getString("SettingScreen_mute"));
soundLabel.setText(LanguageBundle.getString("SettingScreen_sound"));
}
}
| LaurensDM/Webshop-desktop | src/main/java/gui/screens/SettingScreen.java | 1,144 | // voeg een listener toe aan de ComboBox om de taal te wijzigen | line_comment | nl | package gui.screens;
import domein.DomeinController;
import gui.company.CompanyCardComponent;
import gui.components.CustomMenu;
import gui.components.LanguageBundle;
import io.github.palexdev.materialfx.controls.MFXButton;
import io.github.palexdev.materialfx.controls.MFXCheckbox;
import io.github.palexdev.materialfx.controls.MFXScrollPane;
import io.github.palexdev.materialfx.controls.MFXSlider;
import javafx.geometry.Pos;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import resources.ResourceController;
import java.util.Locale;
public class SettingScreen extends MFXScrollPane {
private DomeinController dc;
private ResourceController rs;
private BorderPane root;
private CustomMenu menu;
private VBox pane = new VBox();
private ComboBox<String> languageComboBox;
private static Label title;
private static MFXCheckbox checkbox;
private static Label soundLabel;
private static Label languageLabel;
public SettingScreen(BorderPane root, CustomMenu menu, DomeinController dc, ResourceController rs) {
this.dc = dc;
pane.setAlignment(Pos.TOP_CENTER);
pane.setSpacing(200);
this.rs = rs;
this.root = root;
this.menu = menu;
this.setContent(pane);
this.setFitToHeight(true);
this.setFitToWidth(true);
setup();
}
public void setup() {
title = new Label(LanguageBundle.getString("SettingScreen_setting"));
title.getStyleClass().add("title");
soundLabel = new Label(LanguageBundle.getString("SettingScreen_sound"));
VBox layoutBox = new VBox();
MFXSlider slider = new MFXSlider();
slider.setMin(0);
slider.setMax(100);
slider.setValue(rs.getCurrentVolume()*100);
slider.setOnMouseReleased(e -> {
System.out.println(slider.getValue());
rs.changeVolume(slider.getValue());
});
languageLabel = new Label("Language");
languageComboBox = new ComboBox<>();
HBox.setHgrow(languageComboBox, Priority.ALWAYS);
languageComboBox.getItems().addAll("en", "nl");
languageComboBox.setValue("en");
// voeg een<SUF>
languageComboBox.setOnAction(e -> switchLanguage());
layoutBox.setAlignment(Pos.CENTER);
checkbox = new MFXCheckbox(LanguageBundle.getString("SettingScreen_mute"));
checkbox.setSelected(rs.isMute());
checkbox.setOnAction(e -> rs.handleMute(checkbox.isSelected()));
layoutBox.setSpacing(20);
layoutBox.getChildren().addAll(soundLabel, slider, checkbox, languageLabel, languageComboBox);
pane.getChildren().addAll(title, layoutBox);
}
private void switchLanguage() {
Locale selectedLocale;
String selectedLanguage = languageComboBox.getValue();
if (selectedLanguage.equals("en")) {
selectedLocale = new Locale("en");
} else {
selectedLocale = new Locale("nl");
}
// Wijzig de taal in de hele applicatie
LanguageBundle.setLocale(selectedLocale);
//update taal van pagina waarop je staat
updateText();
/*LoginScreen.updateText();
MainScreen.updateText();
CompanyCardComponent.updateText();
NotificationScreen.updateText();
OrderScreen.updateText();
TransportDienstScreen.updateText();
RegisterScreen.updateText();
MyProductsScreen.updateText();*/
}
public static void updateText() {
title.setText(LanguageBundle.getString("SettingScreen_setting"));
checkbox.setText(LanguageBundle.getString("SettingScreen_mute"));
soundLabel.setText(LanguageBundle.getString("SettingScreen_sound"));
}
}
| false | 774 | 17 | 939 | 19 | 981 | 15 | 939 | 19 | 1,104 | 18 | false | false | false | false | false | true |
592 | 52480_0 | package com.digicoachindezorg.digicoachindezorg_backend.config;
/*
CORS (Cross Origin Resource Sharing) is een instelling die zorgt dat de frontend en de backend met elkaar kunnen
communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080).
De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten.
Vergeet niet om in de security config ook de ".cors()" optie aan te zetten.
*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class GlobalCorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
};
}
}
| Gentlemannerss/digicoachindezorg_backend | src/main/java/com/digicoachindezorg/digicoachindezorg_backend/config/GlobalCorsConfiguration.java | 323 | /*
CORS (Cross Origin Resource Sharing) is een instelling die zorgt dat de frontend en de backend met elkaar kunnen
communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080).
De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten.
Vergeet niet om in de security config ook de ".cors()" optie aan te zetten.
*/ | block_comment | nl | package com.digicoachindezorg.digicoachindezorg_backend.config;
/*
CORS (Cross Origin<SUF>*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class GlobalCorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
};
}
}
| false | 251 | 107 | 298 | 124 | 279 | 98 | 298 | 124 | 323 | 120 | false | false | false | false | false | true |
772 | 24453_2 | package edu.ap.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import edu.ap.spring.controller.RedisController;
import edu.ap.spring.redis.RedisService;
@SpringBootApplication
public class RedisApplication {
private String CHANNEL = "edu:ap:redis";
@Autowired
private RedisService service;
//Subscript op channel
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new ChannelTopic(CHANNEL));
return container;
}
//Deze luistert op channel en wanneer er een message komt stuur die deze onMessage functie van Controller
@Bean
MessageListenerAdapter listenerAdapter(RedisController controller) {
return new MessageListenerAdapter(controller, "onMessage");
}
//Deze gaat de database leeg maken en een message daarin toevoegen
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return (args) -> {
// empty db
this.service.flushDb();
// messaging
service.sendMessage(CHANNEL, "Hello from Spring Boot");
};
}
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
| IsmatFaizi/studeren-examen | Spring-Redis/src/main/java/edu/ap/spring/RedisApplication.java | 524 | //Deze gaat de database leeg maken en een message daarin toevoegen | line_comment | nl | package edu.ap.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import edu.ap.spring.controller.RedisController;
import edu.ap.spring.redis.RedisService;
@SpringBootApplication
public class RedisApplication {
private String CHANNEL = "edu:ap:redis";
@Autowired
private RedisService service;
//Subscript op channel
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new ChannelTopic(CHANNEL));
return container;
}
//Deze luistert op channel en wanneer er een message komt stuur die deze onMessage functie van Controller
@Bean
MessageListenerAdapter listenerAdapter(RedisController controller) {
return new MessageListenerAdapter(controller, "onMessage");
}
//Deze gaat<SUF>
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return (args) -> {
// empty db
this.service.flushDb();
// messaging
service.sendMessage(CHANNEL, "Hello from Spring Boot");
};
}
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
| false | 357 | 17 | 438 | 20 | 460 | 15 | 438 | 20 | 523 | 19 | false | false | false | false | false | true |
2,996 | 60681_1 | package novi.basics;
public class Player {
//attributen: informatie verzamelen
private String name;
private char token;
private int score;
//methoden: acties die de speler uit kan voeren
//constructor
public Player(String name, char token) {
this.name = name;
this.token = token;
score = 0;
}
//get methoden
public String getName() {
return name;
}
public char getToken() {
return token;
}
public int getScore() {
return score;
}
//set methoden
/*public void setScore(int score) {
this.score = score;
}*/
public void addScore() {
score++;
}
} | hogeschoolnovi/tic-tac-toe-Quinten-dev | src/novi/basics/Player.java | 201 | //methoden: acties die de speler uit kan voeren | line_comment | nl | package novi.basics;
public class Player {
//attributen: informatie verzamelen
private String name;
private char token;
private int score;
//methoden: acties<SUF>
//constructor
public Player(String name, char token) {
this.name = name;
this.token = token;
score = 0;
}
//get methoden
public String getName() {
return name;
}
public char getToken() {
return token;
}
public int getScore() {
return score;
}
//set methoden
/*public void setScore(int score) {
this.score = score;
}*/
public void addScore() {
score++;
}
} | false | 165 | 14 | 169 | 14 | 192 | 12 | 169 | 14 | 202 | 14 | false | false | false | false | false | true |
248 | 178223_2 | package dag15;
import java.lang.constant.Constable;
public class Java17Switch {
enum KLEUREN {
BLAUW, GEEL, ROOD;
}
public static void main(String[] args) {
int x = 8;
switch(x) {
default:
System.out.println("Wat is dit?");
break;
case 0:
System.out.println("X is nul");
break;
case 1:
System.out.println("X is een");
break;
case 2:
System.out.println("X is twee");
break;
}
// nieuwe versie, geen break nodig bij ->
switch(x) {
case 0 -> System.out.println("X is nul");
case 1 -> { System.out.println("X is een"); break; } // dit mag
case 2 -> System.out.println("X is twee");
default -> System.out.println("Wat is dit?");
}
// waarde returnen met switch statement
String getal = switch(x) {
case 0 -> "X is nul";
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// waarde returnen met switch statement en expliciet yield
String getal1 = switch(x) {
case 0: yield "X is nul";
case 1: yield "X is een";
case 2: yield "X is twee";
default: yield "Wat is dit?";
};
// waarde returnen met switch statement en meer acties
String getal2 = switch(x) {
case 0 -> {
System.out.println("Het is nul :)");
yield "X is nul";
}
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// enums en switch
KLEUREN kleur = KLEUREN.GEEL;
String s;
switch (kleur) {
case ROOD:
System.out.println("rood");
s = "rood";
break;
case BLAUW:
System.out.println("blauw");
s = "blauw";
break;
case GEEL:
s = "geel";
break;
default:
s = "watdan?!";
}
System.out.println(s);
// als je alle labels behandelt geen default nodig
var s1 = switch (kleur) {
case ROOD -> "rood";
case BLAUW -> KLEUREN.BLAUW;
case GEEL -> 2;
};
System.out.println(s1 + " " + s1.getClass());
}
}
| BrightBoost/ocp | src/main/java/dag15/Java17Switch.java | 754 | // waarde returnen met switch statement en expliciet yield | line_comment | nl | package dag15;
import java.lang.constant.Constable;
public class Java17Switch {
enum KLEUREN {
BLAUW, GEEL, ROOD;
}
public static void main(String[] args) {
int x = 8;
switch(x) {
default:
System.out.println("Wat is dit?");
break;
case 0:
System.out.println("X is nul");
break;
case 1:
System.out.println("X is een");
break;
case 2:
System.out.println("X is twee");
break;
}
// nieuwe versie, geen break nodig bij ->
switch(x) {
case 0 -> System.out.println("X is nul");
case 1 -> { System.out.println("X is een"); break; } // dit mag
case 2 -> System.out.println("X is twee");
default -> System.out.println("Wat is dit?");
}
// waarde returnen met switch statement
String getal = switch(x) {
case 0 -> "X is nul";
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// waarde returnen<SUF>
String getal1 = switch(x) {
case 0: yield "X is nul";
case 1: yield "X is een";
case 2: yield "X is twee";
default: yield "Wat is dit?";
};
// waarde returnen met switch statement en meer acties
String getal2 = switch(x) {
case 0 -> {
System.out.println("Het is nul :)");
yield "X is nul";
}
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// enums en switch
KLEUREN kleur = KLEUREN.GEEL;
String s;
switch (kleur) {
case ROOD:
System.out.println("rood");
s = "rood";
break;
case BLAUW:
System.out.println("blauw");
s = "blauw";
break;
case GEEL:
s = "geel";
break;
default:
s = "watdan?!";
}
System.out.println(s);
// als je alle labels behandelt geen default nodig
var s1 = switch (kleur) {
case ROOD -> "rood";
case BLAUW -> KLEUREN.BLAUW;
case GEEL -> 2;
};
System.out.println(s1 + " " + s1.getClass());
}
}
| false | 610 | 12 | 672 | 13 | 697 | 12 | 672 | 13 | 754 | 12 | false | false | false | false | false | true |
2,453 | 194301_0 | package be.ipeters.brol.cpbelcar.services;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.ibatis.javassist.bytecode.Descriptor.Iterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import be.ipeters.brol.cpbelcar.domain.Car;
import be.ipeters.brol.cpbelcar.domain.CarProduct;
import be.ipeters.brol.cpbelcar.domain.Production;
import be.ipeters.brol.cpbelcar.mappers.CarMapper;
@Service
public class CarService implements CrudService<Car, Integer> {
private boolean isCarCreationPossible = false;
private Integer pcgetProductId;
private Integer partStock = 0;
private Integer carStock = 0;
private Double partPrice=0.0;
private Double carPrice = 0.0;
private Integer partId = 0;
private Production production;
@Autowired
private CarMapper carMapper;
@Autowired
private SupplierOrderService supplierorderService;
@Autowired
private CarProductService cpService;
@Autowired
private ProductService productService;
@Autowired
private ProductionService productionService;
public CarService() {
super();
}
public CarService(CarMapper carMock) {
this.carMapper = carMock;
}
@Override
public void save(Car entity) {
/*
* bij een nieuwe wagen van een bepaald type dient de stock +1 te worden
* tegelijk 4 parts -1
*/
checkPartsAvailable(entity.getId());
if (isCarCreationPossible) {
// verminder de stock van elk onderdeel
partId=entity.getId();
adaptPartStock( partId);
// carMapper.insert(entity); // not creating a new line in the table, so update the stock
this.updateStockPlusOne(entity);
filloutProduction();
productionService.save(production);
System.out.println("We have: "+production.getDescription());
} else {
System.out.println("Not all parts are available...");
}
}
protected void filloutProduction() {
// fill out the fields orderId, orderlineId, description, lastUpdate
production=new Production(1, 1, 1, "created car of type "+partId, LocalDate.now());
}
protected void adaptPartStock(Integer carId) {
// verminder stock van elk van de 4 parts met id=partID
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
for (CarProduct pc : cpList) {
System.out.println("productService.updateProductStock(pc.getProductId()):"+pc.getProductId());
partStock=productService.getProductStock(pc.getProductId());
System.out.println("partStock="+partStock+", for part "+pc.getProductId()+", which is "+productService.findById(pc.getProductId()));
partStock--;
System.out.println("partStock="+partStock);
productService.updateStockMinOne(pc.getProductId());
}
}
public boolean checkPartsAvailable(Integer carId) {
Map<Integer, Integer> cpMap = new HashMap<Integer, Integer>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot produce a car with id " + carId + ".");
isCarCreationPossible = false;
} else { //
for (CarProduct pc : cpList) {
pcgetProductId = pc.getProductId();
System.out.println(pcgetProductId);
partStock = productService.findById(pcgetProductId).getStock();
cpMap.put(pcgetProductId, partStock);
switch (partStock) {
case 0:
// part not available
System.out
.println("part <" + productService.findById(pcgetProductId).getName() + "> not available");
System.out.println("Need to order this part...");
// create SupplierOrder // Order this part
supplierorderService.createSupplierOrderViaPartId(pcgetProductId);
isCarCreationPossible = false;
break;
default:
System.out.println("available!");
isCarCreationPossible = true;
}
}
// check if at least one part is missing to set isCarCreationPossible=false;
for (Map.Entry<Integer, Integer> entry : cpMap.entrySet()) {
if (entry.getValue() == 0) {
isCarCreationPossible = false;
}
}
}
System.out.println("isCarCreationPossible=" + isCarCreationPossible);
return isCarCreationPossible;
}
public Double calculateCarOrderPrice(Integer carId) {
System.out.println("carService - calculateCarOrderPrice");
carPrice=0.0;
Map<Integer, Double> cpMap = new HashMap<Integer, Double>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot calculate a price for car with id " + carId + ".");
} else {
for (CarProduct cp : cpList) {
pcgetProductId = cp.getProductId();
partPrice = productService.findById(pcgetProductId).getConsumerPrice();
System.out.println(pcgetProductId+ " costs " +partPrice);
carPrice+=partPrice;
}
}
System.out.println("carPrice=" + carPrice);
return carPrice;
}
@Override
public Car findById(Integer key) {
return carMapper.findById(key);
}
@Override
public List<Car> findAll() {
return carMapper.findAll();
}
@Override
public void deleteById(Integer key) {
carMapper.deleteById(key);
}
@Override
public void update(Car entity) {
carMapper.update(entity);
}
public Integer getCarStock(Integer key) {
return carMapper.getCarStock(key);
}
public void updateStockMinOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("carStock="+carStock);
carStock--;
System.out.println("carStock="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public void updateStockPlusOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
carStock++;
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public Integer getProductStock(int carProductId) {
// TODO Auto-generated method stub
return this.findById(carProductId).getStock();
}
}
| cpjjpeters/javafx1 | src/main/java/be/ipeters/brol/cpbelcar/services/CarService.java | 2,080 | /*
* bij een nieuwe wagen van een bepaald type dient de stock +1 te worden
* tegelijk 4 parts -1
*/ | block_comment | nl | package be.ipeters.brol.cpbelcar.services;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.ibatis.javassist.bytecode.Descriptor.Iterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import be.ipeters.brol.cpbelcar.domain.Car;
import be.ipeters.brol.cpbelcar.domain.CarProduct;
import be.ipeters.brol.cpbelcar.domain.Production;
import be.ipeters.brol.cpbelcar.mappers.CarMapper;
@Service
public class CarService implements CrudService<Car, Integer> {
private boolean isCarCreationPossible = false;
private Integer pcgetProductId;
private Integer partStock = 0;
private Integer carStock = 0;
private Double partPrice=0.0;
private Double carPrice = 0.0;
private Integer partId = 0;
private Production production;
@Autowired
private CarMapper carMapper;
@Autowired
private SupplierOrderService supplierorderService;
@Autowired
private CarProductService cpService;
@Autowired
private ProductService productService;
@Autowired
private ProductionService productionService;
public CarService() {
super();
}
public CarService(CarMapper carMock) {
this.carMapper = carMock;
}
@Override
public void save(Car entity) {
/*
* bij een nieuwe<SUF>*/
checkPartsAvailable(entity.getId());
if (isCarCreationPossible) {
// verminder de stock van elk onderdeel
partId=entity.getId();
adaptPartStock( partId);
// carMapper.insert(entity); // not creating a new line in the table, so update the stock
this.updateStockPlusOne(entity);
filloutProduction();
productionService.save(production);
System.out.println("We have: "+production.getDescription());
} else {
System.out.println("Not all parts are available...");
}
}
protected void filloutProduction() {
// fill out the fields orderId, orderlineId, description, lastUpdate
production=new Production(1, 1, 1, "created car of type "+partId, LocalDate.now());
}
protected void adaptPartStock(Integer carId) {
// verminder stock van elk van de 4 parts met id=partID
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
for (CarProduct pc : cpList) {
System.out.println("productService.updateProductStock(pc.getProductId()):"+pc.getProductId());
partStock=productService.getProductStock(pc.getProductId());
System.out.println("partStock="+partStock+", for part "+pc.getProductId()+", which is "+productService.findById(pc.getProductId()));
partStock--;
System.out.println("partStock="+partStock);
productService.updateStockMinOne(pc.getProductId());
}
}
public boolean checkPartsAvailable(Integer carId) {
Map<Integer, Integer> cpMap = new HashMap<Integer, Integer>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot produce a car with id " + carId + ".");
isCarCreationPossible = false;
} else { //
for (CarProduct pc : cpList) {
pcgetProductId = pc.getProductId();
System.out.println(pcgetProductId);
partStock = productService.findById(pcgetProductId).getStock();
cpMap.put(pcgetProductId, partStock);
switch (partStock) {
case 0:
// part not available
System.out
.println("part <" + productService.findById(pcgetProductId).getName() + "> not available");
System.out.println("Need to order this part...");
// create SupplierOrder // Order this part
supplierorderService.createSupplierOrderViaPartId(pcgetProductId);
isCarCreationPossible = false;
break;
default:
System.out.println("available!");
isCarCreationPossible = true;
}
}
// check if at least one part is missing to set isCarCreationPossible=false;
for (Map.Entry<Integer, Integer> entry : cpMap.entrySet()) {
if (entry.getValue() == 0) {
isCarCreationPossible = false;
}
}
}
System.out.println("isCarCreationPossible=" + isCarCreationPossible);
return isCarCreationPossible;
}
public Double calculateCarOrderPrice(Integer carId) {
System.out.println("carService - calculateCarOrderPrice");
carPrice=0.0;
Map<Integer, Double> cpMap = new HashMap<Integer, Double>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot calculate a price for car with id " + carId + ".");
} else {
for (CarProduct cp : cpList) {
pcgetProductId = cp.getProductId();
partPrice = productService.findById(pcgetProductId).getConsumerPrice();
System.out.println(pcgetProductId+ " costs " +partPrice);
carPrice+=partPrice;
}
}
System.out.println("carPrice=" + carPrice);
return carPrice;
}
@Override
public Car findById(Integer key) {
return carMapper.findById(key);
}
@Override
public List<Car> findAll() {
return carMapper.findAll();
}
@Override
public void deleteById(Integer key) {
carMapper.deleteById(key);
}
@Override
public void update(Car entity) {
carMapper.update(entity);
}
public Integer getCarStock(Integer key) {
return carMapper.getCarStock(key);
}
public void updateStockMinOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("carStock="+carStock);
carStock--;
System.out.println("carStock="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public void updateStockPlusOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
carStock++;
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public Integer getProductStock(int carProductId) {
// TODO Auto-generated method stub
return this.findById(carProductId).getStock();
}
}
| false | 1,517 | 35 | 1,876 | 36 | 1,860 | 32 | 1,876 | 36 | 2,255 | 40 | false | false | false | false | false | true |
2,753 | 43284_7 | import java.nio.BufferOverflowException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Spel {
ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
//ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
ArrayList<Speler> spelerArrayList = new ArrayList<>();
ArrayList<Gans> gansArrayList = new ArrayList<>();
ArrayList<Gans> speelVolgorde = new ArrayList<>();
Dobbelsteen steen1 = new Dobbelsteen();
Dobbelsteen steen2 = new Dobbelsteen();
public void maakSpelers() {
Bord das = new Bord();
das.fillVakjeArraylist();
System.out.println("hoeveel spelers zijn er");
Scanner in = new Scanner(System.in);
int userInput = 0;
int spelers = 0;
try {
userInput = Integer.parseInt(in.next());
System.out.println("je nummer was" + userInput);
if (userInput < 0) {
throw new ArithmeticException("negatief!");
}
if (userInput >= 7) {
throw new BufferOverflowException();
}
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println("");
}
spelers = userInput;
for (int i = 0; i < spelers; i++) {
try {
System.out.println("voer je naam in");
Scanner in2 = new Scanner(System.in);
String userNaamInput = in2.next();
System.out.println("je naam is " + userNaamInput);
Speler speler = new Speler("usernaam", i + 1);
System.out.println(userNaamInput + " jij bent speler " + i + 1 + " je ganskleur is " + gansKleuren.get(i));
Gans gans = new Gans(gansKleuren.get(i), speler);
spelerArrayList.add(speler);
gansArrayList.add(gans);
} catch (BufferOverflowException ignore) {
}
}
//speler volgorde bepalen
speelVolgorde = bepaalSpeelVolgorde(gansArrayList,steen1);
System.out.println(speelVolgorde);
//methode roll 1
System.out.println("druk op een toests om terug te gaan");
userInput = Integer.parseInt(in.next());
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println(" ");
}
// break; // breaks out of the loop, do not remove fully
} catch (NumberFormatException ignore) {
System.out.println("voer alleen getallen ");
} catch (ArithmeticException ignore) {
System.out.println("negatief ");
} catch (BufferOverflowException ignore) {
System.out.println("veel te groot getal ");
}
}
public void speelronde(ArrayList<Gans> speelVolgorde, Dobbelsteen steen1, Dobbelsteen steen2 ){
for (Gans gans: speelVolgorde) {
if (gans.BeurtOverslaan == true){
continue;
}
int waardeSteen1 = steen1.roll();
int waardeSteen2 = steen2.roll();
// TODO: 13/10/2022 // check voor specialle combi bij en eerste worp
int totaalWaardeWorp = waardeSteen1 + waardeSteen2;
int curPos = gans.getPositie();
}
// TODO: 12/10/2022 for each speler, check if beurt overslaan, roll 2 dobbelstenen, addup, check if arrayIndex empty, move on array
}
public ArrayList<Gans> bepaalSpeelVolgorde(ArrayList<Gans> gansArrayList, Dobbelsteen steen){
ArrayList<Gans> newSpeelvolgorde = new ArrayList<>();
//int[] rolls = new int[gansArrayList.size()];
int x= 0;
ArrayList<Integer> rolls = new ArrayList<>();
for (Gans i: gansArrayList) {
int currentRoll = steen.roll();
while (rolls.contains(currentRoll)){ // waarneer 2 spelers dezelfde worp hebben moet de laatste speler gooien tot hij een niet eerder gegooide waarde krijgt.
currentRoll = steen.roll();
}
rolls.add(currentRoll);
x+=1;
}
// sort players ; sort indexes; how to remember reference to player
// [5,3,4,1]
// get index max; place index in new VolgordeArray, set value in worp array to 0;
for (Gans ii: gansArrayList) {
int max = 0;
for (int val : rolls) {
if (val > max) {
max = val;
}
}
int indexMax = rolls.indexOf(max);
newSpeelvolgorde.add(gansArrayList.get(indexMax));
rolls.set(indexMax, 0);
}
return newSpeelvolgorde;
}
}
| gabeplz/ganzebordStan | src/Spel.java | 1,513 | // waarneer 2 spelers dezelfde worp hebben moet de laatste speler gooien tot hij een niet eerder gegooide waarde krijgt. | line_comment | nl | import java.nio.BufferOverflowException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Spel {
ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
//ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
ArrayList<Speler> spelerArrayList = new ArrayList<>();
ArrayList<Gans> gansArrayList = new ArrayList<>();
ArrayList<Gans> speelVolgorde = new ArrayList<>();
Dobbelsteen steen1 = new Dobbelsteen();
Dobbelsteen steen2 = new Dobbelsteen();
public void maakSpelers() {
Bord das = new Bord();
das.fillVakjeArraylist();
System.out.println("hoeveel spelers zijn er");
Scanner in = new Scanner(System.in);
int userInput = 0;
int spelers = 0;
try {
userInput = Integer.parseInt(in.next());
System.out.println("je nummer was" + userInput);
if (userInput < 0) {
throw new ArithmeticException("negatief!");
}
if (userInput >= 7) {
throw new BufferOverflowException();
}
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println("");
}
spelers = userInput;
for (int i = 0; i < spelers; i++) {
try {
System.out.println("voer je naam in");
Scanner in2 = new Scanner(System.in);
String userNaamInput = in2.next();
System.out.println("je naam is " + userNaamInput);
Speler speler = new Speler("usernaam", i + 1);
System.out.println(userNaamInput + " jij bent speler " + i + 1 + " je ganskleur is " + gansKleuren.get(i));
Gans gans = new Gans(gansKleuren.get(i), speler);
spelerArrayList.add(speler);
gansArrayList.add(gans);
} catch (BufferOverflowException ignore) {
}
}
//speler volgorde bepalen
speelVolgorde = bepaalSpeelVolgorde(gansArrayList,steen1);
System.out.println(speelVolgorde);
//methode roll 1
System.out.println("druk op een toests om terug te gaan");
userInput = Integer.parseInt(in.next());
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println(" ");
}
// break; // breaks out of the loop, do not remove fully
} catch (NumberFormatException ignore) {
System.out.println("voer alleen getallen ");
} catch (ArithmeticException ignore) {
System.out.println("negatief ");
} catch (BufferOverflowException ignore) {
System.out.println("veel te groot getal ");
}
}
public void speelronde(ArrayList<Gans> speelVolgorde, Dobbelsteen steen1, Dobbelsteen steen2 ){
for (Gans gans: speelVolgorde) {
if (gans.BeurtOverslaan == true){
continue;
}
int waardeSteen1 = steen1.roll();
int waardeSteen2 = steen2.roll();
// TODO: 13/10/2022 // check voor specialle combi bij en eerste worp
int totaalWaardeWorp = waardeSteen1 + waardeSteen2;
int curPos = gans.getPositie();
}
// TODO: 12/10/2022 for each speler, check if beurt overslaan, roll 2 dobbelstenen, addup, check if arrayIndex empty, move on array
}
public ArrayList<Gans> bepaalSpeelVolgorde(ArrayList<Gans> gansArrayList, Dobbelsteen steen){
ArrayList<Gans> newSpeelvolgorde = new ArrayList<>();
//int[] rolls = new int[gansArrayList.size()];
int x= 0;
ArrayList<Integer> rolls = new ArrayList<>();
for (Gans i: gansArrayList) {
int currentRoll = steen.roll();
while (rolls.contains(currentRoll)){ // waarneer 2<SUF>
currentRoll = steen.roll();
}
rolls.add(currentRoll);
x+=1;
}
// sort players ; sort indexes; how to remember reference to player
// [5,3,4,1]
// get index max; place index in new VolgordeArray, set value in worp array to 0;
for (Gans ii: gansArrayList) {
int max = 0;
for (int val : rolls) {
if (val > max) {
max = val;
}
}
int indexMax = rolls.indexOf(max);
newSpeelvolgorde.add(gansArrayList.get(indexMax));
rolls.set(indexMax, 0);
}
return newSpeelvolgorde;
}
}
| false | 1,201 | 36 | 1,344 | 44 | 1,326 | 28 | 1,344 | 44 | 1,477 | 40 | false | false | false | false | false | true |
299 | 57243_0 | package cheese.squeeze.gameObjects;_x000D_
_x000D_
import java.util.Iterator;_x000D_
import java.util.List;_x000D_
_x000D_
import cheese.squeeze.helpers.AssetLoader;_x000D_
_x000D_
import com.badlogic.gdx.Gdx;_x000D_
import com.badlogic.gdx.math.MathUtils;_x000D_
import com.badlogic.gdx.math.Vector2;_x000D_
_x000D_
//TODO: direction bijhouden, en veranderen als we aan een gotopoint belanden._x000D_
public class Mouse {_x000D_
_x000D_
private Vector2 position;_x000D_
private Vector2 velocity;_x000D_
private final float FLIKERING =100;_x000D_
private float EYEOPEN;_x000D_
private boolean open = true;_x000D_
_x000D_
private float orignSpeed;_x000D_
private float speed;_x000D_
private float tolerance = 0.02f;_x000D_
_x000D_
private Vector2 absolutePosition;_x000D_
_x000D_
private float rotation;_x000D_
private Vector2 mouseNose = AssetLoader.mouseNose;_x000D_
_x000D_
private Line currentLine;_x000D_
private Line nextLine;_x000D_
private Vector2 goToOrientation;_x000D_
private Vector2 nextGoToPoint;_x000D_
private boolean ended = false;_x000D_
_x000D_
public Mouse(float speed, Line line){_x000D_
EYEOPEN = (float) (FLIKERING*Math.random());_x000D_
float x = line.getX1();_x000D_
float y = line.getY1();_x000D_
//float y = 0;_x000D_
position = new Vector2(x,y);_x000D_
this.currentLine = line;_x000D_
this.speed = speed;_x000D_
this.orignSpeed = speed;_x000D_
//position = new Vector2(x-(mouseNose.x), y- (mouseNose.y));_x000D_
_x000D_
velocity = new Vector2(0, 0);_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
updatePath();_x000D_
}_x000D_
_x000D_
public boolean isOnHorizontalLine() {_x000D_
if(currentLine instanceof HorizontalLine) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void update(float delta) {_x000D_
EYEOPEN--;_x000D_
_x000D_
if (nextGoToPoint != null) {_x000D_
if(atIntersection()) {_x000D_
//System.out.println("intersection reached!");_x000D_
//the mouse stands now at the previous nextGoToPoint_x000D_
setPosition(nextGoToPoint.x, nextGoToPoint.y);_x000D_
//nextGoToPoint is yet to be determined_x000D_
nextGoToPoint = null;_x000D_
//This mouse is now on the new line. _x000D_
//If there is no next line, the mouse stays on this line._x000D_
currentLine = (nextLine != null) ? nextLine : currentLine;_x000D_
//nextLine is yet to be determined._x000D_
nextLine = null;_x000D_
if (currentLine instanceof VerticalLine){_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
} else if (currentLine instanceof HorizontalLine) {_x000D_
if (getPosition().equals(currentLine.getPoint1()))_x000D_
goToOrientation = currentLine.getPoint2().cpy().sub(currentLine.getPoint1());_x000D_
else_x000D_
goToOrientation = currentLine.getPoint1().cpy().sub(currentLine.getPoint2());_x000D_
}_x000D_
//updateVelocityDirection();_x000D_
//pick a new destination_x000D_
updatePath();_x000D_
}_x000D_
//set the mouses new speed._x000D_
if (atIntersection()) {_x000D_
//The mouse ran into something with a dead end._x000D_
((VerticalLine) currentLine).getGoal().activate();_x000D_
velocity.set(Vector2.Zero);_x000D_
ended = true;_x000D_
} else {_x000D_
updateVelocityDirection();_x000D_
}_x000D_
//move the mouse._x000D_
updateVelocityDirection();_x000D_
// setPosition(getX() + velocity.x * delta, getY() + velocity.y * delta);_x000D_
setPosition(getX() + velocity.x * 1, getY() + velocity.y * 1);_x000D_
//System.out.println(this.rotation);_x000D_
} _x000D_
}_x000D_
_x000D_
private void updateVelocityDirection() {_x000D_
if(!ended) {_x000D_
float angle = (float) Math.atan2(nextGoToPoint.y - getY(), nextGoToPoint.x - getX());_x000D_
velocity.set((float) Math.cos(angle) * speed, (float) Math.sin(angle) * speed);_x000D_
//set the mouses angle._x000D_
setRotation(angle * MathUtils.radiansToDegrees);_x000D_
}_x000D_
else {_x000D_
setRotation(90);_x000D_
}_x000D_
}_x000D_
_x000D_
public void updatePath() {_x000D_
Vector2 nextIntersection = currentLine.getNextIntersection(getPosition(), goToOrientation);_x000D_
nextLine = currentLine.getNeighbour(getPosition(), goToOrientation);_x000D_
if (nextIntersection == null) {_x000D_
nextGoToPoint = currentLine.getEndPoint(getPosition(), velocity);_x000D_
} else {_x000D_
nextGoToPoint = nextIntersection;_x000D_
}_x000D_
}_x000D_
_x000D_
private boolean atIntersection() {_x000D_
float dynTolerance = speed / tolerance * Gdx.graphics.getDeltaTime();_x000D_
//System.out.println("dyn tol: " + dynTolerance);_x000D_
return Math.abs(nextGoToPoint.x - getX()) <= dynTolerance _x000D_
&& Math.abs(nextGoToPoint.y - getY()) <= dynTolerance;_x000D_
}_x000D_
_x000D_
private void setRotation(float f) {_x000D_
this.rotation = f;_x000D_
_x000D_
}_x000D_
_x000D_
public float getX() {_x000D_
return position.x;_x000D_
}_x000D_
_x000D_
public float getY() {_x000D_
return position.y;_x000D_
}_x000D_
_x000D_
private void setPosition(float x,float y) {_x000D_
this.position.set(x, y);_x000D_
}_x000D_
_x000D_
public float getXAbs() {_x000D_
return this.absolutePosition.x;_x000D_
}_x000D_
_x000D_
public float getYAbs() {_x000D_
return this.absolutePosition.y;_x000D_
}_x000D_
_x000D_
public float getRotation() {_x000D_
return rotation;_x000D_
}_x000D_
_x000D_
_x000D_
public Vector2 getPosition() {_x000D_
return position;_x000D_
}_x000D_
_x000D_
public boolean isEnded() {_x000D_
return ended ;_x000D_
}_x000D_
_x000D_
public float getSpeed() {_x000D_
// TODO Auto-generated method stub_x000D_
return velocity.x + velocity.y;_x000D_
}_x000D_
_x000D_
//public void changeNextWayPoints(ArrayList<Vector2> newWaypoints) {_x000D_
// this.setPath(nPath);_x000D_
//}_x000D_
_x000D_
public boolean eyesOpen() {_x000D_
if(EYEOPEN < 0 && !open) {_x000D_
EYEOPEN = (float) ((FLIKERING*2)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
if(EYEOPEN < 0 && open) {_x000D_
EYEOPEN = (float) ((FLIKERING/5)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
return open;_x000D_
}_x000D_
_x000D_
public void setSpeed(float angle) {_x000D_
this.speed = this.orignSpeed + this.orignSpeed*angle;_x000D_
}_x000D_
_x000D_
public float getSpeedLine() {_x000D_
return this.speed - this.orignSpeed;_x000D_
}_x000D_
_x000D_
}_x000D_
| Camambar/CheeseSqueeze | core/src/cheese/squeeze/gameObjects/Mouse.java | 1,855 | //TODO: direction bijhouden, en veranderen als we aan een gotopoint belanden._x000D_ | line_comment | nl | package cheese.squeeze.gameObjects;_x000D_
_x000D_
import java.util.Iterator;_x000D_
import java.util.List;_x000D_
_x000D_
import cheese.squeeze.helpers.AssetLoader;_x000D_
_x000D_
import com.badlogic.gdx.Gdx;_x000D_
import com.badlogic.gdx.math.MathUtils;_x000D_
import com.badlogic.gdx.math.Vector2;_x000D_
_x000D_
//TODO: direction<SUF>
public class Mouse {_x000D_
_x000D_
private Vector2 position;_x000D_
private Vector2 velocity;_x000D_
private final float FLIKERING =100;_x000D_
private float EYEOPEN;_x000D_
private boolean open = true;_x000D_
_x000D_
private float orignSpeed;_x000D_
private float speed;_x000D_
private float tolerance = 0.02f;_x000D_
_x000D_
private Vector2 absolutePosition;_x000D_
_x000D_
private float rotation;_x000D_
private Vector2 mouseNose = AssetLoader.mouseNose;_x000D_
_x000D_
private Line currentLine;_x000D_
private Line nextLine;_x000D_
private Vector2 goToOrientation;_x000D_
private Vector2 nextGoToPoint;_x000D_
private boolean ended = false;_x000D_
_x000D_
public Mouse(float speed, Line line){_x000D_
EYEOPEN = (float) (FLIKERING*Math.random());_x000D_
float x = line.getX1();_x000D_
float y = line.getY1();_x000D_
//float y = 0;_x000D_
position = new Vector2(x,y);_x000D_
this.currentLine = line;_x000D_
this.speed = speed;_x000D_
this.orignSpeed = speed;_x000D_
//position = new Vector2(x-(mouseNose.x), y- (mouseNose.y));_x000D_
_x000D_
velocity = new Vector2(0, 0);_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
updatePath();_x000D_
}_x000D_
_x000D_
public boolean isOnHorizontalLine() {_x000D_
if(currentLine instanceof HorizontalLine) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void update(float delta) {_x000D_
EYEOPEN--;_x000D_
_x000D_
if (nextGoToPoint != null) {_x000D_
if(atIntersection()) {_x000D_
//System.out.println("intersection reached!");_x000D_
//the mouse stands now at the previous nextGoToPoint_x000D_
setPosition(nextGoToPoint.x, nextGoToPoint.y);_x000D_
//nextGoToPoint is yet to be determined_x000D_
nextGoToPoint = null;_x000D_
//This mouse is now on the new line. _x000D_
//If there is no next line, the mouse stays on this line._x000D_
currentLine = (nextLine != null) ? nextLine : currentLine;_x000D_
//nextLine is yet to be determined._x000D_
nextLine = null;_x000D_
if (currentLine instanceof VerticalLine){_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
} else if (currentLine instanceof HorizontalLine) {_x000D_
if (getPosition().equals(currentLine.getPoint1()))_x000D_
goToOrientation = currentLine.getPoint2().cpy().sub(currentLine.getPoint1());_x000D_
else_x000D_
goToOrientation = currentLine.getPoint1().cpy().sub(currentLine.getPoint2());_x000D_
}_x000D_
//updateVelocityDirection();_x000D_
//pick a new destination_x000D_
updatePath();_x000D_
}_x000D_
//set the mouses new speed._x000D_
if (atIntersection()) {_x000D_
//The mouse ran into something with a dead end._x000D_
((VerticalLine) currentLine).getGoal().activate();_x000D_
velocity.set(Vector2.Zero);_x000D_
ended = true;_x000D_
} else {_x000D_
updateVelocityDirection();_x000D_
}_x000D_
//move the mouse._x000D_
updateVelocityDirection();_x000D_
// setPosition(getX() + velocity.x * delta, getY() + velocity.y * delta);_x000D_
setPosition(getX() + velocity.x * 1, getY() + velocity.y * 1);_x000D_
//System.out.println(this.rotation);_x000D_
} _x000D_
}_x000D_
_x000D_
private void updateVelocityDirection() {_x000D_
if(!ended) {_x000D_
float angle = (float) Math.atan2(nextGoToPoint.y - getY(), nextGoToPoint.x - getX());_x000D_
velocity.set((float) Math.cos(angle) * speed, (float) Math.sin(angle) * speed);_x000D_
//set the mouses angle._x000D_
setRotation(angle * MathUtils.radiansToDegrees);_x000D_
}_x000D_
else {_x000D_
setRotation(90);_x000D_
}_x000D_
}_x000D_
_x000D_
public void updatePath() {_x000D_
Vector2 nextIntersection = currentLine.getNextIntersection(getPosition(), goToOrientation);_x000D_
nextLine = currentLine.getNeighbour(getPosition(), goToOrientation);_x000D_
if (nextIntersection == null) {_x000D_
nextGoToPoint = currentLine.getEndPoint(getPosition(), velocity);_x000D_
} else {_x000D_
nextGoToPoint = nextIntersection;_x000D_
}_x000D_
}_x000D_
_x000D_
private boolean atIntersection() {_x000D_
float dynTolerance = speed / tolerance * Gdx.graphics.getDeltaTime();_x000D_
//System.out.println("dyn tol: " + dynTolerance);_x000D_
return Math.abs(nextGoToPoint.x - getX()) <= dynTolerance _x000D_
&& Math.abs(nextGoToPoint.y - getY()) <= dynTolerance;_x000D_
}_x000D_
_x000D_
private void setRotation(float f) {_x000D_
this.rotation = f;_x000D_
_x000D_
}_x000D_
_x000D_
public float getX() {_x000D_
return position.x;_x000D_
}_x000D_
_x000D_
public float getY() {_x000D_
return position.y;_x000D_
}_x000D_
_x000D_
private void setPosition(float x,float y) {_x000D_
this.position.set(x, y);_x000D_
}_x000D_
_x000D_
public float getXAbs() {_x000D_
return this.absolutePosition.x;_x000D_
}_x000D_
_x000D_
public float getYAbs() {_x000D_
return this.absolutePosition.y;_x000D_
}_x000D_
_x000D_
public float getRotation() {_x000D_
return rotation;_x000D_
}_x000D_
_x000D_
_x000D_
public Vector2 getPosition() {_x000D_
return position;_x000D_
}_x000D_
_x000D_
public boolean isEnded() {_x000D_
return ended ;_x000D_
}_x000D_
_x000D_
public float getSpeed() {_x000D_
// TODO Auto-generated method stub_x000D_
return velocity.x + velocity.y;_x000D_
}_x000D_
_x000D_
//public void changeNextWayPoints(ArrayList<Vector2> newWaypoints) {_x000D_
// this.setPath(nPath);_x000D_
//}_x000D_
_x000D_
public boolean eyesOpen() {_x000D_
if(EYEOPEN < 0 && !open) {_x000D_
EYEOPEN = (float) ((FLIKERING*2)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
if(EYEOPEN < 0 && open) {_x000D_
EYEOPEN = (float) ((FLIKERING/5)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
return open;_x000D_
}_x000D_
_x000D_
public void setSpeed(float angle) {_x000D_
this.speed = this.orignSpeed + this.orignSpeed*angle;_x000D_
}_x000D_
_x000D_
public float getSpeedLine() {_x000D_
return this.speed - this.orignSpeed;_x000D_
}_x000D_
_x000D_
}_x000D_
| false | 2,610 | 28 | 2,932 | 29 | 2,921 | 24 | 2,932 | 29 | 3,304 | 29 | false | false | false | false | false | true |
1,827 | 99855_5 | package be.valuya.bob.core.reader;
import be.valuya.advantaje.core.AdvantajeRecord;
import be.valuya.bob.core.domain.BobAccount;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;
public class BobAccountRecordReader {
public BobAccount readAccount(AdvantajeRecord advantajeRecord) {
String aid = advantajeRecord.getValue("AID"); //: (STRING, 10): 1
Optional<Boolean> aistitle = advantajeRecord.getValueOptional("AISTITLE"); //: (LOGICAL, 1): true
Optional<String> heading1 = advantajeRecord.getValueOptional("HEADING1"); //: (STRING, 40): Fonds propres
Optional<String> heading2 = advantajeRecord.getValueOptional("HEADING2"); //: (STRING, 40): Eigen vermogen
Optional<String> longheading1 = advantajeRecord.getValueOptional("LONGHEADING1"); //: (STRING, 120): Fonds propres, provisions pour risques et charges et dettes à plus d'un an
Optional<String> longheading2 = advantajeRecord.getValueOptional("LONGHEADING2"); //: (STRING, 120): Eigen vermogen, voorzieningen voor risico's en kosten en schulden op meer dan een jaar
Optional<String> asecondid = advantajeRecord.getValueOptional("ASECONDID"); //: (STRING, 10):
Optional<String> afree = advantajeRecord.getValueOptional("AFREE"); //: (STRING, 40):
Optional<String> acat = advantajeRecord.getValueOptional("ACAT"); //: (STRING, 3):
Optional<String> aintcat = advantajeRecord.getValueOptional("AINTCAT"); //: (STRING, 10):
Optional<String> acatcomm = advantajeRecord.getValueOptional("ACATCOMM"); //: (STRING, 1):
Optional<String> adbcd = advantajeRecord.getValueOptional("ADBCD"); //: (STRING, 1): C
Optional<Boolean> aiscost = advantajeRecord.getValueOptional("AISCOST"); //: (LOGICAL, 1): [-]
Optional<String> avattype = advantajeRecord.getValueOptional("AVATTYPE"); //: (STRING, 1):
Optional<String> avatenat1 = advantajeRecord.getValueOptional("AVATENAT1"); //: (STRING, 3):
Optional<String> avatenat2 = advantajeRecord.getValueOptional("AVATENAT2"); //: (STRING, 3):
Optional<Double> avatecmp = advantajeRecord.getValueOptional("AVATECMP"); //: (DOUBLE, 8): [-]
Optional<String> avatnnat1 = advantajeRecord.getValueOptional("AVATNNAT1"); //: (STRING, 3):
Optional<String> avatnnat2 = advantajeRecord.getValueOptional("AVATNNAT2"); //: (STRING, 3):
Optional<Double> avatncmp = advantajeRecord.getValueOptional("AVATNCMP"); //: (DOUBLE, 8): [-]
Optional<String> avatinat1 = advantajeRecord.getValueOptional("AVATINAT1"); //: (STRING, 3):
Optional<String> avatinat2 = advantajeRecord.getValueOptional("AVATINAT2"); //: (STRING, 3):
Optional<Double> avaticmp = advantajeRecord.getValueOptional("AVATICMP"); //: (DOUBLE, 8): [-]
Optional<Boolean> aissummary = advantajeRecord.getValueOptional("AISSUMMARY"); //: (LOGICAL, 1): false
Optional<Boolean> aisstatus = advantajeRecord.getValueOptional("AISSTATUS"); //: (LOGICAL, 1): [-]
Optional<Boolean> aisreadonl = advantajeRecord.getValueOptional("AISREADONL"); //: (LOGICAL, 1): false
Optional<Boolean> aissecret = advantajeRecord.getValueOptional("AISSECRET"); //: (LOGICAL, 1): false
Optional<Boolean> vtravfa = advantajeRecord.getValueOptional("VTRAVFA"); //: (LOGICAL, 1): [-]
Optional<Boolean> aismatch = advantajeRecord.getValueOptional("AISMATCH"); //: (LOGICAL, 1): false
Optional<String> depacc = advantajeRecord.getValueOptional("DEPACC"); //: (STRING, 10):
Optional<String> provacc = advantajeRecord.getValueOptional("PROVACC"); //: (STRING, 10):
Optional<Boolean> hisintrastat = advantajeRecord.getValueOptional("HISINTRASTAT"); //: (LOGICAL, 1): [-]
Optional<Integer> amatchno = advantajeRecord.getValueOptional("AMATCHNO"); //: (INTEGER, 4): [-]
Optional<String> abalance = advantajeRecord.getValueOptional("ABALANCE"); //: (STRING, 10): LIABILIT
Optional<String> arem = advantajeRecord.getValueOptional("AREM"); //: (STRING, 35):
Optional<Boolean> avatcas = advantajeRecord.getValueOptional("AVATCAS"); //: (LOGICAL, 1): [-]
Optional<Boolean> acctsecondid = advantajeRecord.getValueOptional("ACCTSECONDID"); //: (LOGICAL, 1): [-]
Optional<byte[]> amemo = advantajeRecord.getValueOptional("AMEMO"); //: (BINARY, 9): [B@3cda1055
Optional<Double> prcndcharges = advantajeRecord.getValueOptional("PRCNDCHARGES"); //: (DOUBLE, 8): 0.0
Optional<Double> prcprivate = advantajeRecord.getValueOptional("PRCPRIVATE"); //: (DOUBLE, 8): 0.0
Optional<String> typendcharges = advantajeRecord.getValueOptional("TYPENDCHARGES"); //: (STRING, 12):
Optional<String> createdby = advantajeRecord.getValueOptional("CREATEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> createdon = advantajeRecord.getValueOptional("CREATEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> modifiedby = advantajeRecord.getValueOptional("MODIFIEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> modifiedon = advantajeRecord.getValueOptional("MODIFIEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> trftstatus = advantajeRecord.getValueOptional("TRFTSTATUS"); //: (STRING, 3): A
Optional<String> stationid = advantajeRecord.getValueOptional("STATIONID"); //: (STRING, 3):
Optional<String> afixtype = advantajeRecord.getValueOptional("AFIXTYPE"); //: (STRING, 10):
Optional<Boolean> asleeping = advantajeRecord.getValueOptional("ASLEEPING"); //: (LOGICAL, 1): false
Optional<Boolean> discadvnot = advantajeRecord.getValueOptional("DISCADVNOT"); //: (LOGICAL, 1): false
Optional<String> subtype = advantajeRecord.getValueOptional("SUBTYPE"); //: (STRING, 10): LEQUITY
Optional<String> provaccexc = advantajeRecord.getValueOptional("PROVACCEXC"); //: (STRING, 10):
Optional<String> annexid = advantajeRecord.getValueOptional("ANNEXID"); //: (STRING, 15):
Optional<String> altacct = advantajeRecord.getValueOptional("ALTACCT"); //: (STRING, 10):
Optional<String> aautoop = advantajeRecord.getValueOptional("AAUTOOP"); //: (STRING, 2):
Optional<String> aoldid = advantajeRecord.getValueOptional("AOLDID"); //: (STRING, 10):
Optional<String> aprivaccount = advantajeRecord.getValueOptional("APRIVACCOUNT"); //: (STRING, 10):
Optional<String> oldheading1 = advantajeRecord.getValueOptional("OLDHEADING1"); //: (STRING, 40):
Optional<String> oldheading2 = advantajeRecord.getValueOptional("OLDHEADING2"); //: (STRING, 40):
Optional<Boolean> naeprior = advantajeRecord.getValueOptional("NAEPRIOR"); //: (LOGICAL, 1): [-]
Optional<Boolean> asynchro = advantajeRecord.getValueOptional("ASYNCHRO"); //: (LOGICAL, 1): true
Optional<String> apcnid = advantajeRecord.getValueOptional("APCNID"); //: (STRING, 10):
Optional<BigDecimal> avatecmpOptional = avatecmp.map(this::toBigDecimal);
Optional<BigDecimal> avatncmpOptional = avatncmp.map(this::toBigDecimal);
Optional<BigDecimal> avaticmpOptional = avaticmp.map(this::toBigDecimal);
Optional<BigDecimal> prcndchargesOptional = prcndcharges.map(this::toBigDecimal);
Optional<BigDecimal> prcprivateOptional = prcprivate.map(this::toBigDecimal);
BobAccount bobAccount = new BobAccount();
bobAccount.setAid(aid);
bobAccount.setaIsTitle(aistitle.orElse(null));
bobAccount.setHeading1(heading1.orElse(null));
bobAccount.setHeading2(heading2.orElse(null));
bobAccount.setLongHeading1(longheading1.orElse(null));
bobAccount.setLongHeading2(longheading2.orElse(null));
bobAccount.setSecondId(asecondid.orElse(null));
bobAccount.setFree(afree.orElse(null));
bobAccount.setaCat(acat.orElse(null));
bobAccount.setaIntCat(aintcat.orElse(null));
bobAccount.setaCatComm(acatcomm.orElse(null));
bobAccount.setAdbcd(adbcd.orElse(null));
bobAccount.setAiscost(aiscost.orElse(null));
bobAccount.setAvattype(avattype.orElse(null));
bobAccount.setAvatenat1(avatenat1.orElse(null));
bobAccount.setAvatenat2(avatenat2.orElse(null));
bobAccount.setAvatecmp(avatecmpOptional.orElse(null));
bobAccount.setAvatnnat1(avatnnat1.orElse(null));
bobAccount.setAvatnnat2(avatnnat2.orElse(null));
bobAccount.setAvatncmp(avatncmpOptional.orElse(null));
bobAccount.setAvatinat1(avatinat1.orElse(null));
bobAccount.setAvatinat2(avatinat2.orElse(null));
bobAccount.setAvaticmp(avaticmpOptional.orElse(null));
bobAccount.setAissummary(aissummary.orElse(null));
bobAccount.setAisstatus(aisstatus.orElse(null));
bobAccount.setAisreadonl(aisreadonl.orElse(null));
bobAccount.setAissecret(aissecret.orElse(null));
bobAccount.setVtravfa(vtravfa.orElse(null));
bobAccount.setAismatch(aismatch.orElse(null));
bobAccount.setDepacc(depacc.orElse(null));
bobAccount.setProvacc(provacc.orElse(null));
bobAccount.setHisintrastat(hisintrastat.orElse(null));
bobAccount.setAmatchno(amatchno.orElse(null));
bobAccount.setAbalance(abalance.orElse(null));
bobAccount.setArem(arem.orElse(null));
bobAccount.setAvatcas(avatcas.orElse(null));
bobAccount.setAcctsecondid(acctsecondid.orElse(null));
bobAccount.setAmemo(amemo.orElse(null));
bobAccount.setPrcndcharges(prcndchargesOptional.orElse(null));
bobAccount.setPrcprivate(prcprivateOptional.orElse(null));
bobAccount.setTypendcharges(typendcharges.orElse(null));
bobAccount.setCreatedby(createdby.orElse(null));
bobAccount.setCreatedon(createdon.orElse(null));
bobAccount.setModifiedby(modifiedby.orElse(null));
bobAccount.setModifiedon(modifiedon.orElse(null));
bobAccount.setTrftstatus(trftstatus.orElse(null));
bobAccount.setStationid(stationid.orElse(null));
bobAccount.setAfixtype(afixtype.orElse(null));
bobAccount.setAsleeping(asleeping.orElse(null));
bobAccount.setDiscadvnot(discadvnot.orElse(null));
bobAccount.setSubtype(subtype.orElse(null));
bobAccount.setProvaccexc(provaccexc.orElse(null));
bobAccount.setAnnexid(annexid.orElse(null));
bobAccount.setAltacct(altacct.orElse(null));
bobAccount.setAautoop(aautoop.orElse(null));
bobAccount.setAoldid(aoldid.orElse(null));
bobAccount.setAprivaccount(aprivaccount.orElse(null));
bobAccount.setOldheading1(oldheading1.orElse(null));
bobAccount.setOldheading2(oldheading2.orElse(null));
bobAccount.setNaeprior(naeprior.orElse(null));
bobAccount.setAsynchro(asynchro.orElse(null));
bobAccount.setApcnid(apcnid.orElse(null));
return bobAccount;
}
private BigDecimal toBigDecimal(Double aDouble) {
return BigDecimal.valueOf(aDouble);
}
}
| Valuya/bobthetinker | bobthetinker-core/src/main/java/be/valuya/bob/core/reader/BobAccountRecordReader.java | 3,727 | //: (STRING, 120): Eigen vermogen, voorzieningen voor risico's en kosten en schulden op meer dan een jaar | line_comment | nl | package be.valuya.bob.core.reader;
import be.valuya.advantaje.core.AdvantajeRecord;
import be.valuya.bob.core.domain.BobAccount;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;
public class BobAccountRecordReader {
public BobAccount readAccount(AdvantajeRecord advantajeRecord) {
String aid = advantajeRecord.getValue("AID"); //: (STRING, 10): 1
Optional<Boolean> aistitle = advantajeRecord.getValueOptional("AISTITLE"); //: (LOGICAL, 1): true
Optional<String> heading1 = advantajeRecord.getValueOptional("HEADING1"); //: (STRING, 40): Fonds propres
Optional<String> heading2 = advantajeRecord.getValueOptional("HEADING2"); //: (STRING, 40): Eigen vermogen
Optional<String> longheading1 = advantajeRecord.getValueOptional("LONGHEADING1"); //: (STRING, 120): Fonds propres, provisions pour risques et charges et dettes à plus d'un an
Optional<String> longheading2 = advantajeRecord.getValueOptional("LONGHEADING2"); //: (STRING,<SUF>
Optional<String> asecondid = advantajeRecord.getValueOptional("ASECONDID"); //: (STRING, 10):
Optional<String> afree = advantajeRecord.getValueOptional("AFREE"); //: (STRING, 40):
Optional<String> acat = advantajeRecord.getValueOptional("ACAT"); //: (STRING, 3):
Optional<String> aintcat = advantajeRecord.getValueOptional("AINTCAT"); //: (STRING, 10):
Optional<String> acatcomm = advantajeRecord.getValueOptional("ACATCOMM"); //: (STRING, 1):
Optional<String> adbcd = advantajeRecord.getValueOptional("ADBCD"); //: (STRING, 1): C
Optional<Boolean> aiscost = advantajeRecord.getValueOptional("AISCOST"); //: (LOGICAL, 1): [-]
Optional<String> avattype = advantajeRecord.getValueOptional("AVATTYPE"); //: (STRING, 1):
Optional<String> avatenat1 = advantajeRecord.getValueOptional("AVATENAT1"); //: (STRING, 3):
Optional<String> avatenat2 = advantajeRecord.getValueOptional("AVATENAT2"); //: (STRING, 3):
Optional<Double> avatecmp = advantajeRecord.getValueOptional("AVATECMP"); //: (DOUBLE, 8): [-]
Optional<String> avatnnat1 = advantajeRecord.getValueOptional("AVATNNAT1"); //: (STRING, 3):
Optional<String> avatnnat2 = advantajeRecord.getValueOptional("AVATNNAT2"); //: (STRING, 3):
Optional<Double> avatncmp = advantajeRecord.getValueOptional("AVATNCMP"); //: (DOUBLE, 8): [-]
Optional<String> avatinat1 = advantajeRecord.getValueOptional("AVATINAT1"); //: (STRING, 3):
Optional<String> avatinat2 = advantajeRecord.getValueOptional("AVATINAT2"); //: (STRING, 3):
Optional<Double> avaticmp = advantajeRecord.getValueOptional("AVATICMP"); //: (DOUBLE, 8): [-]
Optional<Boolean> aissummary = advantajeRecord.getValueOptional("AISSUMMARY"); //: (LOGICAL, 1): false
Optional<Boolean> aisstatus = advantajeRecord.getValueOptional("AISSTATUS"); //: (LOGICAL, 1): [-]
Optional<Boolean> aisreadonl = advantajeRecord.getValueOptional("AISREADONL"); //: (LOGICAL, 1): false
Optional<Boolean> aissecret = advantajeRecord.getValueOptional("AISSECRET"); //: (LOGICAL, 1): false
Optional<Boolean> vtravfa = advantajeRecord.getValueOptional("VTRAVFA"); //: (LOGICAL, 1): [-]
Optional<Boolean> aismatch = advantajeRecord.getValueOptional("AISMATCH"); //: (LOGICAL, 1): false
Optional<String> depacc = advantajeRecord.getValueOptional("DEPACC"); //: (STRING, 10):
Optional<String> provacc = advantajeRecord.getValueOptional("PROVACC"); //: (STRING, 10):
Optional<Boolean> hisintrastat = advantajeRecord.getValueOptional("HISINTRASTAT"); //: (LOGICAL, 1): [-]
Optional<Integer> amatchno = advantajeRecord.getValueOptional("AMATCHNO"); //: (INTEGER, 4): [-]
Optional<String> abalance = advantajeRecord.getValueOptional("ABALANCE"); //: (STRING, 10): LIABILIT
Optional<String> arem = advantajeRecord.getValueOptional("AREM"); //: (STRING, 35):
Optional<Boolean> avatcas = advantajeRecord.getValueOptional("AVATCAS"); //: (LOGICAL, 1): [-]
Optional<Boolean> acctsecondid = advantajeRecord.getValueOptional("ACCTSECONDID"); //: (LOGICAL, 1): [-]
Optional<byte[]> amemo = advantajeRecord.getValueOptional("AMEMO"); //: (BINARY, 9): [B@3cda1055
Optional<Double> prcndcharges = advantajeRecord.getValueOptional("PRCNDCHARGES"); //: (DOUBLE, 8): 0.0
Optional<Double> prcprivate = advantajeRecord.getValueOptional("PRCPRIVATE"); //: (DOUBLE, 8): 0.0
Optional<String> typendcharges = advantajeRecord.getValueOptional("TYPENDCHARGES"); //: (STRING, 12):
Optional<String> createdby = advantajeRecord.getValueOptional("CREATEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> createdon = advantajeRecord.getValueOptional("CREATEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> modifiedby = advantajeRecord.getValueOptional("MODIFIEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> modifiedon = advantajeRecord.getValueOptional("MODIFIEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> trftstatus = advantajeRecord.getValueOptional("TRFTSTATUS"); //: (STRING, 3): A
Optional<String> stationid = advantajeRecord.getValueOptional("STATIONID"); //: (STRING, 3):
Optional<String> afixtype = advantajeRecord.getValueOptional("AFIXTYPE"); //: (STRING, 10):
Optional<Boolean> asleeping = advantajeRecord.getValueOptional("ASLEEPING"); //: (LOGICAL, 1): false
Optional<Boolean> discadvnot = advantajeRecord.getValueOptional("DISCADVNOT"); //: (LOGICAL, 1): false
Optional<String> subtype = advantajeRecord.getValueOptional("SUBTYPE"); //: (STRING, 10): LEQUITY
Optional<String> provaccexc = advantajeRecord.getValueOptional("PROVACCEXC"); //: (STRING, 10):
Optional<String> annexid = advantajeRecord.getValueOptional("ANNEXID"); //: (STRING, 15):
Optional<String> altacct = advantajeRecord.getValueOptional("ALTACCT"); //: (STRING, 10):
Optional<String> aautoop = advantajeRecord.getValueOptional("AAUTOOP"); //: (STRING, 2):
Optional<String> aoldid = advantajeRecord.getValueOptional("AOLDID"); //: (STRING, 10):
Optional<String> aprivaccount = advantajeRecord.getValueOptional("APRIVACCOUNT"); //: (STRING, 10):
Optional<String> oldheading1 = advantajeRecord.getValueOptional("OLDHEADING1"); //: (STRING, 40):
Optional<String> oldheading2 = advantajeRecord.getValueOptional("OLDHEADING2"); //: (STRING, 40):
Optional<Boolean> naeprior = advantajeRecord.getValueOptional("NAEPRIOR"); //: (LOGICAL, 1): [-]
Optional<Boolean> asynchro = advantajeRecord.getValueOptional("ASYNCHRO"); //: (LOGICAL, 1): true
Optional<String> apcnid = advantajeRecord.getValueOptional("APCNID"); //: (STRING, 10):
Optional<BigDecimal> avatecmpOptional = avatecmp.map(this::toBigDecimal);
Optional<BigDecimal> avatncmpOptional = avatncmp.map(this::toBigDecimal);
Optional<BigDecimal> avaticmpOptional = avaticmp.map(this::toBigDecimal);
Optional<BigDecimal> prcndchargesOptional = prcndcharges.map(this::toBigDecimal);
Optional<BigDecimal> prcprivateOptional = prcprivate.map(this::toBigDecimal);
BobAccount bobAccount = new BobAccount();
bobAccount.setAid(aid);
bobAccount.setaIsTitle(aistitle.orElse(null));
bobAccount.setHeading1(heading1.orElse(null));
bobAccount.setHeading2(heading2.orElse(null));
bobAccount.setLongHeading1(longheading1.orElse(null));
bobAccount.setLongHeading2(longheading2.orElse(null));
bobAccount.setSecondId(asecondid.orElse(null));
bobAccount.setFree(afree.orElse(null));
bobAccount.setaCat(acat.orElse(null));
bobAccount.setaIntCat(aintcat.orElse(null));
bobAccount.setaCatComm(acatcomm.orElse(null));
bobAccount.setAdbcd(adbcd.orElse(null));
bobAccount.setAiscost(aiscost.orElse(null));
bobAccount.setAvattype(avattype.orElse(null));
bobAccount.setAvatenat1(avatenat1.orElse(null));
bobAccount.setAvatenat2(avatenat2.orElse(null));
bobAccount.setAvatecmp(avatecmpOptional.orElse(null));
bobAccount.setAvatnnat1(avatnnat1.orElse(null));
bobAccount.setAvatnnat2(avatnnat2.orElse(null));
bobAccount.setAvatncmp(avatncmpOptional.orElse(null));
bobAccount.setAvatinat1(avatinat1.orElse(null));
bobAccount.setAvatinat2(avatinat2.orElse(null));
bobAccount.setAvaticmp(avaticmpOptional.orElse(null));
bobAccount.setAissummary(aissummary.orElse(null));
bobAccount.setAisstatus(aisstatus.orElse(null));
bobAccount.setAisreadonl(aisreadonl.orElse(null));
bobAccount.setAissecret(aissecret.orElse(null));
bobAccount.setVtravfa(vtravfa.orElse(null));
bobAccount.setAismatch(aismatch.orElse(null));
bobAccount.setDepacc(depacc.orElse(null));
bobAccount.setProvacc(provacc.orElse(null));
bobAccount.setHisintrastat(hisintrastat.orElse(null));
bobAccount.setAmatchno(amatchno.orElse(null));
bobAccount.setAbalance(abalance.orElse(null));
bobAccount.setArem(arem.orElse(null));
bobAccount.setAvatcas(avatcas.orElse(null));
bobAccount.setAcctsecondid(acctsecondid.orElse(null));
bobAccount.setAmemo(amemo.orElse(null));
bobAccount.setPrcndcharges(prcndchargesOptional.orElse(null));
bobAccount.setPrcprivate(prcprivateOptional.orElse(null));
bobAccount.setTypendcharges(typendcharges.orElse(null));
bobAccount.setCreatedby(createdby.orElse(null));
bobAccount.setCreatedon(createdon.orElse(null));
bobAccount.setModifiedby(modifiedby.orElse(null));
bobAccount.setModifiedon(modifiedon.orElse(null));
bobAccount.setTrftstatus(trftstatus.orElse(null));
bobAccount.setStationid(stationid.orElse(null));
bobAccount.setAfixtype(afixtype.orElse(null));
bobAccount.setAsleeping(asleeping.orElse(null));
bobAccount.setDiscadvnot(discadvnot.orElse(null));
bobAccount.setSubtype(subtype.orElse(null));
bobAccount.setProvaccexc(provaccexc.orElse(null));
bobAccount.setAnnexid(annexid.orElse(null));
bobAccount.setAltacct(altacct.orElse(null));
bobAccount.setAautoop(aautoop.orElse(null));
bobAccount.setAoldid(aoldid.orElse(null));
bobAccount.setAprivaccount(aprivaccount.orElse(null));
bobAccount.setOldheading1(oldheading1.orElse(null));
bobAccount.setOldheading2(oldheading2.orElse(null));
bobAccount.setNaeprior(naeprior.orElse(null));
bobAccount.setAsynchro(asynchro.orElse(null));
bobAccount.setApcnid(apcnid.orElse(null));
return bobAccount;
}
private BigDecimal toBigDecimal(Double aDouble) {
return BigDecimal.valueOf(aDouble);
}
}
| false | 2,951 | 32 | 3,321 | 37 | 3,299 | 28 | 3,320 | 36 | 3,745 | 35 | false | false | false | false | false | true |
2,563 | 69191_0 | package nl.han;
import java.util.ArrayList;
public class Antwoordformulier {
private ArrayList<String> gegevenAntwoorden;
private int aantalGoed;
private Score score;
private Long startTijd;
public Antwoordformulier(){
gegevenAntwoorden = new ArrayList<>();
score = new Score();
startTijd = System.currentTimeMillis();
aantalGoed = 0;
}
public void vraagGoed(){ aantalGoed++;};
public void addAntwoord(String gegevenAntwoord){
gegevenAntwoorden.add(gegevenAntwoord);
}
public String getAntwoord(int i){
return gegevenAntwoorden.get(i);
}
public void maakWoord(String woord){
score.checkWoord(woord);
}
public int berekenScore(Berekening berekening){
var verstrekenTijd = System.currentTimeMillis() - startTijd;
//Bereken de score met berekening A
return score.berekenScore(berekening, verstrekenTijd, aantalGoed);
}
}
| diorcula/OOAD_casestudy-parola | source/src/nl/han/Antwoordformulier.java | 293 | //Bereken de score met berekening A | line_comment | nl | package nl.han;
import java.util.ArrayList;
public class Antwoordformulier {
private ArrayList<String> gegevenAntwoorden;
private int aantalGoed;
private Score score;
private Long startTijd;
public Antwoordformulier(){
gegevenAntwoorden = new ArrayList<>();
score = new Score();
startTijd = System.currentTimeMillis();
aantalGoed = 0;
}
public void vraagGoed(){ aantalGoed++;};
public void addAntwoord(String gegevenAntwoord){
gegevenAntwoorden.add(gegevenAntwoord);
}
public String getAntwoord(int i){
return gegevenAntwoorden.get(i);
}
public void maakWoord(String woord){
score.checkWoord(woord);
}
public int berekenScore(Berekening berekening){
var verstrekenTijd = System.currentTimeMillis() - startTijd;
//Bereken de<SUF>
return score.berekenScore(berekening, verstrekenTijd, aantalGoed);
}
}
| false | 242 | 10 | 275 | 11 | 254 | 9 | 275 | 11 | 302 | 11 | false | false | false | false | false | true |
1,433 | 39552_5 | package controller;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import model.Creature;
import view.Main;
import view.SceneManager;
import java.util.ArrayList;
import java.util.stream.Collectors;
/**Deze class is gelinkt met initiativeScene.fxml en geeft een scherm weer waar je creatures kan invoeren voor
* initiative, voordat je naar het echte initiative bijhoudt scherm gaat.
*
* @author R.Groot
*/
public class InitiativeController {
private final SceneManager SCENEMANAGER = Main.getSceneManager();
private ArrayList<Creature> initiative = new ArrayList<>();
//Checkboxxes
@FXML
private CheckBox lairActionCheckBox;
@FXML
private ListView<Creature> initiativeList;
@FXML
private TextField nameTextField;
@FXML
private TextField initiativeTextField;
@FXML
private TextField hpTextField;
@FXML
private TextField maxHPTextField;
@FXML
private TextField legResTextField;
@FXML
private TextField legActTextField;
@FXML
private VBox legendaryControls;
@FXML
private CheckBox legendaryCheckBox;
/**Deze methode wordt gestart wanneer naar dit scherm wordt gegaan. Momenteel doet deze methode niets, maar
* in de toekomst kunnen hier dingen aan toegevoegd worden als nodig.
*/
public void setup() {
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
}
/**Deze methode zet de initiativeList op volgorde van initiative (hoog naar laag).
*
*/
public void orderList() {
initiative.sort((c1, c2) -> Double.compare(c2.getInitiative(), c1.getInitiative()));
initiativeList.getItems().setAll(initiative);
}
public void handleLegendaryCheckBox(){
legendaryControls.setVisible(legendaryCheckBox.isSelected());
if(legendaryCheckBox.isSelected()) {
legendaryControls.setVisible(true);
legResTextField.setText(String.valueOf(0));
} else{
legendaryControls.setVisible(false);
}
}
/**Met deze methode wordt een creature toegevoegd aan de initiativeList.
*
*/
public void doAdd() {
if(validateCreature()) {
try {
double getInitiative = Double.parseDouble(initiativeTextField.getText());
int getHP = Integer.parseInt(hpTextField.getText());
int getMaxHP = Integer.parseInt(maxHPTextField.getText());
int legRes = 0;
int legAct = 0;
if (!legResTextField.getText().isEmpty()) {
legRes = Integer.parseInt(legResTextField.getText());
}
if (!legActTextField.getText().isEmpty()) {
legAct = Integer.parseInt(legActTextField.getText());
}
initiative.add(new Creature(nameTextField.getText(), getInitiative, getHP, getMaxHP, legRes, legAct));
nameTextField.setText("");
initiativeTextField.setText("");
hpTextField.setText("");
maxHPTextField.setText("");
legResTextField.setText("0");
legActTextField.setText("0");
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
orderList();
} catch (NumberFormatException exception) {
showAlert("Initiative and HP must be valid numbers!");
}
}
}
/**Met deze methode wordt de gebruiker naar de initiativeTracker scherm gebracht.
*
*/
public void doTracker() {
if(initiative == null) {
showAlert("Your initiative list is empty!");
}
SCENEMANAGER.showInitiativeTrackerScene(initiative, lairActionCheckBox.isSelected());
}
/**Met deze methode wordt een creature uit de initiativeList gehaald.
*
*/
public void doDelete() {
Creature selectedCreature = initiativeList.getSelectionModel().getSelectedItem();
if (selectedCreature != null) {
initiative.remove(selectedCreature);
initiativeList.getItems().remove(selectedCreature);
}
}
/**Met deze methode wordt een creature die de gebruiker probeert toe te voegen gevallideerd op een aantal
* punten. De creature kan alleen toegevoegd worden als het overal aan voldoet.
*
* @return: true als het overal aan voldoet.
*/
public boolean validateCreature() {
String name = nameTextField.getText();
String initiativeText = initiativeTextField.getText();
String hpText = hpTextField.getText();
String maxHPText = maxHPTextField.getText();
if (name.isEmpty() || initiativeText.isEmpty() || hpText.isEmpty() || maxHPText.isEmpty()) {
showAlert("All fields are required!");
return false;
}
if(initiative != null) {
ArrayList<String> names = initiative.stream().map(Creature::getName).collect(Collectors.toCollection(ArrayList::new));
for (String creatureName : names) {
if(name.equalsIgnoreCase(creatureName)) {
showAlert("This name is already in the initiative list!");
return false;
}
}
}
if (Integer.parseInt(hpText) < 0 || Integer.parseInt(maxHPText) < 0) {
showAlert("You can't add a creature with less then 0 (max) HP.");
return false;
}
if(nameTextField.getText().length() > 20) {
showAlert("The creature's name can't be more then 20 characters long.");
return false;
}
if (Integer.parseInt(hpText) > Integer.parseInt(maxHPText)) {
showAlert("HP can't be higher than max HP!");
return false;
}
return true;
}
public void lowerLegRes(){
int newLegRes = Integer.parseInt(legResTextField.getText()) - 1;
if(newLegRes < 0) {
showAlert("A creature can't have less then 0 legendary resistances!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void addLegRes(){
if(legResTextField.getText().isEmpty()) {
legResTextField.setText("0");
}
int newLegRes = Integer.parseInt(legResTextField.getText()) + 1;
if(newLegRes > 5) {
showAlert("A creature can't have more then 5 legendary resistances in this program!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void lowerLegAct(){
int newLegAct = Integer.parseInt(legActTextField.getText()) - 1;
if(newLegAct < 0) {
showAlert("A creature can't have less then 0 legendary actions!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void addLegAct(){
if(legActTextField.getText().isEmpty()) {
legActTextField.setText("0");
}
int newLegAct = Integer.parseInt(legActTextField.getText()) + 1;
if(newLegAct > 5) {
showAlert("A creature can't have more then 5 legendary actions in this program!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void doMenu(){
SCENEMANAGER.showMenuScene();
}
/**Geeft een error message als deze methode wordt aangeroepen.
*
* @param message: het bericht dat weergegeven wordt in de error message.
*/
public void showAlert(String message) {
Alert errorMessage = new Alert(Alert.AlertType.ERROR);
errorMessage.setContentText(message);
errorMessage.show();
}
} | Rakky88/InitiativeTracker | src/main/java/controller/InitiativeController.java | 2,231 | /**Met deze methode wordt een creature uit de initiativeList gehaald.
*
*/ | block_comment | nl | package controller;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import model.Creature;
import view.Main;
import view.SceneManager;
import java.util.ArrayList;
import java.util.stream.Collectors;
/**Deze class is gelinkt met initiativeScene.fxml en geeft een scherm weer waar je creatures kan invoeren voor
* initiative, voordat je naar het echte initiative bijhoudt scherm gaat.
*
* @author R.Groot
*/
public class InitiativeController {
private final SceneManager SCENEMANAGER = Main.getSceneManager();
private ArrayList<Creature> initiative = new ArrayList<>();
//Checkboxxes
@FXML
private CheckBox lairActionCheckBox;
@FXML
private ListView<Creature> initiativeList;
@FXML
private TextField nameTextField;
@FXML
private TextField initiativeTextField;
@FXML
private TextField hpTextField;
@FXML
private TextField maxHPTextField;
@FXML
private TextField legResTextField;
@FXML
private TextField legActTextField;
@FXML
private VBox legendaryControls;
@FXML
private CheckBox legendaryCheckBox;
/**Deze methode wordt gestart wanneer naar dit scherm wordt gegaan. Momenteel doet deze methode niets, maar
* in de toekomst kunnen hier dingen aan toegevoegd worden als nodig.
*/
public void setup() {
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
}
/**Deze methode zet de initiativeList op volgorde van initiative (hoog naar laag).
*
*/
public void orderList() {
initiative.sort((c1, c2) -> Double.compare(c2.getInitiative(), c1.getInitiative()));
initiativeList.getItems().setAll(initiative);
}
public void handleLegendaryCheckBox(){
legendaryControls.setVisible(legendaryCheckBox.isSelected());
if(legendaryCheckBox.isSelected()) {
legendaryControls.setVisible(true);
legResTextField.setText(String.valueOf(0));
} else{
legendaryControls.setVisible(false);
}
}
/**Met deze methode wordt een creature toegevoegd aan de initiativeList.
*
*/
public void doAdd() {
if(validateCreature()) {
try {
double getInitiative = Double.parseDouble(initiativeTextField.getText());
int getHP = Integer.parseInt(hpTextField.getText());
int getMaxHP = Integer.parseInt(maxHPTextField.getText());
int legRes = 0;
int legAct = 0;
if (!legResTextField.getText().isEmpty()) {
legRes = Integer.parseInt(legResTextField.getText());
}
if (!legActTextField.getText().isEmpty()) {
legAct = Integer.parseInt(legActTextField.getText());
}
initiative.add(new Creature(nameTextField.getText(), getInitiative, getHP, getMaxHP, legRes, legAct));
nameTextField.setText("");
initiativeTextField.setText("");
hpTextField.setText("");
maxHPTextField.setText("");
legResTextField.setText("0");
legActTextField.setText("0");
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
orderList();
} catch (NumberFormatException exception) {
showAlert("Initiative and HP must be valid numbers!");
}
}
}
/**Met deze methode wordt de gebruiker naar de initiativeTracker scherm gebracht.
*
*/
public void doTracker() {
if(initiative == null) {
showAlert("Your initiative list is empty!");
}
SCENEMANAGER.showInitiativeTrackerScene(initiative, lairActionCheckBox.isSelected());
}
/**Met deze methode<SUF>*/
public void doDelete() {
Creature selectedCreature = initiativeList.getSelectionModel().getSelectedItem();
if (selectedCreature != null) {
initiative.remove(selectedCreature);
initiativeList.getItems().remove(selectedCreature);
}
}
/**Met deze methode wordt een creature die de gebruiker probeert toe te voegen gevallideerd op een aantal
* punten. De creature kan alleen toegevoegd worden als het overal aan voldoet.
*
* @return: true als het overal aan voldoet.
*/
public boolean validateCreature() {
String name = nameTextField.getText();
String initiativeText = initiativeTextField.getText();
String hpText = hpTextField.getText();
String maxHPText = maxHPTextField.getText();
if (name.isEmpty() || initiativeText.isEmpty() || hpText.isEmpty() || maxHPText.isEmpty()) {
showAlert("All fields are required!");
return false;
}
if(initiative != null) {
ArrayList<String> names = initiative.stream().map(Creature::getName).collect(Collectors.toCollection(ArrayList::new));
for (String creatureName : names) {
if(name.equalsIgnoreCase(creatureName)) {
showAlert("This name is already in the initiative list!");
return false;
}
}
}
if (Integer.parseInt(hpText) < 0 || Integer.parseInt(maxHPText) < 0) {
showAlert("You can't add a creature with less then 0 (max) HP.");
return false;
}
if(nameTextField.getText().length() > 20) {
showAlert("The creature's name can't be more then 20 characters long.");
return false;
}
if (Integer.parseInt(hpText) > Integer.parseInt(maxHPText)) {
showAlert("HP can't be higher than max HP!");
return false;
}
return true;
}
public void lowerLegRes(){
int newLegRes = Integer.parseInt(legResTextField.getText()) - 1;
if(newLegRes < 0) {
showAlert("A creature can't have less then 0 legendary resistances!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void addLegRes(){
if(legResTextField.getText().isEmpty()) {
legResTextField.setText("0");
}
int newLegRes = Integer.parseInt(legResTextField.getText()) + 1;
if(newLegRes > 5) {
showAlert("A creature can't have more then 5 legendary resistances in this program!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void lowerLegAct(){
int newLegAct = Integer.parseInt(legActTextField.getText()) - 1;
if(newLegAct < 0) {
showAlert("A creature can't have less then 0 legendary actions!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void addLegAct(){
if(legActTextField.getText().isEmpty()) {
legActTextField.setText("0");
}
int newLegAct = Integer.parseInt(legActTextField.getText()) + 1;
if(newLegAct > 5) {
showAlert("A creature can't have more then 5 legendary actions in this program!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void doMenu(){
SCENEMANAGER.showMenuScene();
}
/**Geeft een error message als deze methode wordt aangeroepen.
*
* @param message: het bericht dat weergegeven wordt in de error message.
*/
public void showAlert(String message) {
Alert errorMessage = new Alert(Alert.AlertType.ERROR);
errorMessage.setContentText(message);
errorMessage.show();
}
} | false | 1,624 | 20 | 1,850 | 21 | 1,885 | 20 | 1,850 | 21 | 2,166 | 24 | false | false | false | false | false | true |
2,114 | 58011_1 | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LinearRing;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import org.geotools.data.dxf.parser.DXFParseException;
import org.geotools.data.dxf.parser.DXFUnivers;
/** @source $URL$ */
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness,
DXFExtendedData extData) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
_extendedData = extData;
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers)
throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
DXFExtendedData _extData = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor alle waarden van type
br.reset();
doLoop = false;
break;
case X_1: // "10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: // "2"
name = cvp.getStringValue();
break;
case LAYER_NAME: // "8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: // "6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: // "62"
c = cvp.getShortValue();
break;
case INT_1: // "70"
flag = cvp.getShortValue();
break;
case VISIBILITY: // "60"
visibility = cvp.getShortValue();
break;
case XDATA_APPLICATION_NAME:
String appName = cvp.getStringValue();
_extData = DXFExtendedData.getExtendedData(br);
_extData.setAppName(appName);
break;
default:
break;
}
}
DXFLwPolyline e =
new DXFLwPolyline(
name,
flag,
c,
l,
lv,
visibility,
lineType,
DXFTables.defaultThickness,
_extData);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices)
throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
case X_1: // "10"
// check of vorig vertex opgeslagen kan worden
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: // "20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: // "42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */
return rotateAndPlace(lc.toArray(new Coordinate[] {}));
}
public String toString(
String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(
getName(),
_flag,
theVertices.size(),
getColor(),
(isVisible() ? 0 : 1),
getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
| apollo-mapping/geotools | modules/unsupported/dxf/src/main/java/org/geotools/data/dxf/entities/DXFLwPolyline.java | 3,599 | // geldt voor alle waarden van type | line_comment | nl | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LinearRing;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import org.geotools.data.dxf.parser.DXFParseException;
import org.geotools.data.dxf.parser.DXFUnivers;
/** @source $URL$ */
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness,
DXFExtendedData extData) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
_extendedData = extData;
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers)
throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
DXFExtendedData _extData = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor<SUF>
br.reset();
doLoop = false;
break;
case X_1: // "10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: // "2"
name = cvp.getStringValue();
break;
case LAYER_NAME: // "8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: // "6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: // "62"
c = cvp.getShortValue();
break;
case INT_1: // "70"
flag = cvp.getShortValue();
break;
case VISIBILITY: // "60"
visibility = cvp.getShortValue();
break;
case XDATA_APPLICATION_NAME:
String appName = cvp.getStringValue();
_extData = DXFExtendedData.getExtendedData(br);
_extData.setAppName(appName);
break;
default:
break;
}
}
DXFLwPolyline e =
new DXFLwPolyline(
name,
flag,
c,
l,
lv,
visibility,
lineType,
DXFTables.defaultThickness,
_extData);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices)
throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
case X_1: // "10"
// check of vorig vertex opgeslagen kan worden
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: // "20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: // "42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */
return rotateAndPlace(lc.toArray(new Coordinate[] {}));
}
public String toString(
String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(
getName(),
_flag,
theVertices.size(),
getColor(),
(isVisible() ? 0 : 1),
getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
| false | 2,668 | 9 | 2,901 | 10 | 3,156 | 8 | 2,901 | 10 | 3,585 | 9 | false | false | false | false | false | true |
1,802 | 17171_2 | package be.ucll.java.ent;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@WebServlet("/inschrijving")
public class InschrijvingServlet extends HttpServlet {
// private static final String COOKIE_STUDENT = "StudentInfo";
private String stud_name = "";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
/*
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie: cookies){
if (cookie != null && cookie.getName() != null && cookie.getName().trim().equalsIgnoreCase(COOKIE_STUDENT)) {
String tmp = cookie.getValue();
if (tmp != null && tmp.trim().length() > 0) {
stud_name = URLDecoder.decode(tmp.trim(), StandardCharsets.UTF_8.toString());
}
}
}
} else {
this.getServletContext().log("No cookies found");
}
*/
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println("<title>Inschrijving</title>");
pw.println("</head>");
pw.println("<body>");
pw.println(" <p><h3>Schrijf u in voor het opleidingsonderdeel 'Java Enterprise'.</h3>");
pw.println(" <form action='" + request.getContextPath() + request.getServletPath() + "' method='post'>");
pw.println(" Student naam: <input type='text' name='stud_name' size='50' maxlength='50' value='" + stud_name + "' /><br/><br/> ");
pw.println(" <input type='submit' value='Inschrijven'/>");
pw.println(" </form></p>");
pw.println("</body>");
pw.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
stud_name = request.getParameter("stud_name");
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println(" <title>Hello Servlets</title>");
pw.println("</head>");
pw.println("<body>");
if (stud_name != null && stud_name.trim().length() > 0) {
pw.println(" <p><h3>Bedankt " + stud_name + ". U bent ingeschreven</h3>");
/*
// Create a cookie. Een 'cookie' kan zeer weinig info bevatten en de inhoud die je wil opslaan hou je best onder de 4000 bytes.
String encodedStr = URLEncoder.encode(stud_name, StandardCharsets.UTF_8.toString());
Cookie cookie = new Cookie(COOKIE_STUDENT, encodedStr);
cookie.setMaxAge(60 * 60 * 24 * 7); // Seconds, 60 * 60 * 24 * 7 = 1 week
response.addCookie(cookie);
this.getServletContext().log("Added cookie with name: " + COOKIE_STUDENT + ", value: " + encodedStr);
*/
} else {
pw.println(" <p><h3>De naam ontbreekt. U bent niet ingeschreven</h3>");
}
pw.println(" <br/><a href='." + request.getServletPath() + "'>Keer terug naar inschrijving</a>");
pw.println(" <br/><br/>Session Id: " + request.getSession().getId());
pw.println("</body>");
pw.println("</html>");
}
}
} | UcllJavaEnterprise/first-servlet | src/main/java/be/ucll/java/ent/InschrijvingServlet.java | 1,157 | /*
// Create a cookie. Een 'cookie' kan zeer weinig info bevatten en de inhoud die je wil opslaan hou je best onder de 4000 bytes.
String encodedStr = URLEncoder.encode(stud_name, StandardCharsets.UTF_8.toString());
Cookie cookie = new Cookie(COOKIE_STUDENT, encodedStr);
cookie.setMaxAge(60 * 60 * 24 * 7); // Seconds, 60 * 60 * 24 * 7 = 1 week
response.addCookie(cookie);
this.getServletContext().log("Added cookie with name: " + COOKIE_STUDENT + ", value: " + encodedStr);
*/ | block_comment | nl | package be.ucll.java.ent;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@WebServlet("/inschrijving")
public class InschrijvingServlet extends HttpServlet {
// private static final String COOKIE_STUDENT = "StudentInfo";
private String stud_name = "";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
/*
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie: cookies){
if (cookie != null && cookie.getName() != null && cookie.getName().trim().equalsIgnoreCase(COOKIE_STUDENT)) {
String tmp = cookie.getValue();
if (tmp != null && tmp.trim().length() > 0) {
stud_name = URLDecoder.decode(tmp.trim(), StandardCharsets.UTF_8.toString());
}
}
}
} else {
this.getServletContext().log("No cookies found");
}
*/
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println("<title>Inschrijving</title>");
pw.println("</head>");
pw.println("<body>");
pw.println(" <p><h3>Schrijf u in voor het opleidingsonderdeel 'Java Enterprise'.</h3>");
pw.println(" <form action='" + request.getContextPath() + request.getServletPath() + "' method='post'>");
pw.println(" Student naam: <input type='text' name='stud_name' size='50' maxlength='50' value='" + stud_name + "' /><br/><br/> ");
pw.println(" <input type='submit' value='Inschrijven'/>");
pw.println(" </form></p>");
pw.println("</body>");
pw.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
stud_name = request.getParameter("stud_name");
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println(" <title>Hello Servlets</title>");
pw.println("</head>");
pw.println("<body>");
if (stud_name != null && stud_name.trim().length() > 0) {
pw.println(" <p><h3>Bedankt " + stud_name + ". U bent ingeschreven</h3>");
/*
// Create a cookie.<SUF>*/
} else {
pw.println(" <p><h3>De naam ontbreekt. U bent niet ingeschreven</h3>");
}
pw.println(" <br/><a href='." + request.getServletPath() + "'>Keer terug naar inschrijving</a>");
pw.println(" <br/><br/>Session Id: " + request.getSession().getId());
pw.println("</body>");
pw.println("</html>");
}
}
} | false | 848 | 152 | 986 | 167 | 993 | 159 | 986 | 167 | 1,170 | 185 | false | false | false | false | false | true |
1,752 | 10815_0 | package domain;
import java.util.ArrayList;
public class BinaryMinHeap<E extends Comparable<E>> {
private ArrayList<E> values;
private boolean isEmpty() {
return values == null || values.size() == 0;
}
public void print() {
if (this.isEmpty())
System.out.println("De heap is leeg");
else
System.out.println(values);
}
public E getMin() {
if (this.isEmpty())
throw new IllegalStateException("Kan niet zoeken in een lege heap");
//TO DO zie oefening 3
return null;
}
public boolean addValue(E value) {
// geen null toevoegen aan de heap
if (value == null) throw new IllegalArgumentException();
// indien de heap leeg is: eerst initialiseren
if (this.isEmpty())
values = new ArrayList<E>();
values.add(value);//achteraan toevoegen
this.bubbleUp();//bubbleUp vanaf de laatste zie slides theorie
return true;
}
private void bubbleUp() {
//TO DO : oefening 4
}
public E removeSmallest() {
if (this.isEmpty())
throw new IllegalStateException("Kan niets verwijderen uit een lege boom");
E res = this.getMin();// res bevat de kleinste = eerste element van de lijst
this.values.set(0, this.values.get(this.values.size() - 1));// verwissel eerste met de laatste
this.values.remove(this.values.size() - 1); // verwijder de laatste
this.bubbleDown(); // bubble down van eerste naar beneden zie theorie
return res;
}
private void bubbleDown() {
// TODO zie oefening 5
}
public ArrayList<E> getPath(E value) {
// TODO zie oefening 6;
return null;
}
}
| TomEversdijk/Bomen_en_grafen_oefeningen | week05_Heap/src/domain/BinaryMinHeap.java | 498 | //TO DO zie oefening 3 | line_comment | nl | package domain;
import java.util.ArrayList;
public class BinaryMinHeap<E extends Comparable<E>> {
private ArrayList<E> values;
private boolean isEmpty() {
return values == null || values.size() == 0;
}
public void print() {
if (this.isEmpty())
System.out.println("De heap is leeg");
else
System.out.println(values);
}
public E getMin() {
if (this.isEmpty())
throw new IllegalStateException("Kan niet zoeken in een lege heap");
//TO DO<SUF>
return null;
}
public boolean addValue(E value) {
// geen null toevoegen aan de heap
if (value == null) throw new IllegalArgumentException();
// indien de heap leeg is: eerst initialiseren
if (this.isEmpty())
values = new ArrayList<E>();
values.add(value);//achteraan toevoegen
this.bubbleUp();//bubbleUp vanaf de laatste zie slides theorie
return true;
}
private void bubbleUp() {
//TO DO : oefening 4
}
public E removeSmallest() {
if (this.isEmpty())
throw new IllegalStateException("Kan niets verwijderen uit een lege boom");
E res = this.getMin();// res bevat de kleinste = eerste element van de lijst
this.values.set(0, this.values.get(this.values.size() - 1));// verwissel eerste met de laatste
this.values.remove(this.values.size() - 1); // verwijder de laatste
this.bubbleDown(); // bubble down van eerste naar beneden zie theorie
return res;
}
private void bubbleDown() {
// TODO zie oefening 5
}
public ArrayList<E> getPath(E value) {
// TODO zie oefening 6;
return null;
}
}
| false | 414 | 9 | 468 | 10 | 463 | 8 | 468 | 10 | 522 | 9 | false | false | false | false | false | true |
1,680 | 8380_0 | /*
* CBM interface
* Dit document beschrijft de interface van CBM die ten behoeve van Melvin beschikbaar wordt gesteld. . </br></br> De API moet worden uitgevraagd met een token. De token kan met een gebruikersnaam en wachtwoord verkregen worden. De token is tijdelijk geldig, daarna kan een nieuwe token opgevraagd worden. </br></br> De Geo-inputparameters moeten matchen op de door CBM gebruikte OSM-versie.
*
* OpenAPI spec version: 0.1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client;
import java.io.IOException;
import java.util.Map;
import java.util.List;
/**
* Callback for asynchronous API call.
*
* @param <T> The return type
*/
public interface ApiCallback<T> {
/**
* This is called when the API call fails.
*
* @param e The exception causing the failure
* @param statusCode Status code of the response if available, otherwise it would be 0
* @param responseHeaders Headers of the response if available, otherwise it would be null
*/
void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API call succeeded.
*
* @param result The result deserialized from response
* @param statusCode Status code of the response
* @param responseHeaders Headers of the response
*/
void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API upload processing.
*
* @param bytesWritten bytes Written
* @param contentLength content length of request body
* @param done write end
*/
void onUploadProgress(long bytesWritten, long contentLength, boolean done);
/**
* This is called when the API downlond processing.
*
* @param bytesRead bytes Read
* @param contentLength content lenngth of the response
* @param done Read end
*/
void onDownloadProgress(long bytesRead, long contentLength, boolean done);
}
| TOMP-WG/TOMP-REF | tomp_meta/src/main/java/io/swagger/client/ApiCallback.java | 580 | /*
* CBM interface
* Dit document beschrijft de interface van CBM die ten behoeve van Melvin beschikbaar wordt gesteld. . </br></br> De API moet worden uitgevraagd met een token. De token kan met een gebruikersnaam en wachtwoord verkregen worden. De token is tijdelijk geldig, daarna kan een nieuwe token opgevraagd worden. </br></br> De Geo-inputparameters moeten matchen op de door CBM gebruikte OSM-versie.
*
* OpenAPI spec version: 0.1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/ | block_comment | nl | /*
* CBM interface
<SUF>*/
package io.swagger.client;
import java.io.IOException;
import java.util.Map;
import java.util.List;
/**
* Callback for asynchronous API call.
*
* @param <T> The return type
*/
public interface ApiCallback<T> {
/**
* This is called when the API call fails.
*
* @param e The exception causing the failure
* @param statusCode Status code of the response if available, otherwise it would be 0
* @param responseHeaders Headers of the response if available, otherwise it would be null
*/
void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API call succeeded.
*
* @param result The result deserialized from response
* @param statusCode Status code of the response
* @param responseHeaders Headers of the response
*/
void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API upload processing.
*
* @param bytesWritten bytes Written
* @param contentLength content length of request body
* @param done write end
*/
void onUploadProgress(long bytesWritten, long contentLength, boolean done);
/**
* This is called when the API downlond processing.
*
* @param bytesRead bytes Read
* @param contentLength content lenngth of the response
* @param done Read end
*/
void onDownloadProgress(long bytesRead, long contentLength, boolean done);
}
| false | 499 | 171 | 542 | 192 | 541 | 164 | 542 | 192 | 596 | 195 | true | true | true | true | true | false |
4,689 | 22086_6 | import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String[] args) {
//Initialiseer een nieuwe JFrame en configureer de basics,
//dus size en de ON_CLOSE operation.
JFrame frame = new JFrame("Workshop frame");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Aanmaak van drie JPanels
JPanel flowLayoutPanel = new JPanel();
JPanel boxLayoutPanel = new JPanel();
JPanel gridLayoutPanel = new JPanel();
//Zet voor iedere panel een aparte layout manager;
//FlowLayout voor links naar rechts, BoxLayout voor x-as of y-as, GridLayout voor raster.
//Let op dat sommige layout managers dus parameters mee moeten krijgen in hun constructors.
flowLayoutPanel.setLayout(new FlowLayout());
boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel, BoxLayout.Y_AXIS));
gridLayoutPanel.setLayout(new GridLayout(3, 2));
//Drie arrays van knoppen, 1 voor iedere panel.
JButton[] buttons1 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons2 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons3 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
//Knoppen toevoegen aan de panels.
for (JButton b : buttons1){
flowLayoutPanel.add(b);
}
for (JButton b : buttons2){
boxLayoutPanel.add(b);
}
for (JButton b : buttons3){
gridLayoutPanel.add(b);
}
//Maak een main panel aan om alle andere panels in onder te brengen, inclusief layout manager.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//Voeg de layout panels toe aan de main panel. Let op, volgorde maakt uit.
mainPanel.add(flowLayoutPanel);
mainPanel.add(boxLayoutPanel);
mainPanel.add(gridLayoutPanel);
//Voeg mainpanel toe aan de JFrame en maak de JFrame visible.
frame.add(mainPanel);
frame.setVisible(true);
}
} | wennhao/project3-4 | guiold_OUTDATED/gui.java | 765 | //Drie arrays van knoppen, 1 voor iedere panel. | line_comment | nl | import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String[] args) {
//Initialiseer een nieuwe JFrame en configureer de basics,
//dus size en de ON_CLOSE operation.
JFrame frame = new JFrame("Workshop frame");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Aanmaak van drie JPanels
JPanel flowLayoutPanel = new JPanel();
JPanel boxLayoutPanel = new JPanel();
JPanel gridLayoutPanel = new JPanel();
//Zet voor iedere panel een aparte layout manager;
//FlowLayout voor links naar rechts, BoxLayout voor x-as of y-as, GridLayout voor raster.
//Let op dat sommige layout managers dus parameters mee moeten krijgen in hun constructors.
flowLayoutPanel.setLayout(new FlowLayout());
boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel, BoxLayout.Y_AXIS));
gridLayoutPanel.setLayout(new GridLayout(3, 2));
//Drie arrays<SUF>
JButton[] buttons1 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons2 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons3 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
//Knoppen toevoegen aan de panels.
for (JButton b : buttons1){
flowLayoutPanel.add(b);
}
for (JButton b : buttons2){
boxLayoutPanel.add(b);
}
for (JButton b : buttons3){
gridLayoutPanel.add(b);
}
//Maak een main panel aan om alle andere panels in onder te brengen, inclusief layout manager.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//Voeg de layout panels toe aan de main panel. Let op, volgorde maakt uit.
mainPanel.add(flowLayoutPanel);
mainPanel.add(boxLayoutPanel);
mainPanel.add(gridLayoutPanel);
//Voeg mainpanel toe aan de JFrame en maak de JFrame visible.
frame.add(mainPanel);
frame.setVisible(true);
}
} | false | 572 | 16 | 636 | 17 | 666 | 14 | 636 | 17 | 778 | 17 | false | false | false | false | false | true |
1,477 | 79324_11 | package framework.database;_x000D_
_x000D_
import java.lang.reflect.Constructor;_x000D_
import java.sql.Connection;_x000D_
import java.sql.Driver;_x000D_
import java.sql.DriverManager;_x000D_
import java.sql.PreparedStatement;_x000D_
import java.sql.ResultSet;_x000D_
import java.sql.ResultSetMetaData;_x000D_
import java.sql.SQLException;_x000D_
import java.util.ArrayList;_x000D_
import java.util.Enumeration;_x000D_
import java.util.HashMap;_x000D_
_x000D_
public class Database {_x000D_
_x000D_
protected Connection conn;_x000D_
protected String connectionUrl;_x000D_
protected String username;_x000D_
protected String password; // TODO: kijken in hoeverre het haalbaar is het wachtwoord hier weg te laten_x000D_
_x000D_
@SuppressWarnings({ "unchecked", "rawtypes" })_x000D_
public Database(String driver, String connectionUrl, String username, String password)_x000D_
{_x000D_
try {_x000D_
// Kijken of de driver bestaat_x000D_
Class DriverClass = Class.forName(driver);_x000D_
_x000D_
Constructor constructorClass = DriverClass.getConstructor();_x000D_
Driver dbDriver = (Driver) constructorClass.newInstance();_x000D_
DriverManager.registerDriver(dbDriver);_x000D_
_x000D_
} catch (Exception e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
_x000D_
this.connectionUrl = connectionUrl;_x000D_
this.username = username;_x000D_
this.password = password;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Maakt connectie naar de databank_x000D_
* _x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public Connection getConnection() throws SQLException_x000D_
{_x000D_
if(this.conn == null || this.conn.isClosed())_x000D_
this.conn = DriverManager.getConnection(connectionUrl,username,password);_x000D_
_x000D_
return this.conn;_x000D_
}_x000D_
_x000D_
public PreparedStatement prepareStatement(String query) throws SQLException_x000D_
{_x000D_
return conn.prepareStatement(query);_x000D_
}_x000D_
_x000D_
public NamedParamStatement namedParamStatement(String query) throws SQLException_x000D_
{_x000D_
return new NamedParamStatement(getConnection(), query);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Geeft alle rows van een result in een handige ArrayList_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public ArrayList<DatabaseRow> getAllRows(ResultSet res) throws SQLException_x000D_
{_x000D_
ArrayList<DatabaseRow> rows = new ArrayList<DatabaseRow>();_x000D_
_x000D_
// Cursor naar -1 zetten._x000D_
res.beforeFirst();_x000D_
_x000D_
// Kijken of er op index 0 iets zit._x000D_
if(res.next()){_x000D_
// Blijkbaar zijn er rows_x000D_
// Cursor terug naar -1 zetten alle rows aflopen._x000D_
res.beforeFirst();_x000D_
_x000D_
// Pas als we aan de EOL zitten van de resultset stoppen we_x000D_
while(!res.isAfterLast()) {_x000D_
// Row ophalen en toevoegen aan Arraylist_x000D_
DatabaseRow row = this.getRow(res);_x000D_
if(row != null)_x000D_
rows.add(row);_x000D_
}_x000D_
}_x000D_
_x000D_
res.close();_x000D_
_x000D_
return rows;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Haalt de volgende row uit een resultset een geeft dit terug in een Hashmap<Kolomnaam,Object>_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public DatabaseRow getRow(ResultSet res) throws SQLException_x000D_
{_x000D_
HashMap<String, Object> row = new HashMap<String, Object>();_x000D_
_x000D_
// MetaData is nodig, daarin zit het aantal kolommen en hoe ze heten_x000D_
ResultSetMetaData metaData = res.getMetaData();_x000D_
int columnCount = metaData.getColumnCount();_x000D_
_x000D_
ArrayList<String> columns = new ArrayList<String>();_x000D_
_x000D_
// Alle kolommen aflopen en hun naam bijhouden in de Array._x000D_
for (int columnNr=1; columnNr<=columnCount; columnNr++){_x000D_
String columnName = metaData.getColumnName(columnNr);_x000D_
columns.add(columnName);_x000D_
}_x000D_
_x000D_
// Springen naar de volgende row_x000D_
if (res.next()){_x000D_
// Alle kolommen in deze row aflopen_x000D_
for (String columnName:columns) {_x000D_
// De waarde van deze kolom ophalen_x000D_
Object rowData = res.getObject(columnName);_x000D_
// Toevoegen aan de hashmap_x000D_
row.put(columnName,rowData);_x000D_
}_x000D_
}_x000D_
_x000D_
if(row.size() <= 0)_x000D_
return null;_x000D_
_x000D_
return new DatabaseRow(row);_x000D_
}_x000D_
_x000D_
public void closeConnection() {_x000D_
try {_x000D_
conn.close();_x000D_
_x000D_
// This manually deregisters JDBC driver, which prevents Tomcat 7_x000D_
// from complaining about memory leaks wrto this class_x000D_
// http://stackoverflow.com/a/5315467/1306509_x000D_
Enumeration<Driver> drivers = DriverManager.getDrivers();_x000D_
while (drivers.hasMoreElements()) {_x000D_
Driver driver = drivers.nextElement();_x000D_
DriverManager.deregisterDriver(driver);_x000D_
}_x000D_
_x000D_
} catch (SQLException e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
}_x000D_
| RobinHoutevelts/DynwebFramework | src/java/framework/database/Database.java | 1,400 | // MetaData is nodig, daarin zit het aantal kolommen en hoe ze heten_x000D_ | line_comment | nl | package framework.database;_x000D_
_x000D_
import java.lang.reflect.Constructor;_x000D_
import java.sql.Connection;_x000D_
import java.sql.Driver;_x000D_
import java.sql.DriverManager;_x000D_
import java.sql.PreparedStatement;_x000D_
import java.sql.ResultSet;_x000D_
import java.sql.ResultSetMetaData;_x000D_
import java.sql.SQLException;_x000D_
import java.util.ArrayList;_x000D_
import java.util.Enumeration;_x000D_
import java.util.HashMap;_x000D_
_x000D_
public class Database {_x000D_
_x000D_
protected Connection conn;_x000D_
protected String connectionUrl;_x000D_
protected String username;_x000D_
protected String password; // TODO: kijken in hoeverre het haalbaar is het wachtwoord hier weg te laten_x000D_
_x000D_
@SuppressWarnings({ "unchecked", "rawtypes" })_x000D_
public Database(String driver, String connectionUrl, String username, String password)_x000D_
{_x000D_
try {_x000D_
// Kijken of de driver bestaat_x000D_
Class DriverClass = Class.forName(driver);_x000D_
_x000D_
Constructor constructorClass = DriverClass.getConstructor();_x000D_
Driver dbDriver = (Driver) constructorClass.newInstance();_x000D_
DriverManager.registerDriver(dbDriver);_x000D_
_x000D_
} catch (Exception e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
_x000D_
this.connectionUrl = connectionUrl;_x000D_
this.username = username;_x000D_
this.password = password;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Maakt connectie naar de databank_x000D_
* _x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public Connection getConnection() throws SQLException_x000D_
{_x000D_
if(this.conn == null || this.conn.isClosed())_x000D_
this.conn = DriverManager.getConnection(connectionUrl,username,password);_x000D_
_x000D_
return this.conn;_x000D_
}_x000D_
_x000D_
public PreparedStatement prepareStatement(String query) throws SQLException_x000D_
{_x000D_
return conn.prepareStatement(query);_x000D_
}_x000D_
_x000D_
public NamedParamStatement namedParamStatement(String query) throws SQLException_x000D_
{_x000D_
return new NamedParamStatement(getConnection(), query);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Geeft alle rows van een result in een handige ArrayList_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public ArrayList<DatabaseRow> getAllRows(ResultSet res) throws SQLException_x000D_
{_x000D_
ArrayList<DatabaseRow> rows = new ArrayList<DatabaseRow>();_x000D_
_x000D_
// Cursor naar -1 zetten._x000D_
res.beforeFirst();_x000D_
_x000D_
// Kijken of er op index 0 iets zit._x000D_
if(res.next()){_x000D_
// Blijkbaar zijn er rows_x000D_
// Cursor terug naar -1 zetten alle rows aflopen._x000D_
res.beforeFirst();_x000D_
_x000D_
// Pas als we aan de EOL zitten van de resultset stoppen we_x000D_
while(!res.isAfterLast()) {_x000D_
// Row ophalen en toevoegen aan Arraylist_x000D_
DatabaseRow row = this.getRow(res);_x000D_
if(row != null)_x000D_
rows.add(row);_x000D_
}_x000D_
}_x000D_
_x000D_
res.close();_x000D_
_x000D_
return rows;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Haalt de volgende row uit een resultset een geeft dit terug in een Hashmap<Kolomnaam,Object>_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public DatabaseRow getRow(ResultSet res) throws SQLException_x000D_
{_x000D_
HashMap<String, Object> row = new HashMap<String, Object>();_x000D_
_x000D_
// MetaData is<SUF>
ResultSetMetaData metaData = res.getMetaData();_x000D_
int columnCount = metaData.getColumnCount();_x000D_
_x000D_
ArrayList<String> columns = new ArrayList<String>();_x000D_
_x000D_
// Alle kolommen aflopen en hun naam bijhouden in de Array._x000D_
for (int columnNr=1; columnNr<=columnCount; columnNr++){_x000D_
String columnName = metaData.getColumnName(columnNr);_x000D_
columns.add(columnName);_x000D_
}_x000D_
_x000D_
// Springen naar de volgende row_x000D_
if (res.next()){_x000D_
// Alle kolommen in deze row aflopen_x000D_
for (String columnName:columns) {_x000D_
// De waarde van deze kolom ophalen_x000D_
Object rowData = res.getObject(columnName);_x000D_
// Toevoegen aan de hashmap_x000D_
row.put(columnName,rowData);_x000D_
}_x000D_
}_x000D_
_x000D_
if(row.size() <= 0)_x000D_
return null;_x000D_
_x000D_
return new DatabaseRow(row);_x000D_
}_x000D_
_x000D_
public void closeConnection() {_x000D_
try {_x000D_
conn.close();_x000D_
_x000D_
// This manually deregisters JDBC driver, which prevents Tomcat 7_x000D_
// from complaining about memory leaks wrto this class_x000D_
// http://stackoverflow.com/a/5315467/1306509_x000D_
Enumeration<Driver> drivers = DriverManager.getDrivers();_x000D_
while (drivers.hasMoreElements()) {_x000D_
Driver driver = drivers.nextElement();_x000D_
DriverManager.deregisterDriver(driver);_x000D_
}_x000D_
_x000D_
} catch (SQLException e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
}_x000D_
| false | 1,989 | 26 | 2,171 | 32 | 2,249 | 25 | 2,171 | 32 | 2,394 | 28 | false | false | false | false | false | true |
325 | 30224_11 | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
// Deze RequestMapping" op klasse niveau betekent dat elke Mapping in deze klasse begint met "localhost:8080/bonus/..."
@RequestMapping(value = "/bonus")
public class TelevisionControllerBonus {
// De lijst is static, omdat er maar 1 lijst kan zijn.
// De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan.
private static final List<String> televisionDatabase = new ArrayList<>();
@GetMapping("/televisions")
public ResponseEntity<List<String>> getAllTelevisions() {
// Return de complete lijst met een 200 status
return ResponseEntity.ok(televisionDatabase);
}
@GetMapping("/televisions/{id}")
public ResponseEntity<String> getTelevision(@PathVariable int id) {
// Return de waarde die op index(id) staat en een 200 status
// Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items.
// Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje.
return ResponseEntity.ok(televisionDatabase.get(id));
}
@PostMapping("/televisions")
public ResponseEntity<String> addTelevision(@RequestBody String television) {
// Bonus bonus: check voor 20 letters:
if(television.length()>20){
throw new TelevisionNameTooLongException("Televisienaam is te lang");
} else {
// Voeg de televisie uit de parameter toe aan de lijst
televisionDatabase.add(television);
// Return de televisie uit de parameter met een 201 status
return ResponseEntity.created(null).body(television);
}
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Void> deleteTelevision(@PathVariable int id) {
// Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen.
televisionDatabase.set(id, null);
// Return een 204 status
return ResponseEntity.noContent().build();
}
@PutMapping("/televisions/{id}")
public ResponseEntity<Void> updateTelevision(@PathVariable int id, @RequestBody String television) {
// In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst.
// In deze methode checken we daar expliciet voor en gooien we een custom exception op.
if(televisionDatabase.isEmpty() || id>televisionDatabase.size()){
throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database.");
} else {
// Vervang de waarde op index(id) met de television uit de parameter
televisionDatabase.set(id, television);
// Return een 204 status
return ResponseEntity.noContent().build();
}
}
} | Christiaan83/backend-spring-boot-tech-it-easy | src/main/java/nl/novi/techiteasy/controllers/TelevisionControllerBonus.java | 897 | // Return een 204 status | line_comment | nl | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
// Deze RequestMapping" op klasse niveau betekent dat elke Mapping in deze klasse begint met "localhost:8080/bonus/..."
@RequestMapping(value = "/bonus")
public class TelevisionControllerBonus {
// De lijst is static, omdat er maar 1 lijst kan zijn.
// De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan.
private static final List<String> televisionDatabase = new ArrayList<>();
@GetMapping("/televisions")
public ResponseEntity<List<String>> getAllTelevisions() {
// Return de complete lijst met een 200 status
return ResponseEntity.ok(televisionDatabase);
}
@GetMapping("/televisions/{id}")
public ResponseEntity<String> getTelevision(@PathVariable int id) {
// Return de waarde die op index(id) staat en een 200 status
// Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items.
// Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje.
return ResponseEntity.ok(televisionDatabase.get(id));
}
@PostMapping("/televisions")
public ResponseEntity<String> addTelevision(@RequestBody String television) {
// Bonus bonus: check voor 20 letters:
if(television.length()>20){
throw new TelevisionNameTooLongException("Televisienaam is te lang");
} else {
// Voeg de televisie uit de parameter toe aan de lijst
televisionDatabase.add(television);
// Return de televisie uit de parameter met een 201 status
return ResponseEntity.created(null).body(television);
}
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Void> deleteTelevision(@PathVariable int id) {
// Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen.
televisionDatabase.set(id, null);
// Return een<SUF>
return ResponseEntity.noContent().build();
}
@PutMapping("/televisions/{id}")
public ResponseEntity<Void> updateTelevision(@PathVariable int id, @RequestBody String television) {
// In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst.
// In deze methode checken we daar expliciet voor en gooien we een custom exception op.
if(televisionDatabase.isEmpty() || id>televisionDatabase.size()){
throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database.");
} else {
// Vervang de waarde op index(id) met de television uit de parameter
televisionDatabase.set(id, television);
// Return een 204 status
return ResponseEntity.noContent().build();
}
}
} | false | 725 | 8 | 831 | 8 | 776 | 8 | 831 | 8 | 919 | 8 | false | false | false | false | false | true |
62 | 25179_6 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.awt.event.ActionListener;
/**
* A graphical view of the simulation grid.
* The view displays a colored rectangle for each location
* representing its contents. It uses a default background color.
* Colors for each type of species can be defined using the
* setColor method.
*
* @author Adriaan van Elk, Eric Gunnink & Jelmer Postma
* @version 27-1-2015
*/
public class SimulatorView extends JFrame implements ActionListener
{
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
private JPanel linkerMenu;
private FieldView fieldView;
public JButton oneStepButton = new JButton("1 stap");
public JButton oneHundredStepButton = new JButton("100 stappen");
// A map for storing colors for participants in the simulation
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private FieldStats stats;
private Simulator theSimulator;
/**
* Create a view of the given width and height.
* @param height The simulation's height.
* @param width The simulation's width.
*/
public SimulatorView(int height, int width, Simulator simulator)
{
stats = new FieldStats();
colors = new LinkedHashMap<Class, Color>();
setTitle("Fox and Rabbit Simulation");
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
linkerMenu = new JPanel(new GridLayout(2,1));
theSimulator = simulator;
setLocation(100, 50);
fieldView = new FieldView(height, width);
Container contents = getContentPane();
contents.add(stepLabel, BorderLayout.NORTH);
contents.add(fieldView, BorderLayout.CENTER);
contents.add(population, BorderLayout.SOUTH);
contents.add(linkerMenu, BorderLayout.WEST);
addButton();
pack();
setVisible(true);
}
private void addButton()
{
linkerMenu.add(oneStepButton);
linkerMenu.add(oneHundredStepButton);
oneStepButton.addActionListener(this);
oneHundredStepButton.addActionListener(this);
}
/**
* Methode om een actie uit te voeren wanneer er op een knop wordt geklikt
*/
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(command.equals("1 stap"))
{
theSimulator.simulateOneStep();
}
if(command.equals("100 stappen"))
{
theSimulator.simulate(100);
}
}
/**
* Define a color to be used for a given class of animal.
* @param animalClass The animal's Class object.
* @param color The color to be used for the given class.
*/
public void setColor(Class animalClass, Color color)
{
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
private Color getColor(Class animalClass)
{
Color col = colors.get(animalClass);
if(col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
}
else {
return col;
}
}
/**
* Show the current status of the field.
* @param step Which iteration step it is.
* @param field The field whose status is to be displayed.
*/
public void showStatus(int step, Field field)
{
if(!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if(animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
}
else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX + stats.getPopulationDetails(field));
fieldView.repaint();
}
/**
* Determine whether the simulation should continue to run.
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field)
{
return stats.isViable(field);
}
/**
* Provide a graphical view of a rectangular field. This is
* a nested class (a class defined inside a class) which
* defines a custom component for the user interface. This
* component displays the field.
* This is rather advanced GUI stuff - you can ignore this
* for your project if you like.
*/
private class FieldView extends JPanel
{
private final int GRID_VIEW_SCALING_FACTOR = 6;
private int gridWidth, gridHeight;
private int xScale, yScale;
Dimension size;
private Graphics g;
private Image fieldImage;
/**
* Create a new FieldView component.
*/
public FieldView(int height, int width)
{
gridHeight = height;
gridWidth = width;
size = new Dimension(0, 0);
}
/**
* Tell the GUI manager how big we would like to be.
*/
public Dimension getPreferredSize()
{
return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR,
gridHeight * GRID_VIEW_SCALING_FACTOR);
}
/**
* Prepare for a new round of painting. Since the component
* may be resized, compute the scaling factor again.
*/
public void preparePaint()
{
if(! size.equals(getSize())) { // if the size has changed...
size = getSize();
fieldImage = fieldView.createImage(size.width, size.height);
g = fieldImage.getGraphics();
xScale = size.width / gridWidth;
if(xScale < 1) {
xScale = GRID_VIEW_SCALING_FACTOR;
}
yScale = size.height / gridHeight;
if(yScale < 1) {
yScale = GRID_VIEW_SCALING_FACTOR;
}
}
}
/**
* Paint on grid location on this field in a given color.
*/
public void drawMark(int x, int y, Color color)
{
g.setColor(color);
g.fillRect(x * xScale, y * yScale, xScale-1, yScale-1);
}
/**
* The field view component needs to be redisplayed. Copy the
* internal image to screen.
*/
public void paintComponent(Graphics g)
{
if(fieldImage != null) {
Dimension currentSize = getSize();
if(size.equals(currentSize)) {
g.drawImage(fieldImage, 0, 0, null);
}
else {
// Rescale the previous image.
g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);
}
}
}
}
}
| AVEHD/fox_bunny | SimulatorView.java | 2,166 | /**
* Methode om een actie uit te voeren wanneer er op een knop wordt geklikt
*/ | block_comment | nl | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.awt.event.ActionListener;
/**
* A graphical view of the simulation grid.
* The view displays a colored rectangle for each location
* representing its contents. It uses a default background color.
* Colors for each type of species can be defined using the
* setColor method.
*
* @author Adriaan van Elk, Eric Gunnink & Jelmer Postma
* @version 27-1-2015
*/
public class SimulatorView extends JFrame implements ActionListener
{
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
private JPanel linkerMenu;
private FieldView fieldView;
public JButton oneStepButton = new JButton("1 stap");
public JButton oneHundredStepButton = new JButton("100 stappen");
// A map for storing colors for participants in the simulation
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private FieldStats stats;
private Simulator theSimulator;
/**
* Create a view of the given width and height.
* @param height The simulation's height.
* @param width The simulation's width.
*/
public SimulatorView(int height, int width, Simulator simulator)
{
stats = new FieldStats();
colors = new LinkedHashMap<Class, Color>();
setTitle("Fox and Rabbit Simulation");
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
linkerMenu = new JPanel(new GridLayout(2,1));
theSimulator = simulator;
setLocation(100, 50);
fieldView = new FieldView(height, width);
Container contents = getContentPane();
contents.add(stepLabel, BorderLayout.NORTH);
contents.add(fieldView, BorderLayout.CENTER);
contents.add(population, BorderLayout.SOUTH);
contents.add(linkerMenu, BorderLayout.WEST);
addButton();
pack();
setVisible(true);
}
private void addButton()
{
linkerMenu.add(oneStepButton);
linkerMenu.add(oneHundredStepButton);
oneStepButton.addActionListener(this);
oneHundredStepButton.addActionListener(this);
}
/**
* Methode om een<SUF>*/
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(command.equals("1 stap"))
{
theSimulator.simulateOneStep();
}
if(command.equals("100 stappen"))
{
theSimulator.simulate(100);
}
}
/**
* Define a color to be used for a given class of animal.
* @param animalClass The animal's Class object.
* @param color The color to be used for the given class.
*/
public void setColor(Class animalClass, Color color)
{
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
private Color getColor(Class animalClass)
{
Color col = colors.get(animalClass);
if(col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
}
else {
return col;
}
}
/**
* Show the current status of the field.
* @param step Which iteration step it is.
* @param field The field whose status is to be displayed.
*/
public void showStatus(int step, Field field)
{
if(!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if(animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
}
else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX + stats.getPopulationDetails(field));
fieldView.repaint();
}
/**
* Determine whether the simulation should continue to run.
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field)
{
return stats.isViable(field);
}
/**
* Provide a graphical view of a rectangular field. This is
* a nested class (a class defined inside a class) which
* defines a custom component for the user interface. This
* component displays the field.
* This is rather advanced GUI stuff - you can ignore this
* for your project if you like.
*/
private class FieldView extends JPanel
{
private final int GRID_VIEW_SCALING_FACTOR = 6;
private int gridWidth, gridHeight;
private int xScale, yScale;
Dimension size;
private Graphics g;
private Image fieldImage;
/**
* Create a new FieldView component.
*/
public FieldView(int height, int width)
{
gridHeight = height;
gridWidth = width;
size = new Dimension(0, 0);
}
/**
* Tell the GUI manager how big we would like to be.
*/
public Dimension getPreferredSize()
{
return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR,
gridHeight * GRID_VIEW_SCALING_FACTOR);
}
/**
* Prepare for a new round of painting. Since the component
* may be resized, compute the scaling factor again.
*/
public void preparePaint()
{
if(! size.equals(getSize())) { // if the size has changed...
size = getSize();
fieldImage = fieldView.createImage(size.width, size.height);
g = fieldImage.getGraphics();
xScale = size.width / gridWidth;
if(xScale < 1) {
xScale = GRID_VIEW_SCALING_FACTOR;
}
yScale = size.height / gridHeight;
if(yScale < 1) {
yScale = GRID_VIEW_SCALING_FACTOR;
}
}
}
/**
* Paint on grid location on this field in a given color.
*/
public void drawMark(int x, int y, Color color)
{
g.setColor(color);
g.fillRect(x * xScale, y * yScale, xScale-1, yScale-1);
}
/**
* The field view component needs to be redisplayed. Copy the
* internal image to screen.
*/
public void paintComponent(Graphics g)
{
if(fieldImage != null) {
Dimension currentSize = getSize();
if(size.equals(currentSize)) {
g.drawImage(fieldImage, 0, 0, null);
}
else {
// Rescale the previous image.
g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);
}
}
}
}
}
| false | 1,619 | 28 | 1,769 | 29 | 1,966 | 24 | 1,769 | 29 | 2,183 | 31 | false | false | false | false | false | true |
1,216 | 42865_0 | package controllers;
import data.ReadData;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.BorderPane;
import models.Player;
import views.CreateNewPlayerView;
import views.TicTacToeView;
/**
* Zorgt voor de setup en het uitvoeren het spel
*
* @author Miguel
*/
public class PlayController {
private BorderPane borderPane;
private Player player1;
private Player player2;
private ComboBox p1ComboBox;
private ComboBox p2ComboBox;
private Button playButton;
private ObservableList players;
/**
* initialiseerd de play controller
*/
public void initialize() {
CreateNewPlayerController createNewPlayerController = new CreateNewPlayerController();
CreateNewPlayerView createNewPlayerView = new CreateNewPlayerView(createNewPlayerController);
players = FXCollections.observableList(ReadData.readDataFile("Player_Archive.dat"));
p1ComboBox.setItems(players);
p1ComboBox.setValue("Choose");
p1ComboBox.setOnAction(t -> {
onComboBoxChange();
});
p2ComboBox.setItems(players);
p2ComboBox.setValue("Choose");
p2ComboBox.setOnAction(t -> {
onComboBoxChange();
});
playButton.setOnAction(t -> {
System.out.println("play game");
TicTacToeController ticTacToeController = new TicTacToeController(player1, player2);
TicTacToeView ticTacToeView = new TicTacToeView(ticTacToeController);
borderPane = ticTacToeView.changeBorderPane(borderPane);
});
}
/**
* veranderd de visibility als de players een waarde hebben die niet hetzelfde zijn
*/
private void onComboBoxChange() {
if (!p1ComboBox.getValue().toString().equals("Choose")) {
player1 = (Player) p1ComboBox.getValue();
}
if (!p2ComboBox.getValue().toString().equals("Choose")) {
player2 = (Player) p2ComboBox.getValue();
}
playButton.setDisable(!(player1 != null && player2 != null && !player1.equals(player2)));
}
/**
* setter voor p1 combobox
* @param p1ComboBox
*/
public void setP1ComboBox(ComboBox p1ComboBox) {
this.p1ComboBox = p1ComboBox;
}
/**
* setter voor p2 combobox
* @param p2ComboBox
*/
public void setP2ComboBox(ComboBox p2ComboBox) {
this.p2ComboBox = p2ComboBox;
}
/**
* setter voor play button
* @param playButton
*/
public void setPlayButton(Button playButton) {
this.playButton = playButton;
}
/**
* setter voor borderpane
* @param borderPane
*/
public void setBorderPane(BorderPane borderPane) {
this.borderPane = borderPane;
}
}
| NoNamer777/hva-tic-tac-toe | src/controllers/PlayController.java | 900 | /**
* Zorgt voor de setup en het uitvoeren het spel
*
* @author Miguel
*/ | block_comment | nl | package controllers;
import data.ReadData;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.BorderPane;
import models.Player;
import views.CreateNewPlayerView;
import views.TicTacToeView;
/**
* Zorgt voor de<SUF>*/
public class PlayController {
private BorderPane borderPane;
private Player player1;
private Player player2;
private ComboBox p1ComboBox;
private ComboBox p2ComboBox;
private Button playButton;
private ObservableList players;
/**
* initialiseerd de play controller
*/
public void initialize() {
CreateNewPlayerController createNewPlayerController = new CreateNewPlayerController();
CreateNewPlayerView createNewPlayerView = new CreateNewPlayerView(createNewPlayerController);
players = FXCollections.observableList(ReadData.readDataFile("Player_Archive.dat"));
p1ComboBox.setItems(players);
p1ComboBox.setValue("Choose");
p1ComboBox.setOnAction(t -> {
onComboBoxChange();
});
p2ComboBox.setItems(players);
p2ComboBox.setValue("Choose");
p2ComboBox.setOnAction(t -> {
onComboBoxChange();
});
playButton.setOnAction(t -> {
System.out.println("play game");
TicTacToeController ticTacToeController = new TicTacToeController(player1, player2);
TicTacToeView ticTacToeView = new TicTacToeView(ticTacToeController);
borderPane = ticTacToeView.changeBorderPane(borderPane);
});
}
/**
* veranderd de visibility als de players een waarde hebben die niet hetzelfde zijn
*/
private void onComboBoxChange() {
if (!p1ComboBox.getValue().toString().equals("Choose")) {
player1 = (Player) p1ComboBox.getValue();
}
if (!p2ComboBox.getValue().toString().equals("Choose")) {
player2 = (Player) p2ComboBox.getValue();
}
playButton.setDisable(!(player1 != null && player2 != null && !player1.equals(player2)));
}
/**
* setter voor p1 combobox
* @param p1ComboBox
*/
public void setP1ComboBox(ComboBox p1ComboBox) {
this.p1ComboBox = p1ComboBox;
}
/**
* setter voor p2 combobox
* @param p2ComboBox
*/
public void setP2ComboBox(ComboBox p2ComboBox) {
this.p2ComboBox = p2ComboBox;
}
/**
* setter voor play button
* @param playButton
*/
public void setPlayButton(Button playButton) {
this.playButton = playButton;
}
/**
* setter voor borderpane
* @param borderPane
*/
public void setBorderPane(BorderPane borderPane) {
this.borderPane = borderPane;
}
}
| false | 629 | 22 | 724 | 28 | 731 | 23 | 724 | 28 | 829 | 25 | false | false | false | false | false | true |
3,400 | 43884_1 | package nerdygadgets.backoffice.main.JDBC;
import nerdygadgets.backoffice.main.data.Shaa256;
import java.sql.*;
public class Driver {
public static void main(String[] args) {
}
//Functies
//Functie adressen
public static ResultSet adressen() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT DeliveryInstructions FROM invoices");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees je de gegevens uit
/*ResultSet myRs = Driver.adressen();
try {
while (myRs.next()) {
System.out.println(myRs.getString("DeliveryInstructions"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie medewerkers
public static ResultSet medewerkers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT FullName, EmailAddress, PhoneNumber FROM people");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet login(String username, String password) {
try {
password = Shaa256.toHexString(Shaa256.getSHA(password));
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
String sql = "SELECT COUNT(*) FROM people WHERE LogonName = ? AND fixedpassword = ?";
PreparedStatement ps = myConn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet myRs = ps.executeQuery();
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees je de gegevens uit
/*ResultSet myRs = Driver.medewerkers();
try {
while (myRs.next()) {
System.out.println(myRs.getString("FullName"));
System.out.println(myRs.getString("EmailAddress"));
System.out.println(myRs.getString("PhoneNumber"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie Orders
public static ResultSet orders() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.OrderID, c.CustomerName, ci.Cityname FROM orders o LEFT JOIN customers c ON o.CustomerID = c.CustomerID LEFT JOIN cities ci ON c.DeliveryCityID = ci.CityID ORDER BY OrderID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getStock() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.StockItemID, o.StockItemName AS `Productnaam`, QuantityOnHand AS `Aantal`FROM wideworldimporters.stockitems o LEFT JOIN stockitemholdings sh ON o.StockItemID = sh.StockItemID ORDER BY o.StockItemID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getCustomers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT * FROM customer_ned");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void UpdateCustomer(String id, String cust, String city, String adres, String post, String email, String tel){
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query = "UPDATE customer_ned SET CustomerName = ?, City = ?, Adres = ?, Postalcode = ?, EmailAddress = ?, TelephoneNumber = ? WHERE CustomerID = ?";
PreparedStatement preparedStmt = myConn.prepareStatement(query);
preparedStmt.setString(1, cust);
preparedStmt.setString(2, city);
preparedStmt.setString(3, adres);
preparedStmt.setString(4, post);
preparedStmt.setString(5, email);
preparedStmt.setString(6, tel);
preparedStmt.setString(7, id);
// execute the java preparedstatement
int rowsAffected = preparedStmt.executeUpdate();
System.out.println("Hoeveelheid rows veranderd: "+rowsAffected);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void UpdateVoorraad(String id, String itemname, String Quantity){ //Moet nog iets gebeuren als 1 niet werkt
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query1 = "UPDATE stockitems SET StockItemName = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt1 = myConn.prepareStatement(query1);
preparedStmt1.setString(1, itemname);
preparedStmt1.setString(2, id);
int rowsAffected1 = preparedStmt1.executeUpdate();
String query2 = "UPDATE stockitemholdings SET QuantityOnHand = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt2 = myConn.prepareStatement(query2);
preparedStmt2.setString(1, Quantity);
preparedStmt2.setString(2, id);
int rowsAffected2 = preparedStmt2.executeUpdate();
System.out.println("Hoeveelheid rows veranderd in tabel 1: "+rowsAffected1);
System.out.println("Hoeveelheid rows veranderd in tabel 2: "+rowsAffected2);
} catch (Exception e) {
e.printStackTrace();
}
}
} | krisBroekstra1/Nerdygadgets | src/nerdygadgets/backoffice/main/JDBC/Driver.java | 1,876 | //Zo lees je de gegevens uit | line_comment | nl | package nerdygadgets.backoffice.main.JDBC;
import nerdygadgets.backoffice.main.data.Shaa256;
import java.sql.*;
public class Driver {
public static void main(String[] args) {
}
//Functies
//Functie adressen
public static ResultSet adressen() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT DeliveryInstructions FROM invoices");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees<SUF>
/*ResultSet myRs = Driver.adressen();
try {
while (myRs.next()) {
System.out.println(myRs.getString("DeliveryInstructions"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie medewerkers
public static ResultSet medewerkers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT FullName, EmailAddress, PhoneNumber FROM people");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet login(String username, String password) {
try {
password = Shaa256.toHexString(Shaa256.getSHA(password));
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
String sql = "SELECT COUNT(*) FROM people WHERE LogonName = ? AND fixedpassword = ?";
PreparedStatement ps = myConn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet myRs = ps.executeQuery();
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees je de gegevens uit
/*ResultSet myRs = Driver.medewerkers();
try {
while (myRs.next()) {
System.out.println(myRs.getString("FullName"));
System.out.println(myRs.getString("EmailAddress"));
System.out.println(myRs.getString("PhoneNumber"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie Orders
public static ResultSet orders() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.OrderID, c.CustomerName, ci.Cityname FROM orders o LEFT JOIN customers c ON o.CustomerID = c.CustomerID LEFT JOIN cities ci ON c.DeliveryCityID = ci.CityID ORDER BY OrderID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getStock() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.StockItemID, o.StockItemName AS `Productnaam`, QuantityOnHand AS `Aantal`FROM wideworldimporters.stockitems o LEFT JOIN stockitemholdings sh ON o.StockItemID = sh.StockItemID ORDER BY o.StockItemID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getCustomers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT * FROM customer_ned");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void UpdateCustomer(String id, String cust, String city, String adres, String post, String email, String tel){
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query = "UPDATE customer_ned SET CustomerName = ?, City = ?, Adres = ?, Postalcode = ?, EmailAddress = ?, TelephoneNumber = ? WHERE CustomerID = ?";
PreparedStatement preparedStmt = myConn.prepareStatement(query);
preparedStmt.setString(1, cust);
preparedStmt.setString(2, city);
preparedStmt.setString(3, adres);
preparedStmt.setString(4, post);
preparedStmt.setString(5, email);
preparedStmt.setString(6, tel);
preparedStmt.setString(7, id);
// execute the java preparedstatement
int rowsAffected = preparedStmt.executeUpdate();
System.out.println("Hoeveelheid rows veranderd: "+rowsAffected);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void UpdateVoorraad(String id, String itemname, String Quantity){ //Moet nog iets gebeuren als 1 niet werkt
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query1 = "UPDATE stockitems SET StockItemName = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt1 = myConn.prepareStatement(query1);
preparedStmt1.setString(1, itemname);
preparedStmt1.setString(2, id);
int rowsAffected1 = preparedStmt1.executeUpdate();
String query2 = "UPDATE stockitemholdings SET QuantityOnHand = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt2 = myConn.prepareStatement(query2);
preparedStmt2.setString(1, Quantity);
preparedStmt2.setString(2, id);
int rowsAffected2 = preparedStmt2.executeUpdate();
System.out.println("Hoeveelheid rows veranderd in tabel 1: "+rowsAffected1);
System.out.println("Hoeveelheid rows veranderd in tabel 2: "+rowsAffected2);
} catch (Exception e) {
e.printStackTrace();
}
}
} | false | 1,370 | 11 | 1,493 | 8 | 1,593 | 7 | 1,493 | 8 | 1,855 | 11 | false | false | false | false | false | true |
662 | 33859_6 | package nl.hu.husacct.game31.domein;
import java.util.*;
public class ComputerSpeler extends Speler{
private double[][][] kaartenTabel;
private Kaart[] kaartenIndex;
private Vector alleKaarten;
private Spel spel;
private int schuifCounter = 0;
public ComputerSpeler(String naam, int fices, Tafel tafel, Pot pot, KaartStapel kaartStapel, Spel spel)
{
super(naam,fices, tafel, pot);
this.alleKaarten = kaartStapel.getKaarten();
this.spel = spel;
vulKaartenTabel();
printTabel();
}
private void vulKaartenTabel()
{
kaartenIndex = new Kaart[32];
Vector kaarten = alleKaarten;
//kaarten ophalen en in een array plaatsen
int index = 0;
for(Iterator itr = kaarten.iterator();itr.hasNext();index++)
{
Kaart k = (Kaart) itr.next();
kaartenIndex[index] = k;
//System.out.println(index + " " + k.geefSymbool() + " " + k.geefGetal());
}
//kaartenTabel invullen, de coordinaten geven de index van de Kaart in de kaartenIndex aan
//op de locatie staat het aantal punten dat een combinatie oplevert
kaartenTabel = new double[32][32][32];
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
//niet dezelfde kaart
if(kaartenIndex[i] != kaartenIndex[j] && kaartenIndex[i] != kaartenIndex[k] && kaartenIndex[j] != kaartenIndex[k])
{
//zelfde getal
String getalK1 = kaartenIndex[i].geefGetal();
String getalK2 = kaartenIndex[j].geefGetal();
String getalK3 = kaartenIndex[k].geefGetal();
if(getalK1.equals(getalK2) && getalK1.equals(getalK3) && getalK3.equals(getalK2))
{
kaartenTabel[i][j][k] = 30.5;
}
//zelfde kleur
String symbool = kaartenIndex[i].geefSymbool();
if(symbool.equals(kaartenIndex[j].geefSymbool()) && symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(symbool.equals(kaartenIndex[j].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde();
}
else if(symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(kaartenIndex[j].geefSymbool().equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
}
}
}
}
}
//de computerspeler krijgt de beurt
public void aanDeBeurt()
{
Vector opTafel = tafel.getKaarten();
Vector inHand = deelname.getKaarten();
double puntenOpTafel = zoekPunten(opTafel);
double puntenInHand = zoekPunten(inHand);
int[] indexHand = new int[3];
int[] indexTafel = new int[3];
for(int i=0;i<3;i++)
{
indexHand[i] = zoekIndex((Kaart)inHand.elementAt(i));
indexTafel[i] = zoekIndex((Kaart)opTafel.elementAt(i));
}
double[][] puntenTabel = combineer(indexHand, indexTafel);
int[] besteCoords = zoekCoordsBeste(puntenTabel);
double bestePunten = puntenTabel[besteCoords[0]][besteCoords[1]];
if(bestePunten > puntenOpTafel && bestePunten > puntenInHand)
{
//1kaart wisselen
tafel.selecteerKaart(besteCoords[1]);
deelname.selecteerKaart(besteCoords[0]);
spel.ruil1Kaart(deelname.getSelected(), tafel.getSelected());
}
else if(bestePunten < puntenOpTafel)
{
//alles wisselen
spel.ruil3Kaart();
schuifCounter = 0;
}
else if(bestePunten <= puntenInHand)
{
if(puntenInHand > 25 || schuifCounter == 2)
{
//pass
spel.pas();
}
else
{
//doorschuiven
schuifCounter++;
spel.doorSchuiven();
}
}
Vector handkaartjes = deelname.getKaarten();
for(int i=0;i<3;i++)
{
Kaart k = (Kaart)handkaartjes.elementAt(i);
System.out.println(k.geefSymbool() + " " + k.geefGetal());
}
}
//de computerspeler krijgt als eerste de beurt in een nieuwe ronde
public void eersteKeerInRonde()
{
schuifCounter = 0;
Vector inHand = deelname.getKaarten();
double puntenInHand = zoekPunten(inHand);
//kan er 30.5 worden gescoord met deze kaarten?
Vector kaarten = deelname.getKaarten();
Kaart krt1 = (Kaart) kaarten.elementAt(0);
Kaart krt2 = (Kaart) kaarten.elementAt(1);
Kaart krt3 = (Kaart) kaarten.elementAt(2);
if(puntenInHand == 31.0)
{
//doorschuiven
spel.doorSchuiven();
schuifCounter++;
}
else if(puntenInHand > 25)
{
//pass
spel.pas();
}
else if(krt1.geefGetal().equals(krt2.geefGetal()) || krt1.geefGetal().equals(krt3.geefGetal()) || krt2.geefGetal().equals(krt3.geefGetal()))
{
//kaarten bekijken
//zoek beste ruil
//aanDeBeurt heeft dezelfde functionaliteiten dus roep ik die hier aan
aanDeBeurt();
}
else if(puntenInHand == 0.0)
{
spel.ruil3Kaart();
}
}
private int[] zoekCoordsBeste(double[][] puntenTabel)
{
int[] coords = new int[2];
double grootste = 0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(puntenTabel[i][j] > grootste)
{
coords[0] = i;
coords[1] = j;
}
}
}
return coords;
}
private double[][] combineer(int[] hand, int[] tafel)
{
double[][] tabel = new double[3][3];
for(int i=0;i<3;i++) //regel
{
for(int j=0;j<3;j++) //kolom
{
int[] combinatie = new int[3];
for(int k=0;k<3;k++)
{
if(k == i)
{
combinatie[k] = tafel[j];
}
else
{
combinatie[k] = hand[k];
}
}
tabel[i][j] = kaartenTabel[combinatie[0]][combinatie[1]][combinatie[2]];
}
}
return tabel;
}
private int zoekIndex(Kaart k)
{
int index = 0;
for(int i=0;i<32;i++)
{
if(kaartenIndex[i] == k)
{
return i;
}
}
return -1;
}
private double zoekPunten(Vector kaarten)
{
double aantalPunten = 0;
int[] index = new int[3];
index[0] = zoekIndex((Kaart)kaarten.elementAt(0));
index[1] = zoekIndex((Kaart)kaarten.elementAt(1));
index[2] = zoekIndex((Kaart)kaarten.elementAt(2));
aantalPunten = kaartenTabel[index[0]][index[1]][index[2]];
return aantalPunten;
}
private void printTabel()
{
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
System.out.print(" " + kaartenTabel[i][j][k]);
}
System.out.print('\n');
}
System.out.print('\n');
}
}
}
| HUSACCT/SaccWithHusacctExample_Maven | src/main/java/nl/hu/husacct/game31/domein/ComputerSpeler.java | 2,758 | //de computerspeler krijgt als eerste de beurt in een nieuwe ronde | line_comment | nl | package nl.hu.husacct.game31.domein;
import java.util.*;
public class ComputerSpeler extends Speler{
private double[][][] kaartenTabel;
private Kaart[] kaartenIndex;
private Vector alleKaarten;
private Spel spel;
private int schuifCounter = 0;
public ComputerSpeler(String naam, int fices, Tafel tafel, Pot pot, KaartStapel kaartStapel, Spel spel)
{
super(naam,fices, tafel, pot);
this.alleKaarten = kaartStapel.getKaarten();
this.spel = spel;
vulKaartenTabel();
printTabel();
}
private void vulKaartenTabel()
{
kaartenIndex = new Kaart[32];
Vector kaarten = alleKaarten;
//kaarten ophalen en in een array plaatsen
int index = 0;
for(Iterator itr = kaarten.iterator();itr.hasNext();index++)
{
Kaart k = (Kaart) itr.next();
kaartenIndex[index] = k;
//System.out.println(index + " " + k.geefSymbool() + " " + k.geefGetal());
}
//kaartenTabel invullen, de coordinaten geven de index van de Kaart in de kaartenIndex aan
//op de locatie staat het aantal punten dat een combinatie oplevert
kaartenTabel = new double[32][32][32];
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
//niet dezelfde kaart
if(kaartenIndex[i] != kaartenIndex[j] && kaartenIndex[i] != kaartenIndex[k] && kaartenIndex[j] != kaartenIndex[k])
{
//zelfde getal
String getalK1 = kaartenIndex[i].geefGetal();
String getalK2 = kaartenIndex[j].geefGetal();
String getalK3 = kaartenIndex[k].geefGetal();
if(getalK1.equals(getalK2) && getalK1.equals(getalK3) && getalK3.equals(getalK2))
{
kaartenTabel[i][j][k] = 30.5;
}
//zelfde kleur
String symbool = kaartenIndex[i].geefSymbool();
if(symbool.equals(kaartenIndex[j].geefSymbool()) && symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(symbool.equals(kaartenIndex[j].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde();
}
else if(symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(kaartenIndex[j].geefSymbool().equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
}
}
}
}
}
//de computerspeler krijgt de beurt
public void aanDeBeurt()
{
Vector opTafel = tafel.getKaarten();
Vector inHand = deelname.getKaarten();
double puntenOpTafel = zoekPunten(opTafel);
double puntenInHand = zoekPunten(inHand);
int[] indexHand = new int[3];
int[] indexTafel = new int[3];
for(int i=0;i<3;i++)
{
indexHand[i] = zoekIndex((Kaart)inHand.elementAt(i));
indexTafel[i] = zoekIndex((Kaart)opTafel.elementAt(i));
}
double[][] puntenTabel = combineer(indexHand, indexTafel);
int[] besteCoords = zoekCoordsBeste(puntenTabel);
double bestePunten = puntenTabel[besteCoords[0]][besteCoords[1]];
if(bestePunten > puntenOpTafel && bestePunten > puntenInHand)
{
//1kaart wisselen
tafel.selecteerKaart(besteCoords[1]);
deelname.selecteerKaart(besteCoords[0]);
spel.ruil1Kaart(deelname.getSelected(), tafel.getSelected());
}
else if(bestePunten < puntenOpTafel)
{
//alles wisselen
spel.ruil3Kaart();
schuifCounter = 0;
}
else if(bestePunten <= puntenInHand)
{
if(puntenInHand > 25 || schuifCounter == 2)
{
//pass
spel.pas();
}
else
{
//doorschuiven
schuifCounter++;
spel.doorSchuiven();
}
}
Vector handkaartjes = deelname.getKaarten();
for(int i=0;i<3;i++)
{
Kaart k = (Kaart)handkaartjes.elementAt(i);
System.out.println(k.geefSymbool() + " " + k.geefGetal());
}
}
//de computerspeler<SUF>
public void eersteKeerInRonde()
{
schuifCounter = 0;
Vector inHand = deelname.getKaarten();
double puntenInHand = zoekPunten(inHand);
//kan er 30.5 worden gescoord met deze kaarten?
Vector kaarten = deelname.getKaarten();
Kaart krt1 = (Kaart) kaarten.elementAt(0);
Kaart krt2 = (Kaart) kaarten.elementAt(1);
Kaart krt3 = (Kaart) kaarten.elementAt(2);
if(puntenInHand == 31.0)
{
//doorschuiven
spel.doorSchuiven();
schuifCounter++;
}
else if(puntenInHand > 25)
{
//pass
spel.pas();
}
else if(krt1.geefGetal().equals(krt2.geefGetal()) || krt1.geefGetal().equals(krt3.geefGetal()) || krt2.geefGetal().equals(krt3.geefGetal()))
{
//kaarten bekijken
//zoek beste ruil
//aanDeBeurt heeft dezelfde functionaliteiten dus roep ik die hier aan
aanDeBeurt();
}
else if(puntenInHand == 0.0)
{
spel.ruil3Kaart();
}
}
private int[] zoekCoordsBeste(double[][] puntenTabel)
{
int[] coords = new int[2];
double grootste = 0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(puntenTabel[i][j] > grootste)
{
coords[0] = i;
coords[1] = j;
}
}
}
return coords;
}
private double[][] combineer(int[] hand, int[] tafel)
{
double[][] tabel = new double[3][3];
for(int i=0;i<3;i++) //regel
{
for(int j=0;j<3;j++) //kolom
{
int[] combinatie = new int[3];
for(int k=0;k<3;k++)
{
if(k == i)
{
combinatie[k] = tafel[j];
}
else
{
combinatie[k] = hand[k];
}
}
tabel[i][j] = kaartenTabel[combinatie[0]][combinatie[1]][combinatie[2]];
}
}
return tabel;
}
private int zoekIndex(Kaart k)
{
int index = 0;
for(int i=0;i<32;i++)
{
if(kaartenIndex[i] == k)
{
return i;
}
}
return -1;
}
private double zoekPunten(Vector kaarten)
{
double aantalPunten = 0;
int[] index = new int[3];
index[0] = zoekIndex((Kaart)kaarten.elementAt(0));
index[1] = zoekIndex((Kaart)kaarten.elementAt(1));
index[2] = zoekIndex((Kaart)kaarten.elementAt(2));
aantalPunten = kaartenTabel[index[0]][index[1]][index[2]];
return aantalPunten;
}
private void printTabel()
{
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
System.out.print(" " + kaartenTabel[i][j][k]);
}
System.out.print('\n');
}
System.out.print('\n');
}
}
}
| false | 2,300 | 17 | 2,669 | 23 | 2,477 | 15 | 2,670 | 23 | 3,188 | 18 | false | false | false | false | false | true |
1,264 | 122744_0 | import java.util.Scanner;
public class OnderdeelC {
// Alles onder de case die geselecteerd wordt zal uitgeprint worden dit komt omdat de code niet weet waar het moet stoppen door het ontbreken van een break
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Vul een maand in:\n");
int month = input.nextInt();
switch (month) {
case 1:
System.out.println("januari");
case 2:
System.out.println("februari");
case 3:
System.out.println("maart");
case 4:
System.out.println("april");
case 5:
System.out.println("mei");
case 6:
System.out.println("juni");
case 7:
System.out.println("juli");
case 8:
System.out.println("augustus");
case 9:
System.out.println("september");
case 10:
System.out.println("oktober");
case 11:
System.out.println("november");
case 12:
System.out.println("december");
default:
System.out.println("Geen geldige invoer");
}
}
}
| Owain94/IOPR-Java | Week2/Werkcolleges/opgave1/src/OnderdeelC.java | 366 | // Alles onder de case die geselecteerd wordt zal uitgeprint worden dit komt omdat de code niet weet waar het moet stoppen door het ontbreken van een break | line_comment | nl | import java.util.Scanner;
public class OnderdeelC {
// Alles onder<SUF>
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Vul een maand in:\n");
int month = input.nextInt();
switch (month) {
case 1:
System.out.println("januari");
case 2:
System.out.println("februari");
case 3:
System.out.println("maart");
case 4:
System.out.println("april");
case 5:
System.out.println("mei");
case 6:
System.out.println("juni");
case 7:
System.out.println("juli");
case 8:
System.out.println("augustus");
case 9:
System.out.println("september");
case 10:
System.out.println("oktober");
case 11:
System.out.println("november");
case 12:
System.out.println("december");
default:
System.out.println("Geen geldige invoer");
}
}
}
| false | 282 | 38 | 326 | 42 | 333 | 34 | 326 | 42 | 359 | 40 | false | false | false | false | false | true |
2,966 | 30795_0 | package nl.novi.uitleg.week2.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Bestandslezer {
private static final String FILE_LOCATION = "src/nl/novi/uitleg/week2/io/bestand.txt";
/**
* Deze methode maakt een ArrayList<User> BufferedReader aan.
* De BufferedReader wordt vervolgens aan de readAllLines methode gegeven om het tekstbestand
* uit te lezen.
* @return lege of gevulde lijst met User-objecten.
*/
public static List<User> readFile() {
List<User> gebruikers = new ArrayList<>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(FILE_LOCATION));
gebruikers = readAllLines(bufferedReader);
} catch (IOException ioException) {
ioException.printStackTrace();
}
return gebruikers;
}
/**
* Deze methode is private en kan dus alleen in de Bestandlezer.java klasse aangeroepen worden.
*
* Deze code ontvangt een BufferedReader en gaat het tekstbestand dat daaronder hangt regel voor regel
* uitlezen.
*
* Daarna wordt de gelezen regel in een String[] array geplaatst. Vanuit deze array wordt uiteindelijk een
* User-object aangemaakt. Dit User-object wordt toegevoegd aan de list en uiteindelijk gereturned.
*
* Deze methode is eigenlijk te groot. Deze heeft te veel verantwoordlijkheden. Het maken van een object op basis
* van een String of Array zou ik bijvoorbeeld in een andere methode of klasse zetten.
* Kun je verzinnen hoe dat moet? Deze oplossing is meer het niveau van Java 1.
*
* @param bufferedReader De bufferedreader met een FileReader en de locatie naar het tekstbestand
* @return Lijst met user-objecten.
* @throws IOException wanneer er iets fout gaat in de IO-operatie.
*/
private static List<User> readAllLines(BufferedReader bufferedReader) throws IOException {
List<User> gebruikers = new ArrayList<>();
String line;
while((line = bufferedReader.readLine()) != null) {
String[] inhoudRegel = line.split("\\|");
String username = inhoudRegel[0];
String score = inhoudRegel[1].trim();
int scoreConverted;
try {
scoreConverted = Integer.parseInt(score);
} catch (NumberFormatException numberFormatException) {
scoreConverted = 0;
}
User user = new User(username, scoreConverted);
gebruikers.add(user);
}
return gebruikers;
}
/**
* Deze methode ontvangt een lijst met User-objecten. Deze worden met een methode uit het user-object omgevormd
* naar Strings die opgeslagen kunnen worden.
* @param users Lijst van users die opgeslagen moeten worden.
* @throws IOException wanneer er iets foutgaat met het opslaan.
*/
public static void save(List<User> users) throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
for (User user : users) {
String lineToSave = user.getTextToSave();
writer.write(lineToSave + "\r\n");
}
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
/**
* Deze methode schrijft een lege String weg naar het tekstbestand. Alle data verdwijnt dus na het aanroepen van
* deze methode.
*
* Public methode, dus deze kan van buiten deze klasse aangeroepen worden.
*
* @throws IOException wanneer er iets fout gaat met het wegschrijven.
*/
public static void emptyFile() throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
writer.write("");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
}
| hogeschoolnovi/SD-BE-JP-oefenopdrachten | src/nl/novi/uitleg/week2/io/Bestandslezer.java | 1,170 | /**
* Deze methode maakt een ArrayList<User> BufferedReader aan.
* De BufferedReader wordt vervolgens aan de readAllLines methode gegeven om het tekstbestand
* uit te lezen.
* @return lege of gevulde lijst met User-objecten.
*/ | block_comment | nl | package nl.novi.uitleg.week2.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Bestandslezer {
private static final String FILE_LOCATION = "src/nl/novi/uitleg/week2/io/bestand.txt";
/**
* Deze methode maakt<SUF>*/
public static List<User> readFile() {
List<User> gebruikers = new ArrayList<>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(FILE_LOCATION));
gebruikers = readAllLines(bufferedReader);
} catch (IOException ioException) {
ioException.printStackTrace();
}
return gebruikers;
}
/**
* Deze methode is private en kan dus alleen in de Bestandlezer.java klasse aangeroepen worden.
*
* Deze code ontvangt een BufferedReader en gaat het tekstbestand dat daaronder hangt regel voor regel
* uitlezen.
*
* Daarna wordt de gelezen regel in een String[] array geplaatst. Vanuit deze array wordt uiteindelijk een
* User-object aangemaakt. Dit User-object wordt toegevoegd aan de list en uiteindelijk gereturned.
*
* Deze methode is eigenlijk te groot. Deze heeft te veel verantwoordlijkheden. Het maken van een object op basis
* van een String of Array zou ik bijvoorbeeld in een andere methode of klasse zetten.
* Kun je verzinnen hoe dat moet? Deze oplossing is meer het niveau van Java 1.
*
* @param bufferedReader De bufferedreader met een FileReader en de locatie naar het tekstbestand
* @return Lijst met user-objecten.
* @throws IOException wanneer er iets fout gaat in de IO-operatie.
*/
private static List<User> readAllLines(BufferedReader bufferedReader) throws IOException {
List<User> gebruikers = new ArrayList<>();
String line;
while((line = bufferedReader.readLine()) != null) {
String[] inhoudRegel = line.split("\\|");
String username = inhoudRegel[0];
String score = inhoudRegel[1].trim();
int scoreConverted;
try {
scoreConverted = Integer.parseInt(score);
} catch (NumberFormatException numberFormatException) {
scoreConverted = 0;
}
User user = new User(username, scoreConverted);
gebruikers.add(user);
}
return gebruikers;
}
/**
* Deze methode ontvangt een lijst met User-objecten. Deze worden met een methode uit het user-object omgevormd
* naar Strings die opgeslagen kunnen worden.
* @param users Lijst van users die opgeslagen moeten worden.
* @throws IOException wanneer er iets foutgaat met het opslaan.
*/
public static void save(List<User> users) throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
for (User user : users) {
String lineToSave = user.getTextToSave();
writer.write(lineToSave + "\r\n");
}
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
/**
* Deze methode schrijft een lege String weg naar het tekstbestand. Alle data verdwijnt dus na het aanroepen van
* deze methode.
*
* Public methode, dus deze kan van buiten deze klasse aangeroepen worden.
*
* @throws IOException wanneer er iets fout gaat met het wegschrijven.
*/
public static void emptyFile() throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
writer.write("");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
}
| false | 921 | 65 | 1,048 | 67 | 989 | 60 | 1,049 | 67 | 1,173 | 75 | false | false | false | false | false | true |
1,159 | 180433_6 | //package nl.hu.fnt.gsos.wsproducer;
//
//import javax.jws.WebService;
//
//@WebService(endpointInterface = "nl.hu.fnt.gsos.wsinterface.WSInterface")
//public class PowerserviceImpl implements WSInterface {
//
// @Override
//// public Response calculatePower(Request request) throws Fault_Exception {
//// ObjectFactory factory = new ObjectFactory();
//// Response response = factory.createResponse();
//// try {
//// Double result = Math.pow(request.getX().doubleValue(), request
//// .getPower().doubleValue());
//// // x en power zijn altijd gehele getallen dan is er geen afronding
//// long actualResult = result.longValue();
//// response.setResult(actualResult);
//// } catch (RuntimeException e) {
//// Fault x = factory.createFault();
//// x.setErrorCode((short) 1);
//// x.setMessage("Kan de macht van " + request.getX()
//// + " tot de macht " + request.getPower().toString()
//// + " niet berekenen.");
//// Fault_Exception fault = new Fault_Exception(
//// "Er ging iets mis met het berekenen van de power", x);
//// throw fault;
//// }
//// return response;
//// }
////
////}
| Murrx/EWDC | ws-parent/ws-producer/src/main/java/nl/hu/fnt/gsos/wsproducer/PowerserviceImpl.java | 343 | //// // x en power zijn altijd gehele getallen dan is er geen afronding | line_comment | nl | //package nl.hu.fnt.gsos.wsproducer;
//
//import javax.jws.WebService;
//
//@WebService(endpointInterface = "nl.hu.fnt.gsos.wsinterface.WSInterface")
//public class PowerserviceImpl implements WSInterface {
//
// @Override
//// public Response calculatePower(Request request) throws Fault_Exception {
//// ObjectFactory factory = new ObjectFactory();
//// Response response = factory.createResponse();
//// try {
//// Double result = Math.pow(request.getX().doubleValue(), request
//// .getPower().doubleValue());
//// // x en<SUF>
//// long actualResult = result.longValue();
//// response.setResult(actualResult);
//// } catch (RuntimeException e) {
//// Fault x = factory.createFault();
//// x.setErrorCode((short) 1);
//// x.setMessage("Kan de macht van " + request.getX()
//// + " tot de macht " + request.getPower().toString()
//// + " niet berekenen.");
//// Fault_Exception fault = new Fault_Exception(
//// "Er ging iets mis met het berekenen van de power", x);
//// throw fault;
//// }
//// return response;
//// }
////
////}
| false | 272 | 21 | 348 | 25 | 315 | 19 | 348 | 25 | 386 | 25 | false | false | false | false | false | true |
957 | 190590_3 | package nl.fontys.smpt42_1.fontysswipe.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import nl.fontys.smpt42_1.fontysswipe.domain.Route;
import nl.fontys.smpt42_1.fontysswipe.domain.Teacher;
import nl.fontys.smpt42_1.fontysswipe.domain.interfaces.CompareAlgo;
import nl.fontys.smpt42_1.fontysswipe.util.FindRouteUtilKt;
/**
* @author SMPT42-1
*/
class CompareController {
private static CompareController instance;
private CompareController() {
// Marked private because the CompareController should never be instantianted outside this class.
}
public static CompareController getInstance() {
return instance == null ? instance = new CompareController() : instance;
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<Teacher> compareTeachers(List<Route> userPoints, List<Teacher> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> teachersMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : teachersMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> compareWorkshops(List<Route> userPoints, List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> workshopsMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : workshopsMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
private List<Route> getCorrectUserPoints(List<Route> userPoints) {
List<Route> correctUserPoints = new ArrayList<Route>();
for (Route route : userPoints) {
route.setUserPoints(route.getUserPoints() / (route.getMaxPoints() / 10));
correctUserPoints.add(route);
}
return correctUserPoints;
}
private static Map<CompareAlgo, Double> sortByValue(Map<CompareAlgo, Double> unsortMap) {
List<Map.Entry<CompareAlgo, Double>> list = new LinkedList<Map.Entry<CompareAlgo, Double>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<CompareAlgo, Double>>() {
public int compare(Map.Entry<CompareAlgo, Double> o1,
Map.Entry<CompareAlgo, Double> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<CompareAlgo, Double> sortedMap = new LinkedHashMap<CompareAlgo, Double>();
for (Map.Entry<CompareAlgo, Double> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Map.Entry<CompareAlgo, Double> entry : sortedMap.entrySet()) {
System.out.println("Key : " + entry.getKey().getName()
+ " Value : " + entry.getValue());
}
return sortedMap;
}
}
| Laugslander/fontys-swipe | app/src/main/java/nl/fontys/smpt42_1/fontysswipe/controller/CompareController.java | 1,492 | /**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/ | block_comment | nl | package nl.fontys.smpt42_1.fontysswipe.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import nl.fontys.smpt42_1.fontysswipe.domain.Route;
import nl.fontys.smpt42_1.fontysswipe.domain.Teacher;
import nl.fontys.smpt42_1.fontysswipe.domain.interfaces.CompareAlgo;
import nl.fontys.smpt42_1.fontysswipe.util.FindRouteUtilKt;
/**
* @author SMPT42-1
*/
class CompareController {
private static CompareController instance;
private CompareController() {
// Marked private because the CompareController should never be instantianted outside this class.
}
public static CompareController getInstance() {
return instance == null ? instance = new CompareController() : instance;
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<Teacher> compareTeachers(List<Route> userPoints, List<Teacher> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> teachersMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : teachersMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
/**
* Compare teacher methode<SUF>*/
List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> compareWorkshops(List<Route> userPoints, List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> workshopsMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : workshopsMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
private List<Route> getCorrectUserPoints(List<Route> userPoints) {
List<Route> correctUserPoints = new ArrayList<Route>();
for (Route route : userPoints) {
route.setUserPoints(route.getUserPoints() / (route.getMaxPoints() / 10));
correctUserPoints.add(route);
}
return correctUserPoints;
}
private static Map<CompareAlgo, Double> sortByValue(Map<CompareAlgo, Double> unsortMap) {
List<Map.Entry<CompareAlgo, Double>> list = new LinkedList<Map.Entry<CompareAlgo, Double>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<CompareAlgo, Double>>() {
public int compare(Map.Entry<CompareAlgo, Double> o1,
Map.Entry<CompareAlgo, Double> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<CompareAlgo, Double> sortedMap = new LinkedHashMap<CompareAlgo, Double>();
for (Map.Entry<CompareAlgo, Double> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Map.Entry<CompareAlgo, Double> entry : sortedMap.entrySet()) {
System.out.println("Key : " + entry.getKey().getName()
+ " Value : " + entry.getValue());
}
return sortedMap;
}
}
| false | 1,160 | 101 | 1,334 | 110 | 1,341 | 96 | 1,334 | 110 | 1,534 | 107 | false | false | false | false | false | true |
745 | 14017_0 | package alphareversi.commands.receive;
import alphareversi.commands.CommandParser;
import alphareversi.commands.RecvCommand;
import java.util.HashMap;
/**
* Created by Joost van Berkel on 3/24/2016.
* Resultaat van een zet ontvangen, bericht naar beide spelers.
* S: SVR GAME MOVE {PLAYER: "--speler--", DETAILS: "--reactie spel op zet--", MOVE:"--zet--"}
* Er is een zet gedaan, dit bericht geeft aan wie deze gezet heeft,
* wat de reactie van het spel erop is
*/
public class RecvGameMoveCommand extends RecvCommand {
private String player;
private String details;
private String move;
/**
* Parse string to create a filled RecvGamelistCommand.
* @param command string containing server message
*/
public RecvGameMoveCommand(String command) {
String[] parts = command.split(" ", 4);
this.setType(parts[0]);
this.setMethod(parts[1]);
this.setAction(parts[2]);
HashMap objects = CommandParser.parseObjectMap(parts[3]);
this.setPlayer((String) objects.get("PLAYER"));
this.setDetails((String) objects.get("DETAILS"));
this.setMove((String) objects.get("MOVE"));
}
public String getPlayer() {
return player;
}
public void setPlayer(String player) {
this.player = player;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getMove() {
return move;
}
public void setMove(String move) {
this.move = move;
}
}
| IcyPalm/AlphaReversi | src/alphareversi/commands/receive/RecvGameMoveCommand.java | 480 | /**
* Created by Joost van Berkel on 3/24/2016.
* Resultaat van een zet ontvangen, bericht naar beide spelers.
* S: SVR GAME MOVE {PLAYER: "--speler--", DETAILS: "--reactie spel op zet--", MOVE:"--zet--"}
* Er is een zet gedaan, dit bericht geeft aan wie deze gezet heeft,
* wat de reactie van het spel erop is
*/ | block_comment | nl | package alphareversi.commands.receive;
import alphareversi.commands.CommandParser;
import alphareversi.commands.RecvCommand;
import java.util.HashMap;
/**
* Created by Joost<SUF>*/
public class RecvGameMoveCommand extends RecvCommand {
private String player;
private String details;
private String move;
/**
* Parse string to create a filled RecvGamelistCommand.
* @param command string containing server message
*/
public RecvGameMoveCommand(String command) {
String[] parts = command.split(" ", 4);
this.setType(parts[0]);
this.setMethod(parts[1]);
this.setAction(parts[2]);
HashMap objects = CommandParser.parseObjectMap(parts[3]);
this.setPlayer((String) objects.get("PLAYER"));
this.setDetails((String) objects.get("DETAILS"));
this.setMove((String) objects.get("MOVE"));
}
public String getPlayer() {
return player;
}
public void setPlayer(String player) {
this.player = player;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getMove() {
return move;
}
public void setMove(String move) {
this.move = move;
}
}
| false | 379 | 105 | 435 | 120 | 438 | 98 | 435 | 120 | 494 | 124 | false | false | false | false | false | true |
428 | 111105_4 | import javax.swing.plaf.nimbus.State;
import javax.xml.transform.Result;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ReizigerOracleDaoImpl extends OracleBaseDao implements ReizigerDao {
/**
* Returned alle reizigers.
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findAll() {
try {
Statement stmt = getConnection().createStatement();
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM FROM REIZIGER";
ResultSet rs = stmt.executeQuery(query);
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while(rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Reiziger findById(int id) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
return buildreizigerobject(rs);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Returned alle reizigers met specifieke geboortedatum.
* @param GBdatum
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findByGBdatum(Date GBdatum) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER WHERE GEBOORTEDATUM = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setDate(1, GBdatum);
ResultSet rs = stmt.executeQuery();
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while (rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Slaat een reiziger op.
* @param reiziger
* @return
*/
public Reiziger save(Reiziger reiziger) {
try {
String query = "INSERT INTO REIZIGER" +
"(VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM) VALUES " +
"(?, ?, ?, ?)";
String generatedColumns[] = { "REIZIGERID" };
PreparedStatement stmt = getConnection().prepareStatement(query, generatedColumns);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if(rs.next()) {
return findById(rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Past een opgeslagen reiziger aan.
* @param reiziger
* @return Reiziger
*/
public Reiziger update(Reiziger reiziger) {
try {
String query =
"UPDATE REIZIGER SET " +
"VOORLETTERS = ?, TUSSENVOEGSEL = ?, ACHTERNAAM = ?, GEBOORTEDATUM = ? " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.setInt(5, reiziger.getId());
ResultSet rs = stmt.executeQuery();
if (rs.rowUpdated()) {
return findById(reiziger.getId());
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Verwijder een reiziger.
* @param reiziger
* @return boolean
*/
public boolean delete(Reiziger reiziger) {
try {
String query = "DELETE FROM REIZIGER WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, reiziger.getId());
int rs = stmt.executeUpdate();
return rs > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private Reiziger buildreizigerobject(ResultSet rs) throws SQLException {
int id = rs.getInt("REIZIGERID");
Reiziger reiziger = new Reiziger();
reiziger.setId(id);
reiziger.setVoorletters(rs.getString("VOORLETTERS"));
reiziger.setTussenveogsel(rs.getString("TUSSENVOEGSEL"));
reiziger.setAchternaam(rs.getString("ACHTERNAAM"));
reiziger.setGeboortedatum(rs.getDate("GEBOORTEDATUM"));
OVChipkaartDaoImpl ovdao = new OVChipkaartDaoImpl();
reiziger.setKaarten(ovdao.findByReiziger(id));
AdresDaoImpl adao = new AdresDaoImpl();
reiziger.setAdressen(adao.findByReiziger(id));
return reiziger;
}
}
| Donneh/ovcasus | src/ReizigerOracleDaoImpl.java | 1,772 | /**
* Verwijder een reiziger.
* @param reiziger
* @return boolean
*/ | block_comment | nl | import javax.swing.plaf.nimbus.State;
import javax.xml.transform.Result;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ReizigerOracleDaoImpl extends OracleBaseDao implements ReizigerDao {
/**
* Returned alle reizigers.
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findAll() {
try {
Statement stmt = getConnection().createStatement();
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM FROM REIZIGER";
ResultSet rs = stmt.executeQuery(query);
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while(rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Reiziger findById(int id) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
return buildreizigerobject(rs);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Returned alle reizigers met specifieke geboortedatum.
* @param GBdatum
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findByGBdatum(Date GBdatum) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER WHERE GEBOORTEDATUM = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setDate(1, GBdatum);
ResultSet rs = stmt.executeQuery();
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while (rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Slaat een reiziger op.
* @param reiziger
* @return
*/
public Reiziger save(Reiziger reiziger) {
try {
String query = "INSERT INTO REIZIGER" +
"(VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM) VALUES " +
"(?, ?, ?, ?)";
String generatedColumns[] = { "REIZIGERID" };
PreparedStatement stmt = getConnection().prepareStatement(query, generatedColumns);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if(rs.next()) {
return findById(rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Past een opgeslagen reiziger aan.
* @param reiziger
* @return Reiziger
*/
public Reiziger update(Reiziger reiziger) {
try {
String query =
"UPDATE REIZIGER SET " +
"VOORLETTERS = ?, TUSSENVOEGSEL = ?, ACHTERNAAM = ?, GEBOORTEDATUM = ? " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.setInt(5, reiziger.getId());
ResultSet rs = stmt.executeQuery();
if (rs.rowUpdated()) {
return findById(reiziger.getId());
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Verwijder een reiziger.<SUF>*/
public boolean delete(Reiziger reiziger) {
try {
String query = "DELETE FROM REIZIGER WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, reiziger.getId());
int rs = stmt.executeUpdate();
return rs > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private Reiziger buildreizigerobject(ResultSet rs) throws SQLException {
int id = rs.getInt("REIZIGERID");
Reiziger reiziger = new Reiziger();
reiziger.setId(id);
reiziger.setVoorletters(rs.getString("VOORLETTERS"));
reiziger.setTussenveogsel(rs.getString("TUSSENVOEGSEL"));
reiziger.setAchternaam(rs.getString("ACHTERNAAM"));
reiziger.setGeboortedatum(rs.getDate("GEBOORTEDATUM"));
OVChipkaartDaoImpl ovdao = new OVChipkaartDaoImpl();
reiziger.setKaarten(ovdao.findByReiziger(id));
AdresDaoImpl adao = new AdresDaoImpl();
reiziger.setAdressen(adao.findByReiziger(id));
return reiziger;
}
}
| false | 1,325 | 27 | 1,460 | 26 | 1,457 | 27 | 1,456 | 26 | 1,768 | 29 | false | false | false | false | false | true |
2,068 | 99697_1 | package nl.antonsteenvoorden.ikpmd.ui;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import nl.antonsteenvoorden.ikpmd.R;
import nl.antonsteenvoorden.ikpmd.adapter.VakkenAdapter;
import nl.antonsteenvoorden.ikpmd.model.Module;
public class StandVanZakenFragment extends Fragment {
View rootView;
Context context;
ListView listAandacht;
VakkenAdapter vakkenAdapter;
private PieChart standVanZakenChart;
private int maxECTS;
ArrayList<Entry> yValues;
ArrayList<String> xValues;
List<Module> modules;
List<Module> vakkenAandacht;
public StandVanZakenFragment() {
yValues = new ArrayList<>();
xValues = new ArrayList<>();
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static StandVanZakenFragment newInstance() {
StandVanZakenFragment fragment = new StandVanZakenFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_stand_van_zaken, container, false);
listAandacht = (ListView) rootView.findViewById(R.id.stand_van_zaken_list);
vakkenAandacht = new ArrayList<>();
modules = new ArrayList<>();
modules = Module.getAll();
context = rootView.getContext();
calculateECTS();
initChart();
getData();
vakkenAdapter = new VakkenAdapter(context, R.layout.vakken_list_item, vakkenAandacht);
listAandacht.setAdapter(vakkenAdapter);
ButterKnife.bind(this, rootView);
return rootView;
}
@Override
public void onResume() {
super.onResume();
getData();
standVanZakenChart.animateY(1500);
}
public void initChart() {
standVanZakenChart = (PieChart) rootView.findViewById(R.id.chart);
standVanZakenChart.setDescription("");
standVanZakenChart.setTouchEnabled(false);
standVanZakenChart.setDrawSliceText(true);
standVanZakenChart.setDrawHoleEnabled(true);
standVanZakenChart.setHoleColorTransparent(true);
standVanZakenChart.setHoleRadius(85);
standVanZakenChart.setCenterTextColor(Color.rgb(0,188,186));
standVanZakenChart.setCenterText("0/0 \n Studiepunten behaald");
standVanZakenChart.setCenterTextSize(20);
standVanZakenChart.getLegend().setEnabled(false);
standVanZakenChart.animateY(1500);
}
public void calculateECTS() {
modules.clear();
modules = Module.getAll();
for(Module module : modules) {
this.maxECTS += module.getEcts();
}
}
public void getData() {
int tmpEcts = 0;
modules.clear();
vakkenAandacht.clear();
modules = Module.getAll();
for(Module module : modules) {
double tmpGrade = module.getGrade();
if(tmpGrade >= 5.5) {
tmpEcts += module.getEcts();
}
else if(module.isGradeSet() == 1 && tmpGrade <= 5.4){
vakkenAandacht.add(module);
}
}
setData(tmpEcts);
}
private void setData(int aantal) {
String label = (String) getString(R.string.stand_van_zaken_data);
standVanZakenChart.setCenterText(aantal + " / 60 \n"+ label );
if(xValues.size() >= 2 && yValues.size() >= 2) {
yValues.set(0, new Entry(aantal, 0));
yValues.set(1, new Entry(maxECTS-aantal, 1));
} else {
yValues.add(new Entry(aantal, 0));
yValues.add(new Entry(maxECTS - aantal, 1));
xValues.add("Behaalde ECTS");
xValues.add("Resterende ECTS");
}
ArrayList<Integer> colors = new ArrayList<>();
colors.add(Color.rgb(0 ,188,186)); // blue
colors.add(Color.rgb(35 ,10,78)); // deep purple
PieDataSet dataSet = new PieDataSet(yValues, "ECTS");
dataSet.setColors(colors);
dataSet.setDrawValues(false);
PieData data = new PieData(xValues, dataSet);
data.setDrawValues(false);
data.setValueTextSize(0.0f);
standVanZakenChart.setData(data); // bind dataset aan chart.
standVanZakenChart.invalidate(); // Aanroepen van een redraw
//redraw list view
listAandacht.invalidate();
Log.d("aantal ects ", Integer.toString(aantal));
}
}
| antonsteenvoorden/Studie-status | app/src/main/java/nl/antonsteenvoorden/ikpmd/ui/StandVanZakenFragment.java | 1,599 | // bind dataset aan chart. | line_comment | nl | package nl.antonsteenvoorden.ikpmd.ui;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import nl.antonsteenvoorden.ikpmd.R;
import nl.antonsteenvoorden.ikpmd.adapter.VakkenAdapter;
import nl.antonsteenvoorden.ikpmd.model.Module;
public class StandVanZakenFragment extends Fragment {
View rootView;
Context context;
ListView listAandacht;
VakkenAdapter vakkenAdapter;
private PieChart standVanZakenChart;
private int maxECTS;
ArrayList<Entry> yValues;
ArrayList<String> xValues;
List<Module> modules;
List<Module> vakkenAandacht;
public StandVanZakenFragment() {
yValues = new ArrayList<>();
xValues = new ArrayList<>();
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static StandVanZakenFragment newInstance() {
StandVanZakenFragment fragment = new StandVanZakenFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_stand_van_zaken, container, false);
listAandacht = (ListView) rootView.findViewById(R.id.stand_van_zaken_list);
vakkenAandacht = new ArrayList<>();
modules = new ArrayList<>();
modules = Module.getAll();
context = rootView.getContext();
calculateECTS();
initChart();
getData();
vakkenAdapter = new VakkenAdapter(context, R.layout.vakken_list_item, vakkenAandacht);
listAandacht.setAdapter(vakkenAdapter);
ButterKnife.bind(this, rootView);
return rootView;
}
@Override
public void onResume() {
super.onResume();
getData();
standVanZakenChart.animateY(1500);
}
public void initChart() {
standVanZakenChart = (PieChart) rootView.findViewById(R.id.chart);
standVanZakenChart.setDescription("");
standVanZakenChart.setTouchEnabled(false);
standVanZakenChart.setDrawSliceText(true);
standVanZakenChart.setDrawHoleEnabled(true);
standVanZakenChart.setHoleColorTransparent(true);
standVanZakenChart.setHoleRadius(85);
standVanZakenChart.setCenterTextColor(Color.rgb(0,188,186));
standVanZakenChart.setCenterText("0/0 \n Studiepunten behaald");
standVanZakenChart.setCenterTextSize(20);
standVanZakenChart.getLegend().setEnabled(false);
standVanZakenChart.animateY(1500);
}
public void calculateECTS() {
modules.clear();
modules = Module.getAll();
for(Module module : modules) {
this.maxECTS += module.getEcts();
}
}
public void getData() {
int tmpEcts = 0;
modules.clear();
vakkenAandacht.clear();
modules = Module.getAll();
for(Module module : modules) {
double tmpGrade = module.getGrade();
if(tmpGrade >= 5.5) {
tmpEcts += module.getEcts();
}
else if(module.isGradeSet() == 1 && tmpGrade <= 5.4){
vakkenAandacht.add(module);
}
}
setData(tmpEcts);
}
private void setData(int aantal) {
String label = (String) getString(R.string.stand_van_zaken_data);
standVanZakenChart.setCenterText(aantal + " / 60 \n"+ label );
if(xValues.size() >= 2 && yValues.size() >= 2) {
yValues.set(0, new Entry(aantal, 0));
yValues.set(1, new Entry(maxECTS-aantal, 1));
} else {
yValues.add(new Entry(aantal, 0));
yValues.add(new Entry(maxECTS - aantal, 1));
xValues.add("Behaalde ECTS");
xValues.add("Resterende ECTS");
}
ArrayList<Integer> colors = new ArrayList<>();
colors.add(Color.rgb(0 ,188,186)); // blue
colors.add(Color.rgb(35 ,10,78)); // deep purple
PieDataSet dataSet = new PieDataSet(yValues, "ECTS");
dataSet.setColors(colors);
dataSet.setDrawValues(false);
PieData data = new PieData(xValues, dataSet);
data.setDrawValues(false);
data.setValueTextSize(0.0f);
standVanZakenChart.setData(data); // bind dataset<SUF>
standVanZakenChart.invalidate(); // Aanroepen van een redraw
//redraw list view
listAandacht.invalidate();
Log.d("aantal ects ", Integer.toString(aantal));
}
}
| false | 1,193 | 6 | 1,405 | 6 | 1,439 | 6 | 1,405 | 6 | 1,617 | 6 | false | false | false | false | false | true |
3,200 | 85648_5 | package nl.han.ica.spookrijder;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.SpriteObject;
import nl.han.ica.OOPDProcessingEngineHAN.Sound.Sound;
public abstract class VerzamelObject extends SpriteObject {
private Spookrijder spookrijder;
private boolean aangeraakt = false;
private int breedte;
private int hoogte;
protected String geluidsnaam; // naam van geluidsbestand
public VerzamelObject(Spookrijder spookrijder, Sprite sprite) {
super(sprite);
this.spookrijder = spookrijder;
setxSpeed(-3);
}
/**
* Update
*
* Zet aangeraakt status en zichtbaarheid op basis van x positie.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
@Override
public void update() {
if (this.getX() < (0 - this.getWidth())) {
this.setX(spookrijder.getWidth() + this.getWidth());
this.setAangeraakt(false);
this.setVisible(true);
}
}
/**
* Zet aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setAangeraakt(boolean aangeraakt) {
this.aangeraakt = aangeraakt;
}
/**
* Verkrijg aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @return Aangeraakt-status van het object.
* @version 1.0
*/
public boolean getAangeraakt() {
return this.aangeraakt;
}
/**
* Verkrijg hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De hoogte van het object.
* @since 11-05-2018
* @version 1.0
*/
public float getHeight() {
return this.hoogte;
}
/**
* Verkrijg breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De breedte van het object.
* @since 11-05-2018
* @version 1.0
*/
public float getWidth() {
return this.breedte;
}
/**
* Zet hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setHeight(int hoogte) {
this.hoogte = hoogte;
}
/**
* Zet breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setWidth(int breedte) {
this.breedte = breedte;
}
/**
* Doe Geluid
*
* Initialiseert een geluidsobject en speelt deze af.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void doeGeluid() {
Sound geluid = new Sound(spookrijder,
"src/main/java/nl/han/ica/spookrijder/media/" + this.geluidsnaam + ".mp3");
geluid.play();
}
}
| jeffreyvr/spookrijder | src/main/java/nl/han/ica/spookrijder/VerzamelObject.java | 1,032 | /**
* Verkrijg breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De breedte van het object.
* @since 11-05-2018
* @version 1.0
*/ | block_comment | nl | package nl.han.ica.spookrijder;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.SpriteObject;
import nl.han.ica.OOPDProcessingEngineHAN.Sound.Sound;
public abstract class VerzamelObject extends SpriteObject {
private Spookrijder spookrijder;
private boolean aangeraakt = false;
private int breedte;
private int hoogte;
protected String geluidsnaam; // naam van geluidsbestand
public VerzamelObject(Spookrijder spookrijder, Sprite sprite) {
super(sprite);
this.spookrijder = spookrijder;
setxSpeed(-3);
}
/**
* Update
*
* Zet aangeraakt status en zichtbaarheid op basis van x positie.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
@Override
public void update() {
if (this.getX() < (0 - this.getWidth())) {
this.setX(spookrijder.getWidth() + this.getWidth());
this.setAangeraakt(false);
this.setVisible(true);
}
}
/**
* Zet aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setAangeraakt(boolean aangeraakt) {
this.aangeraakt = aangeraakt;
}
/**
* Verkrijg aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @return Aangeraakt-status van het object.
* @version 1.0
*/
public boolean getAangeraakt() {
return this.aangeraakt;
}
/**
* Verkrijg hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De hoogte van het object.
* @since 11-05-2018
* @version 1.0
*/
public float getHeight() {
return this.hoogte;
}
/**
* Verkrijg breedte
<SUF>*/
public float getWidth() {
return this.breedte;
}
/**
* Zet hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setHeight(int hoogte) {
this.hoogte = hoogte;
}
/**
* Zet breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setWidth(int breedte) {
this.breedte = breedte;
}
/**
* Doe Geluid
*
* Initialiseert een geluidsobject en speelt deze af.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void doeGeluid() {
Sound geluid = new Sound(spookrijder,
"src/main/java/nl/han/ica/spookrijder/media/" + this.geluidsnaam + ".mp3");
geluid.play();
}
}
| false | 905 | 66 | 1,026 | 67 | 984 | 67 | 1,026 | 67 | 1,109 | 72 | false | false | false | false | false | true |
4,800 | 195998_8 | /**
* Copyright (c) 2012, 2013 SURFnet BV
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package nl.surfnet.bod.search;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import java.util.List;
import nl.surfnet.bod.domain.UniPort;
import org.apache.lucene.queryParser.ParseException;
import org.junit.Test;
public class PhysicalPortIndexAndSearchTest extends AbstractIndexAndSearch<UniPort> {
public PhysicalPortIndexAndSearchTest() {
super(UniPort.class);
}
@Test
public void testIndexAndSearch() throws Exception {
List<UniPort> physicalPorts = searchFor("gamma");
// (N.A.)
assertThat(physicalPorts, hasSize(0));
physicalPorts = searchFor("ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Mock");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
physicalPorts = searchFor("ETH-1-13-4");
// (Noc label 4)
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("OME");
// (Mock_Ut002A_OME01_ETH-1-2-4, Mock_Ut001A_OME01_ETH-1-2-1)
assertThat(physicalPorts, hasSize(2));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
physicalPorts = searchFor("ETH-1-");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1de");
// Mock_port 1de verdieping toren1a
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 1de verdieping toren1a"));
physicalPorts = searchFor("2de");
// Mock_port 2de verdieping toren1b
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 2de verdieping toren1b"));
}
@Test
public void shouldNotCrashOnColon() throws ParseException {
List<UniPort> physicalPorts = searchFor("nocLabel:\"Noc 3 label\"");
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 3 label"));
}
} | zanetworker/bandwidth-on-demand | src/test/java/nl/surfnet/bod/search/PhysicalPortIndexAndSearchTest.java | 1,581 | // Mock_port 2de verdieping toren1b | line_comment | nl | /**
* Copyright (c) 2012, 2013 SURFnet BV
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package nl.surfnet.bod.search;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import java.util.List;
import nl.surfnet.bod.domain.UniPort;
import org.apache.lucene.queryParser.ParseException;
import org.junit.Test;
public class PhysicalPortIndexAndSearchTest extends AbstractIndexAndSearch<UniPort> {
public PhysicalPortIndexAndSearchTest() {
super(UniPort.class);
}
@Test
public void testIndexAndSearch() throws Exception {
List<UniPort> physicalPorts = searchFor("gamma");
// (N.A.)
assertThat(physicalPorts, hasSize(0));
physicalPorts = searchFor("ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Mock");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
physicalPorts = searchFor("ETH-1-13-4");
// (Noc label 4)
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("OME");
// (Mock_Ut002A_OME01_ETH-1-2-4, Mock_Ut001A_OME01_ETH-1-2-1)
assertThat(physicalPorts, hasSize(2));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
physicalPorts = searchFor("ETH-1-");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1de");
// Mock_port 1de verdieping toren1a
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 1de verdieping toren1a"));
physicalPorts = searchFor("2de");
// Mock_port 2de<SUF>
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 2de verdieping toren1b"));
}
@Test
public void shouldNotCrashOnColon() throws ParseException {
List<UniPort> physicalPorts = searchFor("nocLabel:\"Noc 3 label\"");
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 3 label"));
}
} | false | 1,237 | 13 | 1,311 | 15 | 1,358 | 12 | 1,311 | 15 | 1,742 | 14 | false | false | false | false | false | true |
1,669 | 30811_1 | package nl.sjoelclub.competitie.score;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional //Mag operaties op de database doen.
public class ScoreService {
@Autowired //Verbinding tussen repository en service. Zorgt ervoor dat je een object van Repository tot beschikking hebt (eigenlijk interface)
private ScoreRepository scoreRepository;
public Score save(Score score) {
return scoreRepository.save(score);
}
public Iterable<Score> findAll() { //Iterable is een verzameling op het hoogste niveau. Doorheenloopbaar.
Iterable<Score> result = scoreRepository.findAll();
return result;
}
}
| SweerenK/sjoelclub | src/main/java/nl/sjoelclub/competitie/score/ScoreService.java | 221 | //Verbinding tussen repository en service. Zorgt ervoor dat je een object van Repository tot beschikking hebt (eigenlijk interface) | line_comment | nl | package nl.sjoelclub.competitie.score;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional //Mag operaties op de database doen.
public class ScoreService {
@Autowired //Verbinding tussen<SUF>
private ScoreRepository scoreRepository;
public Score save(Score score) {
return scoreRepository.save(score);
}
public Iterable<Score> findAll() { //Iterable is een verzameling op het hoogste niveau. Doorheenloopbaar.
Iterable<Score> result = scoreRepository.findAll();
return result;
}
}
| false | 160 | 29 | 204 | 32 | 192 | 26 | 204 | 32 | 236 | 32 | false | false | false | false | false | true |
4,124 | 37735_6 | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package gui;_x000D_
_x000D_
import domein.DomeinController;_x000D_
import javafx.event.ActionEvent;_x000D_
import javafx.event.EventHandler;_x000D_
import javafx.geometry.Insets;_x000D_
import javafx.geometry.Pos;_x000D_
import javafx.scene.Scene;_x000D_
import javafx.scene.control.Button;_x000D_
import javafx.scene.layout.BorderPane;_x000D_
import javafx.scene.layout.GridPane;_x000D_
import javafx.stage.Stage;_x000D_
_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author bjorn_x000D_
*/_x000D_
public class Startscherm extends BorderPane {_x000D_
_x000D_
private final DomeinController dc;_x000D_
_x000D_
public Startscherm(DomeinController dc) {_x000D_
this.dc = dc;_x000D_
buildGui();_x000D_
}_x000D_
_x000D_
private void buildGui(){_x000D_
_x000D_
_x000D_
_x000D_
//Panes/Boxes/CSS ********************************************************************* _x000D_
getStylesheets().add("/css/startscherm.css");_x000D_
GridPane gpane = new GridPane();_x000D_
//setCancelDefault fzoiets vr via escape terug naar vorig scherm_x000D_
_x000D_
//Start button ************************************************************************ _x000D_
_x000D_
Button btnStart = new Button();_x000D_
btnStart.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnStartOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnStart.setId("btnStart");_x000D_
btnStart.setPrefSize(200, 50);_x000D_
//btnStart.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Resume button ************************************************************************ _x000D_
// Enkel resume game als er al een game in het spel is!_x000D_
Button btnResume = new Button();_x000D_
btnResume.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnResumeOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnResume.setDisable(true);_x000D_
btnResume.setId("btnResume");_x000D_
btnResume.setPrefSize(200, 50);_x000D_
//btnResume.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Highscores button ************************************************************************ _x000D_
Button btnHighScores = new Button();_x000D_
btnHighScores.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnHighscoresOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnHighScores.setId("btnHighScores");_x000D_
btnHighScores.setPrefSize(200, 50);_x000D_
//btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
_x000D_
//Rules button ************************************************************************ _x000D_
Button btnGameRules = new Button();_x000D_
btnGameRules.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnGameRulesOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnGameRules.setId("btnGameRules");_x000D_
btnGameRules.setPrefSize(200, 50);_x000D_
// btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Centering van de Gridpane ***************************************************************_x000D_
_x000D_
gpane.add(btnStart, 0, 0);_x000D_
gpane.add(btnResume, 0, 1);_x000D_
gpane.add(btnHighScores, 0, 2);_x000D_
gpane.add(btnGameRules, 0, 3);_x000D_
gpane.setAlignment(Pos.CENTER);_x000D_
gpane.setPadding(new Insets(50,5,5,5));_x000D_
gpane.setHgap(1);_x000D_
gpane.setVgap(1);_x000D_
setCenter(gpane);_x000D_
_x000D_
}_x000D_
_x000D_
private void btnStartOnAction(ActionEvent event)_x000D_
{_x000D_
//dc.deleteData() = mogelijke methode om nieuw spel te starten_x000D_
SpelersSettings ss = new SpelersSettings(this, dc);_x000D_
Scene scene = new Scene(ss, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
private void btnHighscoresOnAction(ActionEvent event)_x000D_
{_x000D_
HighscoreScherm hs = new HighscoreScherm(this, dc);_x000D_
Scene scene = new Scene(hs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
private void btnResumeOnAction(ActionEvent event)_x000D_
{/*_x000D_
// dc aanspreken + vullen met sepl dat laatste werd opgeslagen en onderbroken_x000D_
dc.vulDomein();_x000D_
OverzichtScherm overzichtscherm = new OverzichtScherm(dc,dc.geefSpelInfo()[1],1);_x000D_
Scene scene = new Scene(overzichtscherm,1250,700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
*/_x000D_
}_x000D_
_x000D_
private void btnGameRulesOnAction(ActionEvent event)_x000D_
{_x000D_
GameRulesScherm grs = new GameRulesScherm(this, dc);_x000D_
Scene scene = new Scene(grs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
}_x000D_
}_x000D_
| rayzorg/regenworm | src/gui/Startscherm.java | 1,569 | // Enkel resume game als er al een game in het spel is!_x000D_ | line_comment | nl | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package gui;_x000D_
_x000D_
import domein.DomeinController;_x000D_
import javafx.event.ActionEvent;_x000D_
import javafx.event.EventHandler;_x000D_
import javafx.geometry.Insets;_x000D_
import javafx.geometry.Pos;_x000D_
import javafx.scene.Scene;_x000D_
import javafx.scene.control.Button;_x000D_
import javafx.scene.layout.BorderPane;_x000D_
import javafx.scene.layout.GridPane;_x000D_
import javafx.stage.Stage;_x000D_
_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author bjorn_x000D_
*/_x000D_
public class Startscherm extends BorderPane {_x000D_
_x000D_
private final DomeinController dc;_x000D_
_x000D_
public Startscherm(DomeinController dc) {_x000D_
this.dc = dc;_x000D_
buildGui();_x000D_
}_x000D_
_x000D_
private void buildGui(){_x000D_
_x000D_
_x000D_
_x000D_
//Panes/Boxes/CSS ********************************************************************* _x000D_
getStylesheets().add("/css/startscherm.css");_x000D_
GridPane gpane = new GridPane();_x000D_
//setCancelDefault fzoiets vr via escape terug naar vorig scherm_x000D_
_x000D_
//Start button ************************************************************************ _x000D_
_x000D_
Button btnStart = new Button();_x000D_
btnStart.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnStartOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnStart.setId("btnStart");_x000D_
btnStart.setPrefSize(200, 50);_x000D_
//btnStart.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Resume button ************************************************************************ _x000D_
// Enkel resume<SUF>
Button btnResume = new Button();_x000D_
btnResume.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnResumeOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnResume.setDisable(true);_x000D_
btnResume.setId("btnResume");_x000D_
btnResume.setPrefSize(200, 50);_x000D_
//btnResume.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Highscores button ************************************************************************ _x000D_
Button btnHighScores = new Button();_x000D_
btnHighScores.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnHighscoresOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnHighScores.setId("btnHighScores");_x000D_
btnHighScores.setPrefSize(200, 50);_x000D_
//btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
_x000D_
//Rules button ************************************************************************ _x000D_
Button btnGameRules = new Button();_x000D_
btnGameRules.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnGameRulesOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnGameRules.setId("btnGameRules");_x000D_
btnGameRules.setPrefSize(200, 50);_x000D_
// btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Centering van de Gridpane ***************************************************************_x000D_
_x000D_
gpane.add(btnStart, 0, 0);_x000D_
gpane.add(btnResume, 0, 1);_x000D_
gpane.add(btnHighScores, 0, 2);_x000D_
gpane.add(btnGameRules, 0, 3);_x000D_
gpane.setAlignment(Pos.CENTER);_x000D_
gpane.setPadding(new Insets(50,5,5,5));_x000D_
gpane.setHgap(1);_x000D_
gpane.setVgap(1);_x000D_
setCenter(gpane);_x000D_
_x000D_
}_x000D_
_x000D_
private void btnStartOnAction(ActionEvent event)_x000D_
{_x000D_
//dc.deleteData() = mogelijke methode om nieuw spel te starten_x000D_
SpelersSettings ss = new SpelersSettings(this, dc);_x000D_
Scene scene = new Scene(ss, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
private void btnHighscoresOnAction(ActionEvent event)_x000D_
{_x000D_
HighscoreScherm hs = new HighscoreScherm(this, dc);_x000D_
Scene scene = new Scene(hs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
private void btnResumeOnAction(ActionEvent event)_x000D_
{/*_x000D_
// dc aanspreken + vullen met sepl dat laatste werd opgeslagen en onderbroken_x000D_
dc.vulDomein();_x000D_
OverzichtScherm overzichtscherm = new OverzichtScherm(dc,dc.geefSpelInfo()[1],1);_x000D_
Scene scene = new Scene(overzichtscherm,1250,700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
*/_x000D_
}_x000D_
_x000D_
private void btnGameRulesOnAction(ActionEvent event)_x000D_
{_x000D_
GameRulesScherm grs = new GameRulesScherm(this, dc);_x000D_
Scene scene = new Scene(grs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
}_x000D_
}_x000D_
| false | 2,131 | 22 | 2,293 | 23 | 2,394 | 21 | 2,293 | 23 | 2,589 | 23 | false | false | false | false | false | true |
1,355 | 70583_7 |
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;
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);
tile.x = (colom * TILE_WIDTH) + TILE_WIDTH / 2;
tile.y = (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-20Jorden01 | TileEngine.java | 2,484 | // Nummer ophalen in de int array | 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;
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<SUF>
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);
tile.x = (colom * TILE_WIDTH) + TILE_WIDTH / 2;
tile.y = (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;
}
}
| false | 2,015 | 10 | 2,123 | 11 | 2,313 | 8 | 2,141 | 11 | 2,542 | 10 | false | false | false | false | false | true |
4,652 | 84266_1 | package nl.vpro.amara;
import java.io.IOException;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.vpro.amara.domain.Action;
import nl.vpro.amara.domain.Subtitles;
import nl.vpro.amara_poms.Config;
import nl.vpro.amara_poms.poms.PomsBroadcast;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author joost
*/
public class SubtitlesTest {
final static Logger LOG = LoggerFactory.getLogger(SubtitlesTest.class);
@BeforeEach
public void setUp() {
Config.init();
}
@Test
public void testDummy() {
assertTrue(true);
}
@Test
public void testPost() {
Subtitles amaraSubtitles = new Subtitles("test subtitles", "vtt",
"WEBVTT\n" +
"\n" +
"1\n" +
"00:00:02.018 --> 00:00:05.007\n" +
"888\n" +
"\n" +
"2\n" +
"00:00:05.012 --> 00:00:07.018\n" +
"TUNE VAN DWDD\n", "test description", "complete");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, "gDq7bAA5XFCR", "nl");
assertNotNull(newAmaraSubtitles);
}
@Test
public void getActions() {
String video_id = "Ep1jZa6c2NRt";
List<Action> actions = Config.getAmaraClient().videos().getActions(video_id, "nl");
System.out.println("" + actions);
}
@Test
public void amarapoms3() throws IOException {
String video_id = "Ep1jZa6c2NRt";
PomsBroadcast pomsBroadcast = new PomsBroadcast("VPWON_1256298", null);
pomsBroadcast.downloadSubtitles();
Subtitles amaraSubtitles = new Subtitles("Blauw Bloed // Een interview met prinses Irene", "vtt",
pomsBroadcast.getSubtitles(), "Een interview met prinses Irene, we volgen koning Willem-Alexander bij de start van de Giro d'Italia en couturier Paul Schulten vertelt alles over koninklijke bloemetjesjurken.", "save-draft");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, video_id, "nl");
assertNotNull(newAmaraSubtitles);
}
public void testGetVTT() {
String amaraSubtitles = Config.getAmaraClient().videos().getAsVTT("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(amaraSubtitles);
}
public void testGet() {
Subtitles amaraSubtitles = Config.getAmaraClient().videos().getSubtitles("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(StringUtils.abbreviate(amaraSubtitles.getSubtitles(), 20));
LOG.info((amaraSubtitles.getVersion_no()));
}
}
| vpro/amara-poms | src/test/java/nl/vpro/amara/SubtitlesTest.java | 1,053 | // Een interview met prinses Irene", "vtt", | line_comment | nl | package nl.vpro.amara;
import java.io.IOException;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.vpro.amara.domain.Action;
import nl.vpro.amara.domain.Subtitles;
import nl.vpro.amara_poms.Config;
import nl.vpro.amara_poms.poms.PomsBroadcast;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author joost
*/
public class SubtitlesTest {
final static Logger LOG = LoggerFactory.getLogger(SubtitlesTest.class);
@BeforeEach
public void setUp() {
Config.init();
}
@Test
public void testDummy() {
assertTrue(true);
}
@Test
public void testPost() {
Subtitles amaraSubtitles = new Subtitles("test subtitles", "vtt",
"WEBVTT\n" +
"\n" +
"1\n" +
"00:00:02.018 --> 00:00:05.007\n" +
"888\n" +
"\n" +
"2\n" +
"00:00:05.012 --> 00:00:07.018\n" +
"TUNE VAN DWDD\n", "test description", "complete");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, "gDq7bAA5XFCR", "nl");
assertNotNull(newAmaraSubtitles);
}
@Test
public void getActions() {
String video_id = "Ep1jZa6c2NRt";
List<Action> actions = Config.getAmaraClient().videos().getActions(video_id, "nl");
System.out.println("" + actions);
}
@Test
public void amarapoms3() throws IOException {
String video_id = "Ep1jZa6c2NRt";
PomsBroadcast pomsBroadcast = new PomsBroadcast("VPWON_1256298", null);
pomsBroadcast.downloadSubtitles();
Subtitles amaraSubtitles = new Subtitles("Blauw Bloed // Een interview<SUF>
pomsBroadcast.getSubtitles(), "Een interview met prinses Irene, we volgen koning Willem-Alexander bij de start van de Giro d'Italia en couturier Paul Schulten vertelt alles over koninklijke bloemetjesjurken.", "save-draft");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, video_id, "nl");
assertNotNull(newAmaraSubtitles);
}
public void testGetVTT() {
String amaraSubtitles = Config.getAmaraClient().videos().getAsVTT("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(amaraSubtitles);
}
public void testGet() {
Subtitles amaraSubtitles = Config.getAmaraClient().videos().getSubtitles("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(StringUtils.abbreviate(amaraSubtitles.getSubtitles(), 20));
LOG.info((amaraSubtitles.getVersion_no()));
}
}
| false | 797 | 13 | 926 | 17 | 931 | 12 | 926 | 17 | 1,083 | 14 | false | false | false | false | false | true |
684 | 74866_11 | package controller;
import database.mysql.CourseDAO;
import database.mysql.QuestionDAO;
import database.mysql.QuizDAO;
import javacouchdb.CouchDBaccess;
import javacouchdb.QuizResultCouchDBDAO;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import model.Question;
import model.Quiz;
import model.QuizResult;
import view.Main;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FillOutQuizController {
private final QuestionDAO questionDAO = new QuestionDAO(Main.getDBaccess());
private final QuizDAO quizDAO = new QuizDAO(Main.getDBaccess());
CouchDBaccess couchDBaccess = new CouchDBaccess("quizmaster","admin", "admin");
private final QuizResultCouchDBDAO quizResultCouchDBDAO = new QuizResultCouchDBDAO(couchDBaccess);
List<Question> questionsQuiz = new ArrayList<>();
private int currentQuestionNumber;
private int vraagNummer = 1;
private int correctAnswers;
private int loginUserId;
private int quizId;
@FXML
private Label titleLabel;
@FXML
private TextArea questionArea;
@FXML
private Button answerA;
@FXML
private Button answerB;
@FXML
private Button answerC;
@FXML
private Button answerD;
@FXML
private Button previousQuestion;
@FXML
private Button nextQuestion;
@FXML
private Button finishQuiz;
@FXML
private Button back;
public void setup(int quizId, int userId) {
loginUserId = userId;
this.quizId = quizId;
//verzamel de vragen die horen bij ingegeven quizId
questionsQuiz = questionDAO.getQuestionsByQuizId(quizId);
//schud de vragen door elkaar
Collections.shuffle(questionsQuiz);
//beginnen met de 1e vraag
currentQuestionNumber = 0;
//score initializeren
correctAnswers = 0;
//Titel
titleLabel.setText("Vraag " + vraagNummer);
//1e vraag tonen
displayQuestion();
}
private void displayQuestion() {
//zolang currenctQuestionNumber tussen 0 en size van questionQuiz zit,
// wordt er een nieuwe vraag met antwoorden getoond
if (currentQuestionNumber >= 0 && currentQuestionNumber < questionsQuiz.size()){
Question currentQuestion = questionsQuiz.get(currentQuestionNumber);
//lijst van antwoorden maken en deze door elkaar shuffelen
ArrayList<String> answerChoices = new ArrayList<>();
answerChoices.add(currentQuestion.getCorrectAnswer());
answerChoices.add(currentQuestion.getAnswer2());
answerChoices.add(currentQuestion.getAnswer3());
answerChoices.add(currentQuestion.getAnswer4());
Collections.shuffle(answerChoices);
//Toon de vraag en de geshuffelde antwoorden in de textarea
String question = currentQuestion.getTextQuestion() + "\n";
String answers = "A. " + answerChoices.get(0) + "\n" +
"B. " + answerChoices.get(1) + "\n" +
"C. " + answerChoices.get(2) + "\n" +
"D. " + answerChoices.get(3);
questionArea.setText(question + answers);
//Button acties instellen
answerA.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(0)));
answerB.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(1)));
answerC.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(2)));
answerD.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(3)));
//aangeven wanneer knoppen next en previous niet werken
nextQuestion.setVisible(currentQuestionNumber != questionsQuiz.size() - 1);
finishQuiz.setVisible(currentQuestionNumber == questionsQuiz.size() - 1);
previousQuestion.setDisable(currentQuestionNumber == 0);
}
}
//Methode die controleert of de String van het gekozen antwoord van de currentQuestion
//overeenkomt met het attribuut correctAnswer van de currentQuestion.
//Als dit het geval is gaat correctAnswers 1 omhoog
private void checkAnswer(Question currentQuestion, String selectedAnswer) {
if (selectedAnswer.equals(currentQuestion.getCorrectAnswer())) {
correctAnswers++;
}
//volgende vraag tonen
currentQuestionNumber++;
vraagNummer++;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
//volgende vraag tonen
public void doNextQuestion() {
currentQuestionNumber++;
vraagNummer++;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
//vorige vraag tonen
public void doPreviousQuestion() {
currentQuestionNumber--;
vraagNummer--;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
public void doMenu() {
Main.getSceneManager().showSelectQuizForStudent(loginUserId);
}
public void doFinishQuiz () {
QuizResult quizResult = new QuizResult(loginUserId, quizId, quizDAO.getOneById(quizId).getSuccesDefinition(), LocalDateTime.now().toString(), correctAnswers, questionsQuiz.size());
quizResultCouchDBDAO.saveSingleQuizResult(quizResult);
Main.getSceneManager().showStudentFeedback(loginUserId, quizDAO.getOneById(quizId));
}
}
| Hayac1113/Quiz_System_Project | src/main/java/controller/FillOutQuizController.java | 1,637 | //overeenkomt met het attribuut correctAnswer van de currentQuestion. | line_comment | nl | package controller;
import database.mysql.CourseDAO;
import database.mysql.QuestionDAO;
import database.mysql.QuizDAO;
import javacouchdb.CouchDBaccess;
import javacouchdb.QuizResultCouchDBDAO;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import model.Question;
import model.Quiz;
import model.QuizResult;
import view.Main;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FillOutQuizController {
private final QuestionDAO questionDAO = new QuestionDAO(Main.getDBaccess());
private final QuizDAO quizDAO = new QuizDAO(Main.getDBaccess());
CouchDBaccess couchDBaccess = new CouchDBaccess("quizmaster","admin", "admin");
private final QuizResultCouchDBDAO quizResultCouchDBDAO = new QuizResultCouchDBDAO(couchDBaccess);
List<Question> questionsQuiz = new ArrayList<>();
private int currentQuestionNumber;
private int vraagNummer = 1;
private int correctAnswers;
private int loginUserId;
private int quizId;
@FXML
private Label titleLabel;
@FXML
private TextArea questionArea;
@FXML
private Button answerA;
@FXML
private Button answerB;
@FXML
private Button answerC;
@FXML
private Button answerD;
@FXML
private Button previousQuestion;
@FXML
private Button nextQuestion;
@FXML
private Button finishQuiz;
@FXML
private Button back;
public void setup(int quizId, int userId) {
loginUserId = userId;
this.quizId = quizId;
//verzamel de vragen die horen bij ingegeven quizId
questionsQuiz = questionDAO.getQuestionsByQuizId(quizId);
//schud de vragen door elkaar
Collections.shuffle(questionsQuiz);
//beginnen met de 1e vraag
currentQuestionNumber = 0;
//score initializeren
correctAnswers = 0;
//Titel
titleLabel.setText("Vraag " + vraagNummer);
//1e vraag tonen
displayQuestion();
}
private void displayQuestion() {
//zolang currenctQuestionNumber tussen 0 en size van questionQuiz zit,
// wordt er een nieuwe vraag met antwoorden getoond
if (currentQuestionNumber >= 0 && currentQuestionNumber < questionsQuiz.size()){
Question currentQuestion = questionsQuiz.get(currentQuestionNumber);
//lijst van antwoorden maken en deze door elkaar shuffelen
ArrayList<String> answerChoices = new ArrayList<>();
answerChoices.add(currentQuestion.getCorrectAnswer());
answerChoices.add(currentQuestion.getAnswer2());
answerChoices.add(currentQuestion.getAnswer3());
answerChoices.add(currentQuestion.getAnswer4());
Collections.shuffle(answerChoices);
//Toon de vraag en de geshuffelde antwoorden in de textarea
String question = currentQuestion.getTextQuestion() + "\n";
String answers = "A. " + answerChoices.get(0) + "\n" +
"B. " + answerChoices.get(1) + "\n" +
"C. " + answerChoices.get(2) + "\n" +
"D. " + answerChoices.get(3);
questionArea.setText(question + answers);
//Button acties instellen
answerA.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(0)));
answerB.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(1)));
answerC.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(2)));
answerD.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(3)));
//aangeven wanneer knoppen next en previous niet werken
nextQuestion.setVisible(currentQuestionNumber != questionsQuiz.size() - 1);
finishQuiz.setVisible(currentQuestionNumber == questionsQuiz.size() - 1);
previousQuestion.setDisable(currentQuestionNumber == 0);
}
}
//Methode die controleert of de String van het gekozen antwoord van de currentQuestion
//overeenkomt met<SUF>
//Als dit het geval is gaat correctAnswers 1 omhoog
private void checkAnswer(Question currentQuestion, String selectedAnswer) {
if (selectedAnswer.equals(currentQuestion.getCorrectAnswer())) {
correctAnswers++;
}
//volgende vraag tonen
currentQuestionNumber++;
vraagNummer++;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
//volgende vraag tonen
public void doNextQuestion() {
currentQuestionNumber++;
vraagNummer++;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
//vorige vraag tonen
public void doPreviousQuestion() {
currentQuestionNumber--;
vraagNummer--;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
public void doMenu() {
Main.getSceneManager().showSelectQuizForStudent(loginUserId);
}
public void doFinishQuiz () {
QuizResult quizResult = new QuizResult(loginUserId, quizId, quizDAO.getOneById(quizId).getSuccesDefinition(), LocalDateTime.now().toString(), correctAnswers, questionsQuiz.size());
quizResultCouchDBDAO.saveSingleQuizResult(quizResult);
Main.getSceneManager().showStudentFeedback(loginUserId, quizDAO.getOneById(quizId));
}
}
| false | 1,221 | 17 | 1,362 | 19 | 1,357 | 15 | 1,362 | 19 | 1,610 | 18 | false | false | false | false | false | true |
1,559 | 69709_0 | package com.example.sanjiv.awarenessapp;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LampDetails extends AppCompatActivity implements View.OnClickListener {
private TextView naam, brightness, maxDecibel, huidigeDecibel;
private Button edit, notify, removeNotify;
private FirebaseDatabase database;
private FirebaseAuth auth;
private FirebaseUser user;
private DatabaseReference mDatabase;
private String key, lampNaam, userRole;
private boolean isNotifyOn;
private Lampen lamp;
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lamp_details);
naam = findViewById(R.id.naamLamp);
maxDecibel = findViewById(R.id.MaxDecibel);
huidigeDecibel = findViewById(R.id.HuidigeDecibel);
edit = findViewById(R.id.editLamp);
notify = findViewById(R.id.addNotify);
removeNotify = findViewById(R.id.removeNotify);
edit.setOnClickListener(this);
notify.setOnClickListener(this);
removeNotify.setOnClickListener(this);
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
user = auth.getCurrentUser();
mDatabase = database.getReference();
//Scherm in het fragment, backPress brengt je terug naar Lampen fragment
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .95), (int) (height * .9));
naam.setText(getIntent().getStringExtra("naam"));
maxDecibel.setText(getIntent().getStringExtra("maxDecibel"));
huidigeDecibel.setText(getIntent().getStringExtra("huidigeDecibel"));
isNotifyOn = Boolean.parseBoolean(getIntent().getStringExtra("notifyOn"));
Log.d("ADebugTag", "notifyOn = " + isNotifyOn);
edit.setVisibility(View.GONE);
notify.setVisibility(View.GONE);
removeNotify.setVisibility(View.GONE);
if (isNotifyOn) {
removeNotify.setVisibility(View.VISIBLE);
} else {
notify.setVisibility(View.VISIBLE);
}
userIsAdmin();
}
@Override
public void onClick(View v) {
if (v == edit) {
Intent intent = new Intent(this, EditLamp.class);
intent.putExtra("naam", getIntent().getStringExtra("naam"));
intent.putExtra("key", getIntent().getStringExtra("key"));
intent.putExtra("huidigeDecibel", getIntent().getStringExtra("huidigeDecibel"));
intent.putExtra("maxDecibel", getIntent().getStringExtra("maxDecibel"));
this.startActivity(intent);
}
if (v == notify) {
Intent intent = new Intent(this, AddNotifyLamp.class);
intent.putExtra("naam", getIntent().getStringExtra("naam"));
intent.putExtra("key", getIntent().getStringExtra("key"));
intent.putExtra("huidigeDecibel", getIntent().getStringExtra("huidigeDecibel"));
intent.putExtra("maxDecibel", getIntent().getStringExtra("maxDecibel"));
this.startActivity(intent);
}
if (v == removeNotify) {
Intent intent = new Intent(this, DeleteNotifyLamp.class);
intent.putExtra("key", getIntent().getStringExtra("key"));
this.startActivity(intent);
}
}
public void userIsAdmin() {
DatabaseReference ref_userRole = mDatabase.child("users").child(user.getUid()).child("rollen");
ref_userRole.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserModel userM = dataSnapshot.getValue(UserModel.class);
userRole = userM.getUserRole();
Log.d("ADebugTag", "Value from database: " + userRole);
updateButtons();
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.d("Lamps", "credentialsUserRoleGet:failure", databaseError.toException());
}
});
}
public void updateButtons() {
if (userRole != null) {
if (userRole.equalsIgnoreCase("admin")) {
Log.d("ADebugTag", "Value from updateButtons: " + userRole);
edit.setVisibility(View.VISIBLE);
}
}
}
}
| Sannijiv/AwarenessApp | app/src/main/java/com/example/sanjiv/awarenessapp/LampDetails.java | 1,525 | //Scherm in het fragment, backPress brengt je terug naar Lampen fragment | line_comment | nl | package com.example.sanjiv.awarenessapp;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LampDetails extends AppCompatActivity implements View.OnClickListener {
private TextView naam, brightness, maxDecibel, huidigeDecibel;
private Button edit, notify, removeNotify;
private FirebaseDatabase database;
private FirebaseAuth auth;
private FirebaseUser user;
private DatabaseReference mDatabase;
private String key, lampNaam, userRole;
private boolean isNotifyOn;
private Lampen lamp;
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lamp_details);
naam = findViewById(R.id.naamLamp);
maxDecibel = findViewById(R.id.MaxDecibel);
huidigeDecibel = findViewById(R.id.HuidigeDecibel);
edit = findViewById(R.id.editLamp);
notify = findViewById(R.id.addNotify);
removeNotify = findViewById(R.id.removeNotify);
edit.setOnClickListener(this);
notify.setOnClickListener(this);
removeNotify.setOnClickListener(this);
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
user = auth.getCurrentUser();
mDatabase = database.getReference();
//Scherm in<SUF>
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .95), (int) (height * .9));
naam.setText(getIntent().getStringExtra("naam"));
maxDecibel.setText(getIntent().getStringExtra("maxDecibel"));
huidigeDecibel.setText(getIntent().getStringExtra("huidigeDecibel"));
isNotifyOn = Boolean.parseBoolean(getIntent().getStringExtra("notifyOn"));
Log.d("ADebugTag", "notifyOn = " + isNotifyOn);
edit.setVisibility(View.GONE);
notify.setVisibility(View.GONE);
removeNotify.setVisibility(View.GONE);
if (isNotifyOn) {
removeNotify.setVisibility(View.VISIBLE);
} else {
notify.setVisibility(View.VISIBLE);
}
userIsAdmin();
}
@Override
public void onClick(View v) {
if (v == edit) {
Intent intent = new Intent(this, EditLamp.class);
intent.putExtra("naam", getIntent().getStringExtra("naam"));
intent.putExtra("key", getIntent().getStringExtra("key"));
intent.putExtra("huidigeDecibel", getIntent().getStringExtra("huidigeDecibel"));
intent.putExtra("maxDecibel", getIntent().getStringExtra("maxDecibel"));
this.startActivity(intent);
}
if (v == notify) {
Intent intent = new Intent(this, AddNotifyLamp.class);
intent.putExtra("naam", getIntent().getStringExtra("naam"));
intent.putExtra("key", getIntent().getStringExtra("key"));
intent.putExtra("huidigeDecibel", getIntent().getStringExtra("huidigeDecibel"));
intent.putExtra("maxDecibel", getIntent().getStringExtra("maxDecibel"));
this.startActivity(intent);
}
if (v == removeNotify) {
Intent intent = new Intent(this, DeleteNotifyLamp.class);
intent.putExtra("key", getIntent().getStringExtra("key"));
this.startActivity(intent);
}
}
public void userIsAdmin() {
DatabaseReference ref_userRole = mDatabase.child("users").child(user.getUid()).child("rollen");
ref_userRole.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserModel userM = dataSnapshot.getValue(UserModel.class);
userRole = userM.getUserRole();
Log.d("ADebugTag", "Value from database: " + userRole);
updateButtons();
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.d("Lamps", "credentialsUserRoleGet:failure", databaseError.toException());
}
});
}
public void updateButtons() {
if (userRole != null) {
if (userRole.equalsIgnoreCase("admin")) {
Log.d("ADebugTag", "Value from updateButtons: " + userRole);
edit.setVisibility(View.VISIBLE);
}
}
}
}
| false | 994 | 18 | 1,228 | 20 | 1,229 | 16 | 1,228 | 20 | 1,440 | 19 | false | false | false | false | false | true |
3,611 | 23619_1 | package nl.duckson.zombiesiege.entity;
import java.awt.geom.AffineTransform;
public class Human extends Entity implements Directionable, Attackable {
protected static int width = 64, height = 64;
/**
* The direction in degrees the entity is facing
*/
protected int direction = 0;
public Human() {
this.hitpoints = startHitpoints();
}
public int hit(Attackable enemy) {
return 0;
}
protected int hitpoints = 0;
public int startHitpoints() {
return 10;
}
public int getHitpoints() {
return hitpoints;
}
public boolean isDead() {
return hitpoints >= 0;
}
public void watch(int x, int y) {
// Bereken de hoek om naar te kijken...
int delta_x = this.x - x;
int delta_y = this.y - y;
// @todo: This calculation is terrible, refactor it!
direction = (int) Math.toDegrees(
Math.atan2(delta_y, delta_x)
);
// @todo: Find out what this offset is about
direction -= (90 + 45);
}
public AffineTransform getAffineTransform() {
AffineTransform trans = new AffineTransform();
trans.translate(x, y);
trans.rotate(Math.toRadians(direction), width / 2, height / 2);
return trans;
}
public int getDirectionDegrees() {
return direction;
}
public double getDirectionRadians() {
return Math.toRadians(direction);
}
public String getIcon() {
return "human.png";
}
}
| mbernson/zombiesiege | src/nl/duckson/zombiesiege/entity/Human.java | 457 | // Bereken de hoek om naar te kijken... | line_comment | nl | package nl.duckson.zombiesiege.entity;
import java.awt.geom.AffineTransform;
public class Human extends Entity implements Directionable, Attackable {
protected static int width = 64, height = 64;
/**
* The direction in degrees the entity is facing
*/
protected int direction = 0;
public Human() {
this.hitpoints = startHitpoints();
}
public int hit(Attackable enemy) {
return 0;
}
protected int hitpoints = 0;
public int startHitpoints() {
return 10;
}
public int getHitpoints() {
return hitpoints;
}
public boolean isDead() {
return hitpoints >= 0;
}
public void watch(int x, int y) {
// Bereken de<SUF>
int delta_x = this.x - x;
int delta_y = this.y - y;
// @todo: This calculation is terrible, refactor it!
direction = (int) Math.toDegrees(
Math.atan2(delta_y, delta_x)
);
// @todo: Find out what this offset is about
direction -= (90 + 45);
}
public AffineTransform getAffineTransform() {
AffineTransform trans = new AffineTransform();
trans.translate(x, y);
trans.rotate(Math.toRadians(direction), width / 2, height / 2);
return trans;
}
public int getDirectionDegrees() {
return direction;
}
public double getDirectionRadians() {
return Math.toRadians(direction);
}
public String getIcon() {
return "human.png";
}
}
| false | 359 | 11 | 395 | 13 | 434 | 10 | 395 | 13 | 477 | 13 | false | false | false | false | false | true |
4,109 | 11184_1 | package ss.week7.cmdline;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Client class for a simple client-server application
* @author Theo Ruys
* @version 2005.02.21
*/
public class Client {
private static final String USAGE = "usage: java week4.cmdline.Client <name> <address> <port>";
/** Start een Client-applicatie op. */
public static void main(String[] args) {
if (args.length != 3) {
System.out.println(USAGE);
System.exit(0);
}
String name = args[0];
InetAddress addr = null;
int port = 0;
Socket sock = null;
// check args[1] - the IP-adress
try {
addr = InetAddress.getByName(args[1]);
} catch (UnknownHostException e) {
System.out.println(USAGE);
System.out.println("ERROR: host " + args[1] + " unknown");
System.exit(0);
}
// parse args[2] - the port
try {
port = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
System.out.println("ERROR: port " + args[2] + " is not an integer");
System.exit(0);
}
// try to open a Socket to the server
try {
sock = new Socket(addr, port);
} catch (IOException e) {
System.out.println("ERROR: could not create a socket on " + addr
+ " and port " + port);
}
// create Peer object and start the two-way communication
try {
Peer client = new Peer(name, sock);
Thread streamInputHandler = new Thread(client);
streamInputHandler.start();
client.handleTerminalInput();
System.out.println("komt ie heir?");
client.shutDown();
} catch (IOException e) {
e.printStackTrace();
}
}
} // end of class Client
| ramononis/project-rollit | weeky7/src/ss/week7/cmdline/Client.java | 568 | /** Start een Client-applicatie op. */ | block_comment | nl | package ss.week7.cmdline;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Client class for a simple client-server application
* @author Theo Ruys
* @version 2005.02.21
*/
public class Client {
private static final String USAGE = "usage: java week4.cmdline.Client <name> <address> <port>";
/** Start een Client-applicatie<SUF>*/
public static void main(String[] args) {
if (args.length != 3) {
System.out.println(USAGE);
System.exit(0);
}
String name = args[0];
InetAddress addr = null;
int port = 0;
Socket sock = null;
// check args[1] - the IP-adress
try {
addr = InetAddress.getByName(args[1]);
} catch (UnknownHostException e) {
System.out.println(USAGE);
System.out.println("ERROR: host " + args[1] + " unknown");
System.exit(0);
}
// parse args[2] - the port
try {
port = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
System.out.println("ERROR: port " + args[2] + " is not an integer");
System.exit(0);
}
// try to open a Socket to the server
try {
sock = new Socket(addr, port);
} catch (IOException e) {
System.out.println("ERROR: could not create a socket on " + addr
+ " and port " + port);
}
// create Peer object and start the two-way communication
try {
Peer client = new Peer(name, sock);
Thread streamInputHandler = new Thread(client);
streamInputHandler.start();
client.handleTerminalInput();
System.out.println("komt ie heir?");
client.shutDown();
} catch (IOException e) {
e.printStackTrace();
}
}
} // end of class Client
| false | 461 | 10 | 550 | 10 | 537 | 11 | 550 | 10 | 637 | 11 | false | false | false | false | false | true |
2,733 | 31689_7 | /*
* Copyright (C) 2013 FrankkieNL
*
* 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.frankkie.ontp;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import org.apache.http.NameValuePair;
/**
* CUSTOM LOGGER
*
* Deze class zo gemaakt,
* dat hij zoveel mogelijk lijkt op het bestaande Log-systeem,
* en dat hij op dezelfde manier kan worden aangeroepen.
* Als je alle logs via deze class laat lopen,
* kan je makkelijk logging in en uit schakelen.
* Ook exceptions kan je hiermee printen mbv de writer.
* Voor later is het ook handig, (aanpasbaarheid)
* als voortaan de logs naar een file moeten of zo,
* hoef je niet alle logs in de app aan te passen,
* maar alleen deze class.
*
* Voorbeeld:
* normaal:
* Log.v("tag", "bericht");
* voortaan:
* CLog.v("bericht");
* @author Frankkie
*/
public class CLog extends OutputStream {
private ByteArrayOutputStream bos = new ByteArrayOutputStream();
public static String TAG = "CLog";
/**
* Minimum errorlevel om te worden gelogd.
* Waardes komen van android.util.Log.*;
*/
public static int errorLevel = Log.VERBOSE;
public static boolean shouldLog = true;
/**
* door deze printwriter kan je meteen zo doen:
* exception.printStackTrace(CLog.writer);
*/
public static PrintWriter writer = new PrintWriter(new CLog());
public CLog(Context c) {
setShouldLogByDebuggable(c);
}
public CLog(Context c, String tag) {
setShouldLogByDebuggable(c);
setTag(tag);
}
public static boolean checkDebuggable(Context c) {
return (0 != (c.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
}
public static void setShouldLog(boolean bool){
shouldLog = bool;
}
public static void setShouldLogByDebuggable(Context c) {
shouldLog = checkDebuggable(c);
}
public CLog() {
// le nothin'
}
public CLog(String tag) {
setTag(tag);
}
@Override
public void write(int b) throws IOException {
if (b == (int) '\n') {
String s = new String(this.bos.toByteArray());
CLog.v(TAG, s);
this.bos = new ByteArrayOutputStream();
} else {
this.bos.write(b);
}
}
public static void setTag(String s) {
TAG = s;
}
public static String getTag() {
return TAG;
}
/**
* print exceptions
* @param e
*/
public static void ex(Exception e) {
if (shouldLog) {
e.printStackTrace();
}
}
/**
* print exceptions
* @param e
*/
public static void exOLD(Exception e) {
if (shouldLog) {
e.printStackTrace(writer);
}
}
public static void e(String tag, String msg) {
if (shouldLog && errorLevel <= Log.ERROR) {
Log.e(tag, msg);
}
}
public static void d(String tag, String msg) {
if (shouldLog && errorLevel <= Log.DEBUG) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (shouldLog && errorLevel <= Log.INFO) {
Log.i(tag, msg);
}
}
public static void v(String tag, String msg) {
if (shouldLog && errorLevel <= Log.VERBOSE) {
Log.v(tag, msg);
}
}
public static void w(String tag, String msg) {
if (shouldLog && errorLevel <= Log.WARN) {
Log.w(tag, msg);
}
}
public static void e(Object msg) {
e(TAG, msg.toString());
}
public static void d(Object msg) {
d(TAG, msg.toString());
}
public static void i(Object msg) {
i(TAG, msg.toString());
}
public static void v(Object msg) {
v(TAG, msg.toString());
}
public static void w(Object msg) {
w(TAG, msg.toString());
}
/**
* Print all parameter of List<NameValuePair>
* @param pairs the pairs to be printed
*/
public static void printNameValuePairs(List<NameValuePair> pairs) {
if (!shouldLog) {
return;
}
Iterator i = pairs.iterator();
while (i.hasNext()) {
NameValuePair p = (NameValuePair) i.next();
v(p.getName() + ":" + p.getValue());
}
}
/**
* Het sluiten van een dialog geeft veel te
* vaak een exception, waar we toch niets mee doen.
* @param d
*/
public static void dismissDialog(Dialog d) {
try {
d.dismiss();
} catch (Exception e) {
//./ignore
}
}
}
| frankkienl/NTP-Sync | src/nl/frankkie/ontp/CLog.java | 1,589 | /**
* Het sluiten van een dialog geeft veel te
* vaak een exception, waar we toch niets mee doen.
* @param d
*/ | block_comment | nl | /*
* Copyright (C) 2013 FrankkieNL
*
* 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.frankkie.ontp;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import org.apache.http.NameValuePair;
/**
* CUSTOM LOGGER
*
* Deze class zo gemaakt,
* dat hij zoveel mogelijk lijkt op het bestaande Log-systeem,
* en dat hij op dezelfde manier kan worden aangeroepen.
* Als je alle logs via deze class laat lopen,
* kan je makkelijk logging in en uit schakelen.
* Ook exceptions kan je hiermee printen mbv de writer.
* Voor later is het ook handig, (aanpasbaarheid)
* als voortaan de logs naar een file moeten of zo,
* hoef je niet alle logs in de app aan te passen,
* maar alleen deze class.
*
* Voorbeeld:
* normaal:
* Log.v("tag", "bericht");
* voortaan:
* CLog.v("bericht");
* @author Frankkie
*/
public class CLog extends OutputStream {
private ByteArrayOutputStream bos = new ByteArrayOutputStream();
public static String TAG = "CLog";
/**
* Minimum errorlevel om te worden gelogd.
* Waardes komen van android.util.Log.*;
*/
public static int errorLevel = Log.VERBOSE;
public static boolean shouldLog = true;
/**
* door deze printwriter kan je meteen zo doen:
* exception.printStackTrace(CLog.writer);
*/
public static PrintWriter writer = new PrintWriter(new CLog());
public CLog(Context c) {
setShouldLogByDebuggable(c);
}
public CLog(Context c, String tag) {
setShouldLogByDebuggable(c);
setTag(tag);
}
public static boolean checkDebuggable(Context c) {
return (0 != (c.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
}
public static void setShouldLog(boolean bool){
shouldLog = bool;
}
public static void setShouldLogByDebuggable(Context c) {
shouldLog = checkDebuggable(c);
}
public CLog() {
// le nothin'
}
public CLog(String tag) {
setTag(tag);
}
@Override
public void write(int b) throws IOException {
if (b == (int) '\n') {
String s = new String(this.bos.toByteArray());
CLog.v(TAG, s);
this.bos = new ByteArrayOutputStream();
} else {
this.bos.write(b);
}
}
public static void setTag(String s) {
TAG = s;
}
public static String getTag() {
return TAG;
}
/**
* print exceptions
* @param e
*/
public static void ex(Exception e) {
if (shouldLog) {
e.printStackTrace();
}
}
/**
* print exceptions
* @param e
*/
public static void exOLD(Exception e) {
if (shouldLog) {
e.printStackTrace(writer);
}
}
public static void e(String tag, String msg) {
if (shouldLog && errorLevel <= Log.ERROR) {
Log.e(tag, msg);
}
}
public static void d(String tag, String msg) {
if (shouldLog && errorLevel <= Log.DEBUG) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (shouldLog && errorLevel <= Log.INFO) {
Log.i(tag, msg);
}
}
public static void v(String tag, String msg) {
if (shouldLog && errorLevel <= Log.VERBOSE) {
Log.v(tag, msg);
}
}
public static void w(String tag, String msg) {
if (shouldLog && errorLevel <= Log.WARN) {
Log.w(tag, msg);
}
}
public static void e(Object msg) {
e(TAG, msg.toString());
}
public static void d(Object msg) {
d(TAG, msg.toString());
}
public static void i(Object msg) {
i(TAG, msg.toString());
}
public static void v(Object msg) {
v(TAG, msg.toString());
}
public static void w(Object msg) {
w(TAG, msg.toString());
}
/**
* Print all parameter of List<NameValuePair>
* @param pairs the pairs to be printed
*/
public static void printNameValuePairs(List<NameValuePair> pairs) {
if (!shouldLog) {
return;
}
Iterator i = pairs.iterator();
while (i.hasNext()) {
NameValuePair p = (NameValuePair) i.next();
v(p.getName() + ":" + p.getValue());
}
}
/**
* Het sluiten van<SUF>*/
public static void dismissDialog(Dialog d) {
try {
d.dismiss();
} catch (Exception e) {
//./ignore
}
}
}
| false | 1,263 | 37 | 1,430 | 41 | 1,511 | 36 | 1,430 | 41 | 1,641 | 43 | false | false | false | false | false | true |
4,245 | 28800_0 | package domain;
import persistence.Marshalling;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
public class Ring {
private String naam;
private String letter;
private int index;
@XmlElementWrapper(name = "Tijdslots")
@XmlElement(name = "Tijdslot")
private final List<Tijdslot> tijdslots;
@XmlIDREF
@XmlElementWrapper(name = "Disciplines")
@XmlElement(name = "Discipline")
private final HashSet<Discipline> disciplines;
public Ring(String ringNaam, String ringLetter, int ringIndex) {
naam = ringNaam;
letter = ringLetter;
index = ringIndex;
tijdslots = new ArrayList<>();
disciplines = new HashSet<>();
}
public Ring(){
this("Ring zonder naam " + Math.random(), "", 0);
}
public String getNaam() { return naam; }
public void setNaam(String naam) { this.naam = naam; }
public String getLetter() { return letter; }
public void setLetter(String letter) { this.letter = letter; }
@XmlID
@XmlAttribute(name = "id")
public String getRef() { return "R"+ index; }
public void setRef(String s) { this.index = Integer.parseInt(s.substring(1)); }
public int getRingIndex() { return index; }
public void setRingIndex(int ringIndex) { index = ringIndex; }
@XmlTransient
public List<Tijdslot> getTijdslots() {
return tijdslots;
}
@XmlTransient
public HashSet<Discipline> getDisciplines() { return disciplines;}
public void addDiscipline(Discipline discipline) {
disciplines.add(discipline);
//tijdslots voor ring maken als ze nog niet bestaan
if(tijdslots.size() == 0) {
for (int i = 0; i < Marshalling.TOTALETIJD; i = i + discipline.getDuur()) { //TODO: property van maken
Tijdslot tijdslot = new Tijdslot(i, discipline.getDuur(), this);
tijdslots.add(tijdslot);
}
}
}
public String getVerkorteNotatie() {
return naam
.replace("meisjes","")
.replace("jongens","")
.replace("gemengd","");
}
@Override
public String toString() { return naam + (letter != "" ? " " + letter : ""); }
@Override
public int hashCode() { return Objects.hash(getRingIndex()); }
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof Ring) {
Ring other = (Ring) o;
return getRingIndex() == other.getRingIndex();
} else {
return false;
}
}
}
| samverstraete/klj-sf-planner | src/main/java/domain/Ring.java | 822 | //tijdslots voor ring maken als ze nog niet bestaan | line_comment | nl | package domain;
import persistence.Marshalling;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
public class Ring {
private String naam;
private String letter;
private int index;
@XmlElementWrapper(name = "Tijdslots")
@XmlElement(name = "Tijdslot")
private final List<Tijdslot> tijdslots;
@XmlIDREF
@XmlElementWrapper(name = "Disciplines")
@XmlElement(name = "Discipline")
private final HashSet<Discipline> disciplines;
public Ring(String ringNaam, String ringLetter, int ringIndex) {
naam = ringNaam;
letter = ringLetter;
index = ringIndex;
tijdslots = new ArrayList<>();
disciplines = new HashSet<>();
}
public Ring(){
this("Ring zonder naam " + Math.random(), "", 0);
}
public String getNaam() { return naam; }
public void setNaam(String naam) { this.naam = naam; }
public String getLetter() { return letter; }
public void setLetter(String letter) { this.letter = letter; }
@XmlID
@XmlAttribute(name = "id")
public String getRef() { return "R"+ index; }
public void setRef(String s) { this.index = Integer.parseInt(s.substring(1)); }
public int getRingIndex() { return index; }
public void setRingIndex(int ringIndex) { index = ringIndex; }
@XmlTransient
public List<Tijdslot> getTijdslots() {
return tijdslots;
}
@XmlTransient
public HashSet<Discipline> getDisciplines() { return disciplines;}
public void addDiscipline(Discipline discipline) {
disciplines.add(discipline);
//tijdslots voor<SUF>
if(tijdslots.size() == 0) {
for (int i = 0; i < Marshalling.TOTALETIJD; i = i + discipline.getDuur()) { //TODO: property van maken
Tijdslot tijdslot = new Tijdslot(i, discipline.getDuur(), this);
tijdslots.add(tijdslot);
}
}
}
public String getVerkorteNotatie() {
return naam
.replace("meisjes","")
.replace("jongens","")
.replace("gemengd","");
}
@Override
public String toString() { return naam + (letter != "" ? " " + letter : ""); }
@Override
public int hashCode() { return Objects.hash(getRingIndex()); }
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof Ring) {
Ring other = (Ring) o;
return getRingIndex() == other.getRingIndex();
} else {
return false;
}
}
}
| false | 632 | 13 | 797 | 15 | 734 | 11 | 797 | 15 | 876 | 15 | false | false | false | false | false | true |
12 | 28346_9 | package org.firstinspires.ftc.teamcode.autonomousroutes;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.teamcode.autonomousclasses.BezierCurveRoute;
import org.firstinspires.ftc.teamcode.robots.CompetitionRobot;
/** Comment to make the program disappear from the driverstation app. */
@Autonomous
public class RedStart1VisionPushParkB extends LinearOpMode {
private final boolean BLUE_SIDE = false;
private final boolean SKIP_VISION = false;
private BezierCurveRoute case0;
private BezierCurveRoute case2;
private BezierCurveRoute case0ParkB;
private BezierCurveRoute case1ParkB;
private BezierCurveRoute case2ParkB;
private CompetitionRobot robot;
private void initAutonomous() {
robot = new CompetitionRobot(this);
case0 = new BezierCurveRoute(
new double[] {-134.835833333334, 221.373750000001, -150.769166666667, 36.0989583333336}, //The x-coefficients
new double[] {-5.57666666666569, 65.7249999999985, 155.350000000001, -151.1675}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2 = new BezierCurveRoute(
new double[] {6.37333333333339, -11.9500000000003, -27.0866666666663, 52.9783333333332}, //The x-coefficients
new double[] {195.98, -169.69, 7.96666666666653, 29.4766666666668}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case0ParkB= new BezierCurveRoute(
new double[] {-12.1989583333324, -1351.993125, 7146.846875, -15288.7802083333, 15483.615, -7288.35479166666, 1574.16354166666}, //The x-coefficients
new double[] {-408.490833333334, 2329.6525, -6601.37916666666, 14366.8875, -18804.52, 12077.6658333333, -2888.51416666666}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case1ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
}
@Override
public void runOpMode() {
int markerPosition = 1;
initAutonomous();
robot.grabber.grab();
sleep(1000);
// TODO: Hier 1 functie van maken.
while (!isStarted() && !isStopRequested()) {
markerPosition = robot.webcam.getMarkerPosition(BLUE_SIDE);
// result
telemetry.addData("Position", markerPosition);
telemetry.update();
}
// Jeroen denkt dat dit niet nodig is.
waitForStart();
// Choose default option if skip.
if (SKIP_VISION) {
markerPosition = 1;
}
switch (markerPosition) {
case 0: // LEFT
leftPixelPlacement();
return;
case 2: // RIGHT
rightPixelPlacement();
return;
default: // Default MIDDLE
middlePixelPlacement();
return;
}
}
private void middlePixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel naar de middelste streep.
robot.drivetrain.driveStraight(65, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.tiltMechanism.TiltMechanismDown();
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-25, 0.4);
//Rij naar de backstage en parkeer.
case1ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void rightPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.drivetrain.driveStraight(45, 0.4);
robot.drivetrain.turnRobotAO(45);
robot.drivetrain.driveStraight(20, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.drivetrain.driveStraight(-20, 0.4);
robot.drivetrain.turnRobotAO(0);
robot.drivetrain.driveStraight(10, 0.4);
//Rij naar de backstage en parkeer.
case2ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void leftPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel naar de linker streep.
case0.executeWithPointSkip();
sleep(200);
robot.pusher.release();
sleep(200);
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-10, 0.4);
robot.tiltMechanism.TiltMechanismDown();
//Rij naar de backstage en parkeer.
case0ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
} | 16788-TheEncryptedGentlemen/FtcRobotController | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomousroutes/RedStart1VisionPushParkB.java | 2,111 | //Push pixel naar de middelste streep. | line_comment | nl | package org.firstinspires.ftc.teamcode.autonomousroutes;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.teamcode.autonomousclasses.BezierCurveRoute;
import org.firstinspires.ftc.teamcode.robots.CompetitionRobot;
/** Comment to make the program disappear from the driverstation app. */
@Autonomous
public class RedStart1VisionPushParkB extends LinearOpMode {
private final boolean BLUE_SIDE = false;
private final boolean SKIP_VISION = false;
private BezierCurveRoute case0;
private BezierCurveRoute case2;
private BezierCurveRoute case0ParkB;
private BezierCurveRoute case1ParkB;
private BezierCurveRoute case2ParkB;
private CompetitionRobot robot;
private void initAutonomous() {
robot = new CompetitionRobot(this);
case0 = new BezierCurveRoute(
new double[] {-134.835833333334, 221.373750000001, -150.769166666667, 36.0989583333336}, //The x-coefficients
new double[] {-5.57666666666569, 65.7249999999985, 155.350000000001, -151.1675}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2 = new BezierCurveRoute(
new double[] {6.37333333333339, -11.9500000000003, -27.0866666666663, 52.9783333333332}, //The x-coefficients
new double[] {195.98, -169.69, 7.96666666666653, 29.4766666666668}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case0ParkB= new BezierCurveRoute(
new double[] {-12.1989583333324, -1351.993125, 7146.846875, -15288.7802083333, 15483.615, -7288.35479166666, 1574.16354166666}, //The x-coefficients
new double[] {-408.490833333334, 2329.6525, -6601.37916666666, 14366.8875, -18804.52, 12077.6658333333, -2888.51416666666}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case1ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
}
@Override
public void runOpMode() {
int markerPosition = 1;
initAutonomous();
robot.grabber.grab();
sleep(1000);
// TODO: Hier 1 functie van maken.
while (!isStarted() && !isStopRequested()) {
markerPosition = robot.webcam.getMarkerPosition(BLUE_SIDE);
// result
telemetry.addData("Position", markerPosition);
telemetry.update();
}
// Jeroen denkt dat dit niet nodig is.
waitForStart();
// Choose default option if skip.
if (SKIP_VISION) {
markerPosition = 1;
}
switch (markerPosition) {
case 0: // LEFT
leftPixelPlacement();
return;
case 2: // RIGHT
rightPixelPlacement();
return;
default: // Default MIDDLE
middlePixelPlacement();
return;
}
}
private void middlePixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel<SUF>
robot.drivetrain.driveStraight(65, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.tiltMechanism.TiltMechanismDown();
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-25, 0.4);
//Rij naar de backstage en parkeer.
case1ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void rightPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.drivetrain.driveStraight(45, 0.4);
robot.drivetrain.turnRobotAO(45);
robot.drivetrain.driveStraight(20, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.drivetrain.driveStraight(-20, 0.4);
robot.drivetrain.turnRobotAO(0);
robot.drivetrain.driveStraight(10, 0.4);
//Rij naar de backstage en parkeer.
case2ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void leftPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel naar de linker streep.
case0.executeWithPointSkip();
sleep(200);
robot.pusher.release();
sleep(200);
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-10, 0.4);
robot.tiltMechanism.TiltMechanismDown();
//Rij naar de backstage en parkeer.
case0ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
} | false | 2,193 | 11 | 2,259 | 12 | 2,296 | 10 | 2,259 | 12 | 2,576 | 13 | false | false | false | false | false | true |
2,565 | 166310_0 | package com.fokkenrood.antlr;_x000D_
_x000D_
import java.util.Calendar;_x000D_
_x000D_
import com.fokkenrood.antlr.ProfielSpraakParser.ObjectContext;_x000D_
import com.fokkenrood.antlr.ProfielSpraakParser.RegelContext;_x000D_
_x000D_
_x000D_
public class AangifteDroolsListener extends ProfielSpraakBaseListener {_x000D_
private Calendar TODAY = Calendar.getInstance();_x000D_
private String regel = "Regel";_x000D_
private String regelset = "Regelset";_x000D_
private StringBuilder drlWhen = new StringBuilder();_x000D_
private StringBuilder drlThen = new StringBuilder();_x000D_
_x000D_
// CONSTRUCTOR:_x000D_
public AangifteDroolsListener() {_x000D_
TODAY.set(2017, 1, 16); // Datum voor digitaal Tijdreizen: YYYY, (MM=0-11), (DD=1-31)_x000D_
} // end constructor_x000D_
_x000D_
// GET-er:_x000D_
public String getDRL() {_x000D_
return (drlWhen.toString() + drlThen.toString());_x000D_
}_x000D_
_x000D_
_x000D_
@Override_x000D_
public void enterRegel(RegelContext ctx) {_x000D_
drlWhen.setLength(0);_x000D_
drlWhen.append("package ");_x000D_
drlWhen.append(regelset);_x000D_
drlWhen.append("\n\n");_x000D_
drlWhen.append("import com.fokkenrood.drools.Aangifte;\n\n");_x000D_
drlWhen.append("rule \"");_x000D_
drlWhen.append(regel);_x000D_
drlWhen.append("\"\n");_x000D_
drlWhen.append(" when\n");_x000D_
drlThen.setLength(0);_x000D_
drlThen.append("\n )\n");_x000D_
drlThen.append(" then\n");_x000D_
} // end enterRegel_x000D_
_x000D_
_x000D_
@Override_x000D_
public void exitRegel(RegelContext ctx) {_x000D_
drlThen.append(" $aangifte.setScore(\"");_x000D_
drlThen.append(ctx.w.getText());_x000D_
drlThen.append("\");\n");_x000D_
drlThen.append("end\n");_x000D_
} // end exitRegel_x000D_
_x000D_
_x000D_
@Override_x000D_
public void exitObject(ObjectContext ctx) {_x000D_
drlWhen.append(drlWhen.indexOf("$aangifte") < 1 ? " $aangifte : Aangifte(\n" : ",\n");_x000D_
if (ctx.w1 != null) {_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.f.signifier);_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.v.operator);_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.w1.value);_x000D_
} // end if_x000D_
if (ctx.w2 != null) {_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.f.signifier);_x000D_
drlWhen.append((ctx.not != null ? " not" : ""));_x000D_
drlWhen.append(" matches \".*(");_x000D_
drlWhen.append(ctx.w2.getText());_x000D_
drlWhen.append(").*\"");_x000D_
} // end if_x000D_
} // end exitObject_x000D_
_x000D_
_x000D_
} // end class_x000D_
| discipl/act-native | backend/src/main/java/com/fokkenrood/antlr/AangifteDroolsListener.java | 873 | // Datum voor digitaal Tijdreizen: YYYY, (MM=0-11), (DD=1-31)_x000D_ | line_comment | nl | package com.fokkenrood.antlr;_x000D_
_x000D_
import java.util.Calendar;_x000D_
_x000D_
import com.fokkenrood.antlr.ProfielSpraakParser.ObjectContext;_x000D_
import com.fokkenrood.antlr.ProfielSpraakParser.RegelContext;_x000D_
_x000D_
_x000D_
public class AangifteDroolsListener extends ProfielSpraakBaseListener {_x000D_
private Calendar TODAY = Calendar.getInstance();_x000D_
private String regel = "Regel";_x000D_
private String regelset = "Regelset";_x000D_
private StringBuilder drlWhen = new StringBuilder();_x000D_
private StringBuilder drlThen = new StringBuilder();_x000D_
_x000D_
// CONSTRUCTOR:_x000D_
public AangifteDroolsListener() {_x000D_
TODAY.set(2017, 1, 16); // Datum voor<SUF>
} // end constructor_x000D_
_x000D_
// GET-er:_x000D_
public String getDRL() {_x000D_
return (drlWhen.toString() + drlThen.toString());_x000D_
}_x000D_
_x000D_
_x000D_
@Override_x000D_
public void enterRegel(RegelContext ctx) {_x000D_
drlWhen.setLength(0);_x000D_
drlWhen.append("package ");_x000D_
drlWhen.append(regelset);_x000D_
drlWhen.append("\n\n");_x000D_
drlWhen.append("import com.fokkenrood.drools.Aangifte;\n\n");_x000D_
drlWhen.append("rule \"");_x000D_
drlWhen.append(regel);_x000D_
drlWhen.append("\"\n");_x000D_
drlWhen.append(" when\n");_x000D_
drlThen.setLength(0);_x000D_
drlThen.append("\n )\n");_x000D_
drlThen.append(" then\n");_x000D_
} // end enterRegel_x000D_
_x000D_
_x000D_
@Override_x000D_
public void exitRegel(RegelContext ctx) {_x000D_
drlThen.append(" $aangifte.setScore(\"");_x000D_
drlThen.append(ctx.w.getText());_x000D_
drlThen.append("\");\n");_x000D_
drlThen.append("end\n");_x000D_
} // end exitRegel_x000D_
_x000D_
_x000D_
@Override_x000D_
public void exitObject(ObjectContext ctx) {_x000D_
drlWhen.append(drlWhen.indexOf("$aangifte") < 1 ? " $aangifte : Aangifte(\n" : ",\n");_x000D_
if (ctx.w1 != null) {_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.f.signifier);_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.v.operator);_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.w1.value);_x000D_
} // end if_x000D_
if (ctx.w2 != null) {_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.f.signifier);_x000D_
drlWhen.append((ctx.not != null ? " not" : ""));_x000D_
drlWhen.append(" matches \".*(");_x000D_
drlWhen.append(ctx.w2.getText());_x000D_
drlWhen.append(").*\"");_x000D_
} // end if_x000D_
} // end exitObject_x000D_
_x000D_
_x000D_
} // end class_x000D_
| false | 1,151 | 35 | 1,337 | 36 | 1,290 | 33 | 1,337 | 36 | 1,421 | 38 | false | false | false | false | false | true |
2,960 | 112978_0 | package nl.novi.javaprogrammeren;
import nl.novi.javaprogrammeren.overerving.Rocket;
public class Main {
/*
Bekijk onderstaande code. Er zijn twee klasse, twee objecten.
ApolloRocket extends Rocket.
De ApolloRocket is speciaal. Wanneer deze geïnstantieerd wordt, moeten we ook het aantal motoren meegeven. Pas de
constructor aan.
Maak vervolgens in deze klasse een ApolloRocket object aan en roep de toString()-methode aan.
*/
public static void main(String[] args) {
Rocket genericRocket = new Rocket(100);
genericRocket.fly(10);
System.out.println(genericRocket.toString());
}
}
| hogeschoolnovi/SD-BE-JP-Overerving-01b | src/nl/novi/javaprogrammeren/Main.java | 206 | /*
Bekijk onderstaande code. Er zijn twee klasse, twee objecten.
ApolloRocket extends Rocket.
De ApolloRocket is speciaal. Wanneer deze geïnstantieerd wordt, moeten we ook het aantal motoren meegeven. Pas de
constructor aan.
Maak vervolgens in deze klasse een ApolloRocket object aan en roep de toString()-methode aan.
*/ | block_comment | nl | package nl.novi.javaprogrammeren;
import nl.novi.javaprogrammeren.overerving.Rocket;
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());
}
}
| false | 162 | 90 | 185 | 97 | 169 | 82 | 185 | 97 | 217 | 110 | false | false | false | false | false | true |
206 | 22196_13 | package nl.noscope.emeraldextraction.objects;_x000D_
_x000D_
import android.util.Log;_x000D_
import nl.saxion.act.playground.model.GameBoard;_x000D_
import nl.saxion.act.playground.model.GameObject;_x000D_
_x000D_
/**_x000D_
* De miner is ons speler object, deze verplaatst zich dan ook steeds_x000D_
* _x000D_
* @author Boyd_x000D_
*/_x000D_
public class Miner extends GameObject {_x000D_
public static final String MINER_IMAGE = "miner";_x000D_
public static final String MINER_UP = "up";_x000D_
public static final String MINER_DOWN = "down";_x000D_
public static final String MINER_LEFT = "links";_x000D_
public static final String MINER_RIGHT = "rechts";_x000D_
_x000D_
int position = 0;_x000D_
_x000D_
_x000D_
/** Returns the ImageId of the image to show. */_x000D_
@Override_x000D_
public String getImageId() {_x000D_
if (position == 1) {_x000D_
return MINER_LEFT; _x000D_
} else if (position == 2) {_x000D_
return MINER_RIGHT; _x000D_
} else if (position == 3) {_x000D_
return MINER_UP; _x000D_
} else if (position == 4) {_x000D_
return MINER_DOWN; _x000D_
} else {_x000D_
return MINER_IMAGE;_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
public void walkLeft(GameBoard gameBoard) {_x000D_
_x000D_
position = 1;_x000D_
_x000D_
int newPosX = getPositionX() - 1;_x000D_
int newPosY = getPositionY();_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
_x000D_
}_x000D_
_x000D_
public void walkRight(GameBoard gameBoard) {_x000D_
_x000D_
position = 2;_x000D_
_x000D_
int newPosX = getPositionX() + 1;_x000D_
int newPosY = getPositionY();_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
}_x000D_
_x000D_
public void walkUp(GameBoard gameBoard) {_x000D_
_x000D_
position = 3;_x000D_
_x000D_
int newPosX = getPositionX();_x000D_
int newPosY = getPositionY() - 1;_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
}_x000D_
_x000D_
public void walkDown(GameBoard gameBoard) {_x000D_
_x000D_
position = 4;_x000D_
_x000D_
int newPosX = getPositionX();_x000D_
int newPosY = getPositionY() + 1;_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
_x000D_
}_x000D_
_x000D_
private void StateCheck(int newPosX, int newPosY, GameBoard gameBoard, int direction) {_x000D_
// Als de nieuwe positie naast het bord is doet hij niks_x000D_
if (newPosX >= gameBoard.getWidth() - 1 || newPosX == 0) {_x000D_
return;_x000D_
} else if (newPosY >= gameBoard.getHeight() - 1 || newPosY == 0){_x000D_
return;_x000D_
}_x000D_
_x000D_
// Kijk of er een object is op het nieuwe punt_x000D_
GameObject objectAtNewPos = gameBoard.getObject(newPosX, newPosY);_x000D_
if (objectAtNewPos != null) {_x000D_
_x000D_
// Miner kan niet door een aantal objecten heen_x000D_
if (objectAtNewPos instanceof Stone) {_x000D_
return;_x000D_
}_x000D_
if (objectAtNewPos instanceof Iron) {_x000D_
return;_x000D_
}_x000D_
if (objectAtNewPos instanceof Minecart) {_x000D_
return;_x000D_
}_x000D_
_x000D_
if (objectAtNewPos instanceof Emerald) {_x000D_
// Je kan een emerald niet naar beneden drukken_x000D_
if (direction == 4) { return; }_x000D_
// Duw de emerald omhoog als er vrije ruimte boven is_x000D_
if (direction == 3) {_x000D_
if (gameBoard.getObject(newPosX, newPosY - 1) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar links als er vrije ruimte links van de emerald is_x000D_
if (direction == 1) {_x000D_
if (gameBoard.getObject(newPosX - 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is_x000D_
if (direction == 2) {_x000D_
if (gameBoard.getObject(newPosX + 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY);_x000D_
}_x000D_
else { return ; }_x000D_
}_x000D_
}_x000D_
if (objectAtNewPos instanceof StoneMove) {_x000D_
// Je kan een emerald niet naar beneden drukken_x000D_
if (direction == 4) { return; }_x000D_
// Duw de emerald omhoog als er vrije ruimte boven is_x000D_
if (direction == 3) {_x000D_
if (gameBoard.getObject(newPosX, newPosY - 1) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar links als er vrije ruimte links van de emerald is_x000D_
if (direction == 1) {_x000D_
if (gameBoard.getObject(newPosX - 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is_x000D_
if (direction == 2) {_x000D_
if (gameBoard.getObject(newPosX + 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY);_x000D_
}_x000D_
else { return ; }_x000D_
}_x000D_
}_x000D_
_x000D_
if (objectAtNewPos instanceof Sand) {_x000D_
gameBoard.removeObject(objectAtNewPos);_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
// Verplaats de miner naar zijn nieuwe positie_x000D_
//Log.d("Miner", "Ik verplaats nu de miner");_x000D_
gameBoard.moveObject(this, newPosX, newPosY);_x000D_
//gameBoard.updateView();_x000D_
Log.d("Miner", "Miner verplaatst");_x000D_
_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void onTouched(GameBoard gameBoard) {_x000D_
// TODO Auto-generated method stub_x000D_
_x000D_
}_x000D_
}_x000D_
| Bernardez/Speelveld | src/nl/noscope/emeraldextraction/objects/Miner.java | 1,801 | // Verplaats de miner naar zijn nieuwe positie_x000D_ | line_comment | nl | package nl.noscope.emeraldextraction.objects;_x000D_
_x000D_
import android.util.Log;_x000D_
import nl.saxion.act.playground.model.GameBoard;_x000D_
import nl.saxion.act.playground.model.GameObject;_x000D_
_x000D_
/**_x000D_
* De miner is ons speler object, deze verplaatst zich dan ook steeds_x000D_
* _x000D_
* @author Boyd_x000D_
*/_x000D_
public class Miner extends GameObject {_x000D_
public static final String MINER_IMAGE = "miner";_x000D_
public static final String MINER_UP = "up";_x000D_
public static final String MINER_DOWN = "down";_x000D_
public static final String MINER_LEFT = "links";_x000D_
public static final String MINER_RIGHT = "rechts";_x000D_
_x000D_
int position = 0;_x000D_
_x000D_
_x000D_
/** Returns the ImageId of the image to show. */_x000D_
@Override_x000D_
public String getImageId() {_x000D_
if (position == 1) {_x000D_
return MINER_LEFT; _x000D_
} else if (position == 2) {_x000D_
return MINER_RIGHT; _x000D_
} else if (position == 3) {_x000D_
return MINER_UP; _x000D_
} else if (position == 4) {_x000D_
return MINER_DOWN; _x000D_
} else {_x000D_
return MINER_IMAGE;_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
public void walkLeft(GameBoard gameBoard) {_x000D_
_x000D_
position = 1;_x000D_
_x000D_
int newPosX = getPositionX() - 1;_x000D_
int newPosY = getPositionY();_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
_x000D_
}_x000D_
_x000D_
public void walkRight(GameBoard gameBoard) {_x000D_
_x000D_
position = 2;_x000D_
_x000D_
int newPosX = getPositionX() + 1;_x000D_
int newPosY = getPositionY();_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
}_x000D_
_x000D_
public void walkUp(GameBoard gameBoard) {_x000D_
_x000D_
position = 3;_x000D_
_x000D_
int newPosX = getPositionX();_x000D_
int newPosY = getPositionY() - 1;_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
}_x000D_
_x000D_
public void walkDown(GameBoard gameBoard) {_x000D_
_x000D_
position = 4;_x000D_
_x000D_
int newPosX = getPositionX();_x000D_
int newPosY = getPositionY() + 1;_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
_x000D_
}_x000D_
_x000D_
private void StateCheck(int newPosX, int newPosY, GameBoard gameBoard, int direction) {_x000D_
// Als de nieuwe positie naast het bord is doet hij niks_x000D_
if (newPosX >= gameBoard.getWidth() - 1 || newPosX == 0) {_x000D_
return;_x000D_
} else if (newPosY >= gameBoard.getHeight() - 1 || newPosY == 0){_x000D_
return;_x000D_
}_x000D_
_x000D_
// Kijk of er een object is op het nieuwe punt_x000D_
GameObject objectAtNewPos = gameBoard.getObject(newPosX, newPosY);_x000D_
if (objectAtNewPos != null) {_x000D_
_x000D_
// Miner kan niet door een aantal objecten heen_x000D_
if (objectAtNewPos instanceof Stone) {_x000D_
return;_x000D_
}_x000D_
if (objectAtNewPos instanceof Iron) {_x000D_
return;_x000D_
}_x000D_
if (objectAtNewPos instanceof Minecart) {_x000D_
return;_x000D_
}_x000D_
_x000D_
if (objectAtNewPos instanceof Emerald) {_x000D_
// Je kan een emerald niet naar beneden drukken_x000D_
if (direction == 4) { return; }_x000D_
// Duw de emerald omhoog als er vrije ruimte boven is_x000D_
if (direction == 3) {_x000D_
if (gameBoard.getObject(newPosX, newPosY - 1) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar links als er vrije ruimte links van de emerald is_x000D_
if (direction == 1) {_x000D_
if (gameBoard.getObject(newPosX - 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is_x000D_
if (direction == 2) {_x000D_
if (gameBoard.getObject(newPosX + 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY);_x000D_
}_x000D_
else { return ; }_x000D_
}_x000D_
}_x000D_
if (objectAtNewPos instanceof StoneMove) {_x000D_
// Je kan een emerald niet naar beneden drukken_x000D_
if (direction == 4) { return; }_x000D_
// Duw de emerald omhoog als er vrije ruimte boven is_x000D_
if (direction == 3) {_x000D_
if (gameBoard.getObject(newPosX, newPosY - 1) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar links als er vrije ruimte links van de emerald is_x000D_
if (direction == 1) {_x000D_
if (gameBoard.getObject(newPosX - 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is_x000D_
if (direction == 2) {_x000D_
if (gameBoard.getObject(newPosX + 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY);_x000D_
}_x000D_
else { return ; }_x000D_
}_x000D_
}_x000D_
_x000D_
if (objectAtNewPos instanceof Sand) {_x000D_
gameBoard.removeObject(objectAtNewPos);_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
// Verplaats de<SUF>
//Log.d("Miner", "Ik verplaats nu de miner");_x000D_
gameBoard.moveObject(this, newPosX, newPosY);_x000D_
//gameBoard.updateView();_x000D_
Log.d("Miner", "Miner verplaatst");_x000D_
_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void onTouched(GameBoard gameBoard) {_x000D_
// TODO Auto-generated method stub_x000D_
_x000D_
}_x000D_
}_x000D_
| false | 2,472 | 17 | 2,817 | 21 | 2,674 | 17 | 2,817 | 21 | 3,136 | 19 | false | false | false | false | false | true |
1,401 | 72767_14 |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class MyWorld extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public MyWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
int[][] map = {
{17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,},
{16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,16,17,16,17,17,17,16,17,17,17,17,17,17,17,17,16,16,16,17,},
{17,16,17,16,16,16,16,16,16,16,17,16,17,16,16,16,17,16,17,16,16,16,16,16,16,17,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,16,17,16,17,16,17,17,17,16,17,17,17,17,17,16,16,17,16,17,16,17,},
{17,16,17,16,17,16,16,16,16,16,17,16,17,16,16,16,16,16,16,16,16,16,17,16,16,17,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,16,17,17,17,17,17,17,17,17,16,16,17,16,17,17,16,17,16,17,},
{17,16,17,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,17,16,17,16,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,17,17,16,16,16,17,16,16,17,16,16,17,16,17,16,17,17,16,17,},
{17,16,17,16,16,16,16,16,16,17,17,16,17,17,16,16,17,16,16,17,16,16,17,16,17,17,16,16,16,17,},
{17,16,17,17,17,17,17,17,16,16,16,16,16,16,16,16,17,16,16,17,16,16,17,16,16,16,16,17,16,17,},
{17,16,16,16,16,16,16,16,16,17,17,17,17,17,16,16,17,16,16,16,16,16,17,16,16,17,17,17,16,17,},
{17,16,17,17,17,17,17,16,16,17,17,16,16,17,16,17,17,17,17,17,16,16,17,17,16,16,17,17,16,17,},
{17,16,17,16,16,16,17,16,16,16,16,16,16,17,16,17,16,16,16,16,16,16,16,17,16,16,17,16,16,17,},
{17,16,17,16,16,16,17,16,16,17,17,17,17,17,16,17,16,17,17,17,17,17,16,17,16,16,17,17,17,17,},
{17,16,17,16,16,16,17,16,17,17,16,16,16,16,16,17,16,17,16,16,16,17,16,17,16,16,16,16,16,17,},
{17,16,17,16,16,16,17,16,17,16,17,17,16,17,16,17,16,16,17,16,16,17,16,16,17,17,17,16,16,17,},
{17,16,16,16,16,16,17,16,17,16,17,16,16,17,16,17,16,17,16,17,16,17,16,17,17,16,17,16,16,17,},
{17,16,17,17,17,17,17,16,17,16,17,16,16,17,16,17,17,16,16,17,16,17,16,16,16,16,17,16,16,17,},
{17,16,16,17,17,17,17,16,17,16,17,16,16,17,16,16,16,16,17,17,16,17,17,17,17,17,17,16,16,17,},
{17,17,16,16,16,16,17,17,17,16,16,16,16,17,17,17,17,16,17,16,16,17,16,16,16,16,17,16,16,17,},
{17,17,17,16,16,16,16,16,16,16,16,16,16,17,16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,16,},
{17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 70, 70, 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();
Star star = new Star();
// 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, 30, 105);
addObject(new Letters('J'),385,385);
addObject(new Letters('U'),665,1155);
addObject(new Letters('M'),1085,245);
addObject(new Letters('P'),1925,945);
addObject(star, 245, 660);
//addObject(new Enemy(), 1170, 410);
// 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);
}
@Override
public void act() {
ce.update();
}
}
| ROCMondriaanTIN/project-greenfoot-game-Toni2000 | MyWorld.java | 2,095 | // Toevoegen van de mover instantie of een extentie hiervan | line_comment | nl |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class MyWorld extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public MyWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
int[][] map = {
{17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,},
{16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,16,17,16,17,17,17,16,17,17,17,17,17,17,17,17,16,16,16,17,},
{17,16,17,16,16,16,16,16,16,16,17,16,17,16,16,16,17,16,17,16,16,16,16,16,16,17,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,16,17,16,17,16,17,17,17,16,17,17,17,17,17,16,16,17,16,17,16,17,},
{17,16,17,16,17,16,16,16,16,16,17,16,17,16,16,16,16,16,16,16,16,16,17,16,16,17,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,16,17,17,17,17,17,17,17,17,16,16,17,16,17,17,16,17,16,17,},
{17,16,17,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,17,16,17,16,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,17,17,16,16,16,17,16,16,17,16,16,17,16,17,16,17,17,16,17,},
{17,16,17,16,16,16,16,16,16,17,17,16,17,17,16,16,17,16,16,17,16,16,17,16,17,17,16,16,16,17,},
{17,16,17,17,17,17,17,17,16,16,16,16,16,16,16,16,17,16,16,17,16,16,17,16,16,16,16,17,16,17,},
{17,16,16,16,16,16,16,16,16,17,17,17,17,17,16,16,17,16,16,16,16,16,17,16,16,17,17,17,16,17,},
{17,16,17,17,17,17,17,16,16,17,17,16,16,17,16,17,17,17,17,17,16,16,17,17,16,16,17,17,16,17,},
{17,16,17,16,16,16,17,16,16,16,16,16,16,17,16,17,16,16,16,16,16,16,16,17,16,16,17,16,16,17,},
{17,16,17,16,16,16,17,16,16,17,17,17,17,17,16,17,16,17,17,17,17,17,16,17,16,16,17,17,17,17,},
{17,16,17,16,16,16,17,16,17,17,16,16,16,16,16,17,16,17,16,16,16,17,16,17,16,16,16,16,16,17,},
{17,16,17,16,16,16,17,16,17,16,17,17,16,17,16,17,16,16,17,16,16,17,16,16,17,17,17,16,16,17,},
{17,16,16,16,16,16,17,16,17,16,17,16,16,17,16,17,16,17,16,17,16,17,16,17,17,16,17,16,16,17,},
{17,16,17,17,17,17,17,16,17,16,17,16,16,17,16,17,17,16,16,17,16,17,16,16,16,16,17,16,16,17,},
{17,16,16,17,17,17,17,16,17,16,17,16,16,17,16,16,16,16,17,17,16,17,17,17,17,17,17,16,16,17,},
{17,17,16,16,16,16,17,17,17,16,16,16,16,17,17,17,17,16,17,16,16,17,16,16,16,16,17,16,16,17,},
{17,17,17,16,16,16,16,16,16,16,16,16,16,17,16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,16,},
{17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 70, 70, 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();
Star star = new Star();
// 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, 30, 105);
addObject(new Letters('J'),385,385);
addObject(new Letters('U'),665,1155);
addObject(new Letters('M'),1085,245);
addObject(new Letters('P'),1925,945);
addObject(star, 245, 660);
//addObject(new Enemy(), 1170, 410);
// 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<SUF>
ce.addCollidingMover(hero);
}
@Override
public void act() {
ce.update();
}
}
| false | 2,675 | 16 | 2,737 | 18 | 2,748 | 15 | 2,737 | 18 | 2,818 | 17 | false | false | false | false | false | true |
37 | 24509_4 | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package henkapp;_x000D_
_x000D_
import java.util.Objects;_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author Stijn_x000D_
*/_x000D_
public class Persoon implements Comparable<Persoon>{_x000D_
_x000D_
private String naam;_x000D_
private String plaats;_x000D_
private String telefoon;_x000D_
_x000D_
Persoon(String naam, String plaats, String telefoon) {_x000D_
this.naam = naam;_x000D_
this.plaats = plaats;_x000D_
this.telefoon = telefoon;_x000D_
}_x000D_
_x000D_
@Override_x000D_
public String toString() {_x000D_
return naam + " - " + telefoon;_x000D_
}_x000D_
_x000D_
public String getNaam() {_x000D_
return naam;_x000D_
}_x000D_
_x000D_
public void setNaam(String naam) {_x000D_
this.naam = naam;_x000D_
}_x000D_
_x000D_
public String getPlaats() {_x000D_
return plaats;_x000D_
}_x000D_
_x000D_
public void setPlaats(String plaats) {_x000D_
this.plaats = plaats;_x000D_
}_x000D_
_x000D_
public String getTelefoon() {_x000D_
return telefoon;_x000D_
}_x000D_
_x000D_
public void setTelefoon(String telefoon) {_x000D_
this.telefoon = telefoon;_x000D_
}_x000D_
_x000D_
boolean contentEquals(Persoon p) {_x000D_
if (this.naam.equals(p.getNaam())) {_x000D_
if (this.plaats.equals(p.getPlaats())) {_x000D_
if (this.telefoon.equals(p.getTelefoon())) {_x000D_
return true;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
//Bron: http://stackoverflow.com/questions/185937/overriding-the-java-equals-method-quirk_x000D_
@Override_x000D_
public boolean equals(Object other) {_x000D_
if (other == null) { //Wanneer het andere object null is zijn de twee ongelijk_x000D_
return false;_x000D_
}_x000D_
if (other.hashCode() == this.hashCode()) {_x000D_
return true;_x000D_
}_x000D_
if (!(other instanceof Persoon)) {_x000D_
return false;_x000D_
}_x000D_
Persoon otherPersoon = (Persoon) other;_x000D_
if (this.naam.equals(otherPersoon.getNaam())) {_x000D_
if (this.plaats.equals(otherPersoon.getPlaats())) {_x000D_
if (this.telefoon.equals(otherPersoon.getTelefoon())) {_x000D_
return true;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
// Automatisch gegenereerde hashCode() methode_x000D_
// Geen aanpassingen omdat het me zo goed lijkt_x000D_
@Override_x000D_
public int hashCode() {_x000D_
int hash = 7;_x000D_
hash = 83 * hash + Objects.hashCode(this.naam);_x000D_
hash = 83 * hash + Objects.hashCode(this.plaats);_x000D_
hash = 83 * hash + Objects.hashCode(this.telefoon);_x000D_
return hash;_x000D_
}_x000D_
_x000D_
// Bron:http://www.tutorialspoint.com/java/java_using_comparator.htm_x000D_
// Vergelijken van de namen._x000D_
@Override_x000D_
public int compareTo(Persoon o) {_x000D_
return (this.naam).compareTo(o.naam);_x000D_
}_x000D_
}_x000D_
| 94BasMulder/JCF4MitStijn | HenkApp/src/henkapp/Persoon.java | 864 | // Geen aanpassingen omdat het me zo goed lijkt_x000D_ | line_comment | nl | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package henkapp;_x000D_
_x000D_
import java.util.Objects;_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author Stijn_x000D_
*/_x000D_
public class Persoon implements Comparable<Persoon>{_x000D_
_x000D_
private String naam;_x000D_
private String plaats;_x000D_
private String telefoon;_x000D_
_x000D_
Persoon(String naam, String plaats, String telefoon) {_x000D_
this.naam = naam;_x000D_
this.plaats = plaats;_x000D_
this.telefoon = telefoon;_x000D_
}_x000D_
_x000D_
@Override_x000D_
public String toString() {_x000D_
return naam + " - " + telefoon;_x000D_
}_x000D_
_x000D_
public String getNaam() {_x000D_
return naam;_x000D_
}_x000D_
_x000D_
public void setNaam(String naam) {_x000D_
this.naam = naam;_x000D_
}_x000D_
_x000D_
public String getPlaats() {_x000D_
return plaats;_x000D_
}_x000D_
_x000D_
public void setPlaats(String plaats) {_x000D_
this.plaats = plaats;_x000D_
}_x000D_
_x000D_
public String getTelefoon() {_x000D_
return telefoon;_x000D_
}_x000D_
_x000D_
public void setTelefoon(String telefoon) {_x000D_
this.telefoon = telefoon;_x000D_
}_x000D_
_x000D_
boolean contentEquals(Persoon p) {_x000D_
if (this.naam.equals(p.getNaam())) {_x000D_
if (this.plaats.equals(p.getPlaats())) {_x000D_
if (this.telefoon.equals(p.getTelefoon())) {_x000D_
return true;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
//Bron: http://stackoverflow.com/questions/185937/overriding-the-java-equals-method-quirk_x000D_
@Override_x000D_
public boolean equals(Object other) {_x000D_
if (other == null) { //Wanneer het andere object null is zijn de twee ongelijk_x000D_
return false;_x000D_
}_x000D_
if (other.hashCode() == this.hashCode()) {_x000D_
return true;_x000D_
}_x000D_
if (!(other instanceof Persoon)) {_x000D_
return false;_x000D_
}_x000D_
Persoon otherPersoon = (Persoon) other;_x000D_
if (this.naam.equals(otherPersoon.getNaam())) {_x000D_
if (this.plaats.equals(otherPersoon.getPlaats())) {_x000D_
if (this.telefoon.equals(otherPersoon.getTelefoon())) {_x000D_
return true;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
// Automatisch gegenereerde hashCode() methode_x000D_
// Geen aanpassingen<SUF>
@Override_x000D_
public int hashCode() {_x000D_
int hash = 7;_x000D_
hash = 83 * hash + Objects.hashCode(this.naam);_x000D_
hash = 83 * hash + Objects.hashCode(this.plaats);_x000D_
hash = 83 * hash + Objects.hashCode(this.telefoon);_x000D_
return hash;_x000D_
}_x000D_
_x000D_
// Bron:http://www.tutorialspoint.com/java/java_using_comparator.htm_x000D_
// Vergelijken van de namen._x000D_
@Override_x000D_
public int compareTo(Persoon o) {_x000D_
return (this.naam).compareTo(o.naam);_x000D_
}_x000D_
}_x000D_
| false | 1,335 | 19 | 1,463 | 24 | 1,459 | 18 | 1,463 | 24 | 1,585 | 22 | false | false | false | false | false | true |
1,125 | 124819_13 | package nl.overheid.stelsel.gba.reva.bag.triemap;
import java.io.Serializable;
import org.apache.commons.lang.StringUtils;
public class BagAdres implements Serializable {
private static final long serialVersionUID = -733312179296502981L;
/**
* Een categorisering van de gebruiksdoelen van het betreffende
* VERBLIJFSOBJECT, zoals dit formeel door de overheid als zodanig is
* toegestaan. Een VERBLIJFSOBJECT is de kleinste binnen één of meerdere
* panden gelegen en voor woon -, bedrijfsmatige - of recreatieve doeleinden
* geschikte eenheid van gebruik, die ontsloten wordt via een eigen toegang
* vanaf de openbare weg, een erf of een gedeelde verkeersruimte en die
* onderwerp kan zijn van rechtshandelingen.
*/
private String gebruiksdoel;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nummering.
*/
private String huisnummer;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nadere toevoeging aan een huisnummer of een combinatie
* van huisnummer en huisletter.
*/
private String huisnummertoevoeging;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende toevoeging aan een huisnummer in de vorm van een
* alfanumeriek teken.
*/
private String huisletter;
/**
* De unieke aanduiding van een NUMMERAANDUIDING. Een NUMMERAANDUIDING is een
* door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String nummeraanduidingId;
/**
* Een naam die aan een OPENBARE RUIMTE is toegekend in een daartoe strekkend
* formeel gemeentelijk besluit. Een OPENBARE RUIMTE is een door de
* gemeenteraad als zodanig aangewezen benaming van een binnen 1 woonplaats
* gelegen buitenruimte.
*
*/
private String openbareRuimteNaam;
/**
* De door TNT Post vastgestelde code behorende bij een bepaalde combinatie
* van een straatnaam en een huisnummer.
*/
private String postcode;
/**
* De aard van een als zodanig benoemde NUMMERAANDUIDING. Een NUMMERAANDUIDING
* is een door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String type;
/**
* De landelijk unieke aanduiding van een WOONPLAATS, zoals vastgesteld door
* de beheerder van de landelijke tabel voor woonplaatsen. Een WOONPLAATS is
* een door de gemeenteraad als zodanig aangewezen gedeelte van het
* gemeentelijk grondgebied.
*/
private String woonplaatsId;
/**
* De benaming van een door het gemeentebestuur aangewezen WOONPLAATS. Een
* WOONPLAATS is een door de gemeenteraad als zodanig aangewezen gedeelte van
* het gemeentelijk grondgebied.
*/
private String woonplaatsNaam;
public BagAdres() {
// Lege constructor.
}
public String getGebruiksdoel() {
return gebruiksdoel;
}
public void setGebruiksdoel( String gebruiksdoel ) {
this.gebruiksdoel = gebruiksdoel;
}
public String getHuisnummer() {
return huisnummer;
}
public void setHuisnummer( String huisnummer ) {
this.huisnummer = huisnummer;
}
public String getHuisnummertoevoeging() {
return huisnummertoevoeging;
}
public void setHuisnummertoevoeging( String huisnummertoevoeging ) {
this.huisnummertoevoeging = huisnummertoevoeging;
}
public String getHuisletter() {
return huisletter;
}
public void setHuisletter( String huisletter ) {
this.huisletter = huisletter;
}
public String getNummeraanduidingId() {
return nummeraanduidingId;
}
public void setNummeraanduidingId( String nummeraanduidingId ) {
this.nummeraanduidingId = nummeraanduidingId;
}
public String getOpenbareRuimteNaam() {
return openbareRuimteNaam;
}
public void setOpenbareRuimteNaam( String openbareRuimteNaam ) {
this.openbareRuimteNaam = openbareRuimteNaam;
}
public String getPostcode() {
return postcode;
}
public void setPostcode( String postcode ) {
this.postcode = postcode;
}
public String getType() {
return type;
}
public void setType( String type ) {
this.type = type;
}
public String getWoonplaatsId() {
return woonplaatsId;
}
public void setWoonplaatsId( String woonplaatsId ) {
this.woonplaatsId = woonplaatsId;
}
public String getWoonplaatsNaam() {
return woonplaatsNaam;
}
public void setWoonplaatsNaam( String woonplaatsNaam ) {
this.woonplaatsNaam = woonplaatsNaam;
}
/**
* Geeft de NUMMERAANDUIDING bestaande uit de samenvoeging van:
* (huisnummer)(huisletter)(huisnummertoevoeging)
*
* @return De samengestelde nummeraanduiding.
*/
public String getNummeraanduiding() {
StringBuffer nummeraanduiding = new StringBuffer();
if( huisnummer != null ) {
nummeraanduiding.append( huisnummer );
}
if( huisletter != null ) {
nummeraanduiding.append( huisletter );
}
if( huisnummertoevoeging != null ) {
nummeraanduiding.append( huisnummertoevoeging );
}
return nummeraanduiding.toString();
}
@Override
public boolean equals( Object obj ) {
// Vergelijking met niks.
if( obj == null ) {
return false;
}
// Vergelijking met zichzelf.
if( this == obj ) {
return true;
}
if( obj instanceof BagAdres ) {
BagAdres adres = (BagAdres) obj;
// We gaan ervan uit dat de objecten gelijk zijn, totdat we zeker
// weten dat dit niet zo is.
boolean isEqual = true;
isEqual &= StringUtils.equalsIgnoreCase( gebruiksdoel, adres.getGebruiksdoel() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummer, adres.getHuisnummer() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummertoevoeging, adres.getHuisnummertoevoeging() );
isEqual &= StringUtils.equalsIgnoreCase( huisletter, adres.getHuisletter() );
isEqual &= StringUtils.equalsIgnoreCase( nummeraanduidingId, adres.getNummeraanduidingId() );
isEqual &= StringUtils.equalsIgnoreCase( openbareRuimteNaam, adres.getOpenbareRuimteNaam() );
isEqual &= StringUtils.equalsIgnoreCase( postcode, adres.getPostcode() );
isEqual &= StringUtils.equalsIgnoreCase( type, adres.getType() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsId, adres.getWoonplaatsId() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsNaam, adres.getWoonplaatsNaam() );
return isEqual;
}
return false;
}
@Override
public int hashCode() {
StringBuffer string = new StringBuffer();
string.append( gebruiksdoel );
string.append( huisnummer );
string.append( huisnummertoevoeging );
string.append( huisletter );
string.append( nummeraanduidingId );
string.append( openbareRuimteNaam );
string.append( postcode );
string.append( type );
string.append( woonplaatsId );
string.append( woonplaatsNaam );
return string.toString().hashCode();
}
@Override
public String toString() {
StringBuffer string = new StringBuffer();
string.append( nummeraanduidingId ).append( "," );
string.append( woonplaatsNaam ).append( " " ).append( woonplaatsId ).append( "," );
string.append( openbareRuimteNaam ).append( "," );
if( huisnummer != null ) {
string.append( huisnummer ).append( "," );
}
if( huisletter != null ) {
string.append( huisletter ).append( "," );
}
if( huisnummertoevoeging != null ) {
string.append( huisnummertoevoeging ).append( "," );
}
string.append( postcode ).append( "," );
string.append( type ).append( "," );
string.append( gebruiksdoel );
return string.toString();
}
}
| MinBZK/REVA | huidig-productie-reva/reva/reva-bag/reva-bag-triemap/src/main/java/nl/overheid/stelsel/gba/reva/bag/triemap/BagAdres.java | 2,670 | // We gaan ervan uit dat de objecten gelijk zijn, totdat we zeker | line_comment | nl | package nl.overheid.stelsel.gba.reva.bag.triemap;
import java.io.Serializable;
import org.apache.commons.lang.StringUtils;
public class BagAdres implements Serializable {
private static final long serialVersionUID = -733312179296502981L;
/**
* Een categorisering van de gebruiksdoelen van het betreffende
* VERBLIJFSOBJECT, zoals dit formeel door de overheid als zodanig is
* toegestaan. Een VERBLIJFSOBJECT is de kleinste binnen één of meerdere
* panden gelegen en voor woon -, bedrijfsmatige - of recreatieve doeleinden
* geschikte eenheid van gebruik, die ontsloten wordt via een eigen toegang
* vanaf de openbare weg, een erf of een gedeelde verkeersruimte en die
* onderwerp kan zijn van rechtshandelingen.
*/
private String gebruiksdoel;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nummering.
*/
private String huisnummer;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nadere toevoeging aan een huisnummer of een combinatie
* van huisnummer en huisletter.
*/
private String huisnummertoevoeging;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende toevoeging aan een huisnummer in de vorm van een
* alfanumeriek teken.
*/
private String huisletter;
/**
* De unieke aanduiding van een NUMMERAANDUIDING. Een NUMMERAANDUIDING is een
* door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String nummeraanduidingId;
/**
* Een naam die aan een OPENBARE RUIMTE is toegekend in een daartoe strekkend
* formeel gemeentelijk besluit. Een OPENBARE RUIMTE is een door de
* gemeenteraad als zodanig aangewezen benaming van een binnen 1 woonplaats
* gelegen buitenruimte.
*
*/
private String openbareRuimteNaam;
/**
* De door TNT Post vastgestelde code behorende bij een bepaalde combinatie
* van een straatnaam en een huisnummer.
*/
private String postcode;
/**
* De aard van een als zodanig benoemde NUMMERAANDUIDING. Een NUMMERAANDUIDING
* is een door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String type;
/**
* De landelijk unieke aanduiding van een WOONPLAATS, zoals vastgesteld door
* de beheerder van de landelijke tabel voor woonplaatsen. Een WOONPLAATS is
* een door de gemeenteraad als zodanig aangewezen gedeelte van het
* gemeentelijk grondgebied.
*/
private String woonplaatsId;
/**
* De benaming van een door het gemeentebestuur aangewezen WOONPLAATS. Een
* WOONPLAATS is een door de gemeenteraad als zodanig aangewezen gedeelte van
* het gemeentelijk grondgebied.
*/
private String woonplaatsNaam;
public BagAdres() {
// Lege constructor.
}
public String getGebruiksdoel() {
return gebruiksdoel;
}
public void setGebruiksdoel( String gebruiksdoel ) {
this.gebruiksdoel = gebruiksdoel;
}
public String getHuisnummer() {
return huisnummer;
}
public void setHuisnummer( String huisnummer ) {
this.huisnummer = huisnummer;
}
public String getHuisnummertoevoeging() {
return huisnummertoevoeging;
}
public void setHuisnummertoevoeging( String huisnummertoevoeging ) {
this.huisnummertoevoeging = huisnummertoevoeging;
}
public String getHuisletter() {
return huisletter;
}
public void setHuisletter( String huisletter ) {
this.huisletter = huisletter;
}
public String getNummeraanduidingId() {
return nummeraanduidingId;
}
public void setNummeraanduidingId( String nummeraanduidingId ) {
this.nummeraanduidingId = nummeraanduidingId;
}
public String getOpenbareRuimteNaam() {
return openbareRuimteNaam;
}
public void setOpenbareRuimteNaam( String openbareRuimteNaam ) {
this.openbareRuimteNaam = openbareRuimteNaam;
}
public String getPostcode() {
return postcode;
}
public void setPostcode( String postcode ) {
this.postcode = postcode;
}
public String getType() {
return type;
}
public void setType( String type ) {
this.type = type;
}
public String getWoonplaatsId() {
return woonplaatsId;
}
public void setWoonplaatsId( String woonplaatsId ) {
this.woonplaatsId = woonplaatsId;
}
public String getWoonplaatsNaam() {
return woonplaatsNaam;
}
public void setWoonplaatsNaam( String woonplaatsNaam ) {
this.woonplaatsNaam = woonplaatsNaam;
}
/**
* Geeft de NUMMERAANDUIDING bestaande uit de samenvoeging van:
* (huisnummer)(huisletter)(huisnummertoevoeging)
*
* @return De samengestelde nummeraanduiding.
*/
public String getNummeraanduiding() {
StringBuffer nummeraanduiding = new StringBuffer();
if( huisnummer != null ) {
nummeraanduiding.append( huisnummer );
}
if( huisletter != null ) {
nummeraanduiding.append( huisletter );
}
if( huisnummertoevoeging != null ) {
nummeraanduiding.append( huisnummertoevoeging );
}
return nummeraanduiding.toString();
}
@Override
public boolean equals( Object obj ) {
// Vergelijking met niks.
if( obj == null ) {
return false;
}
// Vergelijking met zichzelf.
if( this == obj ) {
return true;
}
if( obj instanceof BagAdres ) {
BagAdres adres = (BagAdres) obj;
// We gaan<SUF>
// weten dat dit niet zo is.
boolean isEqual = true;
isEqual &= StringUtils.equalsIgnoreCase( gebruiksdoel, adres.getGebruiksdoel() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummer, adres.getHuisnummer() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummertoevoeging, adres.getHuisnummertoevoeging() );
isEqual &= StringUtils.equalsIgnoreCase( huisletter, adres.getHuisletter() );
isEqual &= StringUtils.equalsIgnoreCase( nummeraanduidingId, adres.getNummeraanduidingId() );
isEqual &= StringUtils.equalsIgnoreCase( openbareRuimteNaam, adres.getOpenbareRuimteNaam() );
isEqual &= StringUtils.equalsIgnoreCase( postcode, adres.getPostcode() );
isEqual &= StringUtils.equalsIgnoreCase( type, adres.getType() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsId, adres.getWoonplaatsId() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsNaam, adres.getWoonplaatsNaam() );
return isEqual;
}
return false;
}
@Override
public int hashCode() {
StringBuffer string = new StringBuffer();
string.append( gebruiksdoel );
string.append( huisnummer );
string.append( huisnummertoevoeging );
string.append( huisletter );
string.append( nummeraanduidingId );
string.append( openbareRuimteNaam );
string.append( postcode );
string.append( type );
string.append( woonplaatsId );
string.append( woonplaatsNaam );
return string.toString().hashCode();
}
@Override
public String toString() {
StringBuffer string = new StringBuffer();
string.append( nummeraanduidingId ).append( "," );
string.append( woonplaatsNaam ).append( " " ).append( woonplaatsId ).append( "," );
string.append( openbareRuimteNaam ).append( "," );
if( huisnummer != null ) {
string.append( huisnummer ).append( "," );
}
if( huisletter != null ) {
string.append( huisletter ).append( "," );
}
if( huisnummertoevoeging != null ) {
string.append( huisnummertoevoeging ).append( "," );
}
string.append( postcode ).append( "," );
string.append( type ).append( "," );
string.append( gebruiksdoel );
return string.toString();
}
}
| false | 2,252 | 20 | 2,438 | 21 | 2,216 | 16 | 2,438 | 21 | 2,730 | 22 | false | false | false | false | false | true |
21 | 141870_0 | package view;
import java.awt.Color;
import java.awt.Graphics;
import java.util.HashMap;
import javax.swing.JPanel;
import logic.Counter;
/**
* maak een histogram aan
*/
public class Histogram extends JPanel
{
// hashmap die hoeveelheid per kleur bij houdt
private HashMap<Color, Counter> stats;
// hoogte van de histogram
private int height;
// breedte van de histogram
private int width;
// afstand tussen ieder balk
private final int SPACE = 40;
/**
* leeg constructor
*/
public Histogram()
{
}
/**
* stats wordt toegewezen
* @param stats populate stats
*/
public void stats(HashMap<Color, Counter> stats)
{
this.stats = stats;
}
/**
* bepaald de frame grote van de histogram
* @param width
* @param height
*/
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
}
/**
* maak de histogram
* @param g Graphic component
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// hoogte van de blok
int height;
// breedte van de blok
int width;
if (!stats.isEmpty())
{
width = this.width / stats.size();
}
else
{
width = 4;
}
// blok counter
int blok = 0;
// teken de blok
for (Color color : stats.keySet())
{
// bepaald de hoogte van de blok;
height = stats.get(color).getCount() / 5;
// kleurt de blok
g.setColor(color);
g.fillRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
// paint de outline van de blok
g.setColor(Color.BLACK);
g.drawRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
blok++;
}
}
} | 2ntense/foxes-and-rabbits-v2 | src/view/Histogram.java | 634 | /**
* maak een histogram aan
*/ | block_comment | nl | package view;
import java.awt.Color;
import java.awt.Graphics;
import java.util.HashMap;
import javax.swing.JPanel;
import logic.Counter;
/**
* maak een histogram<SUF>*/
public class Histogram extends JPanel
{
// hashmap die hoeveelheid per kleur bij houdt
private HashMap<Color, Counter> stats;
// hoogte van de histogram
private int height;
// breedte van de histogram
private int width;
// afstand tussen ieder balk
private final int SPACE = 40;
/**
* leeg constructor
*/
public Histogram()
{
}
/**
* stats wordt toegewezen
* @param stats populate stats
*/
public void stats(HashMap<Color, Counter> stats)
{
this.stats = stats;
}
/**
* bepaald de frame grote van de histogram
* @param width
* @param height
*/
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
}
/**
* maak de histogram
* @param g Graphic component
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// hoogte van de blok
int height;
// breedte van de blok
int width;
if (!stats.isEmpty())
{
width = this.width / stats.size();
}
else
{
width = 4;
}
// blok counter
int blok = 0;
// teken de blok
for (Color color : stats.keySet())
{
// bepaald de hoogte van de blok;
height = stats.get(color).getCount() / 5;
// kleurt de blok
g.setColor(color);
g.fillRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
// paint de outline van de blok
g.setColor(Color.BLACK);
g.drawRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
blok++;
}
}
} | false | 500 | 9 | 581 | 10 | 575 | 9 | 581 | 10 | 690 | 11 | false | false | false | false | false | true |
573 | 126690_6 | package be.intectbrussel;
public class Oefenreeks1 {
public static void main(String[] args) {
System.out.println("Operators - Oefenreeks - 1");
System.out.println("---- Oefening - 1 ----");
// 1. Declareer twee integer variabelen, "a" en "b", en geef ze de waarden 5 en 10.
int a = 5;
int b = 10;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de plus operator (+) om de som van "a" en "b" te berekenen en print het resultaat.
int res = a + b;
System.out.println("Som resultaat = " + res);
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de min operator (-) om het verschil tussen "a" en "b" te berekenen en print het resultaat.
res = a - b;
System.out.println("Aftrekking resultaat = " + res);
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de maal operator (*) om het product van "a" en "b" te berekenen en print het resultaat.
res = a * b;
System.out.println("Vermenigvuldiging resultaat = " + res);
System.out.println("---- Oefening - 5 ----");
// 5. Gebruik de gedeeld door operator (/) om het quotient van "a" en "b" te berekenen en print het resultaat.
res = a / b;
System.out.println("Deling resultaat = " + res);
System.out.println("---- Oefening - 6 ----");
// 6. Gebruik de modulo operator (%) om de rest van "a" gedeeld door "b" te berekenen en print het resultaat.
res = a % b;
System.out.println("Rest resultaat = " + res);
System.out.println("---- Oefening - 7 ----");
// 7. Gebruik de increment operator (++) om de waarde van "a" te verhogen met 1 en print het resultaat.
int inc = ++a;
System.out.println("Verhoogde resultaat = " + inc);
System.out.println("---- Oefening - 8 ----");
// 8. Gebruik de decrement operator (--) om de waarde van "a" te verlagen met 1 en print het resultaat.
int dec = --a;
System.out.println("Verlaagde resultaat = " + dec);
System.out.println("---- Oefening - 9 ----");
// 9. Gebruik de gelijk aan vergelijkingsoperator (==) om te controleren of "a" gelijk is aan "b" en print het resultaat.
Boolean boolRes = a == b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
System.out.println("---- Oefening - 10 ----");
// 10. Gebruik de niet gelijk aan vergelijkingsoperator (!=) om te controleren of "a" ongelijk is aan "b" en print het resultaat.
boolRes = a != b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
}
}
| Gabe-Alvess/OperatorsOefening | src/be/intectbrussel/Oefenreeks1.java | 888 | // 7. Gebruik de increment operator (++) om de waarde van "a" te verhogen met 1 en print het resultaat. | line_comment | nl | package be.intectbrussel;
public class Oefenreeks1 {
public static void main(String[] args) {
System.out.println("Operators - Oefenreeks - 1");
System.out.println("---- Oefening - 1 ----");
// 1. Declareer twee integer variabelen, "a" en "b", en geef ze de waarden 5 en 10.
int a = 5;
int b = 10;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de plus operator (+) om de som van "a" en "b" te berekenen en print het resultaat.
int res = a + b;
System.out.println("Som resultaat = " + res);
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de min operator (-) om het verschil tussen "a" en "b" te berekenen en print het resultaat.
res = a - b;
System.out.println("Aftrekking resultaat = " + res);
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de maal operator (*) om het product van "a" en "b" te berekenen en print het resultaat.
res = a * b;
System.out.println("Vermenigvuldiging resultaat = " + res);
System.out.println("---- Oefening - 5 ----");
// 5. Gebruik de gedeeld door operator (/) om het quotient van "a" en "b" te berekenen en print het resultaat.
res = a / b;
System.out.println("Deling resultaat = " + res);
System.out.println("---- Oefening - 6 ----");
// 6. Gebruik de modulo operator (%) om de rest van "a" gedeeld door "b" te berekenen en print het resultaat.
res = a % b;
System.out.println("Rest resultaat = " + res);
System.out.println("---- Oefening - 7 ----");
// 7. Gebruik<SUF>
int inc = ++a;
System.out.println("Verhoogde resultaat = " + inc);
System.out.println("---- Oefening - 8 ----");
// 8. Gebruik de decrement operator (--) om de waarde van "a" te verlagen met 1 en print het resultaat.
int dec = --a;
System.out.println("Verlaagde resultaat = " + dec);
System.out.println("---- Oefening - 9 ----");
// 9. Gebruik de gelijk aan vergelijkingsoperator (==) om te controleren of "a" gelijk is aan "b" en print het resultaat.
Boolean boolRes = a == b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
System.out.println("---- Oefening - 10 ----");
// 10. Gebruik de niet gelijk aan vergelijkingsoperator (!=) om te controleren of "a" ongelijk is aan "b" en print het resultaat.
boolRes = a != b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
}
}
| false | 792 | 33 | 850 | 32 | 828 | 28 | 850 | 32 | 927 | 34 | false | false | false | false | false | true |
3,349 | 7466_19 | package classes;
import java.util.Arrays;
import java.util.Scanner;
import classes.ConsoleColors;
public class Game {
ConsoleColors consolecolor = new ConsoleColors();
public static void Play(String word)
{
Scanner input = new Scanner(System.in); // antwoord van gebruiker opvangen
int rounds=1; // start vanaf ronde
int max_rounds=10; // max aantal rondes van spel sessie
char[] wordC = word.toUpperCase().toCharArray(); // Te raden woord (opsplitsen in letters)
char[] existingC = {' ',' ',' ',' ',' '}; //Bijhouden geraden letters die in het woord voorkomen maar op een andere positie
char[] solutionC = {'*','*','*','*','*'};//Bijhouden geraden oplossing, letters op juiste plaats = woord
String exit = " "; // vergelijkt met exitWord
String exitWord ="stop"; // vergelijkt met exit
boolean win=false; //Spel beëndigen wanneer het woord is geraden
boolean existingCharCheck = false; //Bijhouden of minstens een letter van andere positie werd geraden voor sysout melding
char[] inputC = new char[5]; //gebruikers input opslitsen in letters voor verdere verwerking
//Welkom bericht
//System.out.println(ConsoleColors.BLUE_BOLD + word +" \n"); //Oplossing voor programma test
System.out.println(ConsoleColors.BLUE+"\n Raad het woord bestaande uit vijf letters"+ConsoleColors.RESET);
System.out.println(ConsoleColors.BLUE_BOLD+" * * * * * \n"+ConsoleColors.RESET);
do // zolang rondes (rounds) en niet gewonnen (win)
{
// Geef antwoord in
if(rounds==1)
{
System.out.print(ConsoleColors.PURPLE_BOLD +" | Type "+ConsoleColors.YELLOW_BACKGROUND_BRIGHT+"stop"+ConsoleColors.RESET+ConsoleColors.PURPLE_BOLD+" om het spel te verlaten\n"+ConsoleColors.RESET);
System.out.print(ConsoleColors.PURPLE_BOLD +" | Start met een woord van vijf letters. Je hebt "+max_rounds+" kansen om te raden\n : "+ConsoleColors.RESET);
}
else
{
String space;
if(rounds<10) {
space=" ";
}
else{
space="";
}
System.out.print(ConsoleColors.PURPLE_BOLD +"| Kans "+space+rounds+"/"+max_rounds+" | : "+ConsoleColors.RESET);
}
String inputString = (input.nextLine().toString().toUpperCase()); // Antwoord van gebruiker opvangen
exit = inputString.toLowerCase(); // wordt verder in programma vergeleken met variabele exitWord (stopwoord) om te verlaten
// Controleer string op lengte
while (inputString.length()!=5 && !exit.equals(exitWord)){ //indien antwoord geen vijf letters en niet is gelijk aan stop woord
System.out.println(ConsoleColors.PURPLE_BOLD + " | Voer een geldig vijf letter woord in: "+ConsoleColors.RESET);
inputString = (input.nextLine().toString().toUpperCase()); // Herhaald antwoord gebruiker opvangen indien vorig anwtoord ongeldig
exit = inputString.toLowerCase();// wordt verder in programma vergeleken met variabele exitWord (stopwoord) om te verlaten
}
if(!exit.equals(exitWord))
{
// Controleer antwoord
inputC = inputString.toCharArray();
for(int i = 0;i<wordC.length;i++)
{
if(inputC[i]==wordC[i])
{
solutionC[i]=wordC[i]; //Oplossing bijhouden
}
}
// Controleer of er bestaande letters in het woord zitten op een andere plaats
for(int i = 0;i<wordC.length;i++)
{
for(int j=0;j<wordC.length;j++)
{
if(inputC[i]==wordC[j])
{
if(inputC[i]!=solutionC[j])
{
existingC[i] = inputC[i];
existingCharCheck=true; //Bijhouden of minstens een letter van andere positie geraden voor sysout melding
}
}
}
}
if(Arrays.equals(solutionC, wordC))
{
win=true; // Gewonnen, doorbreek de while loop
}
else
{
Status(inputC,solutionC);
// Bestaande letters weergeven die in het woord voorkomen
if(existingCharCheck)//indien minstens letter bestaat die in het woord voorkomt op andere plaats
{
int spaceAfterChar=0;// formatting, bijhouden hoeveel spaties nodig zijn voor achter getoonde lettes
System.out.print(ConsoleColors.YELLOW_BOLD+" Andere plaats: ");
StringBuilder existingB = new StringBuilder(); // stringbuilder om de letters bij elkaar te zetten, ontdoen van hun array positie, om lege ruimtes te voorkomen bij print
for(int i=0;i<existingC.length;i++)
{
boolean check_double=false;
if(existingC[i]!=' ')// zorgen dat er geen lege ruimte komt tussen de letters, letters bij elkaar en spaties achteraan --> formatting
{
for(int j=0;j<i;j++)
{
if(existingC[j]==existingC[i])
{
check_double=true; // controle om de dubbele letters er uit te halen
}
}
if(!check_double) {
existingB.append(existingC[i]);
existingB.append(" ");// formatting, achter elke letter een spatie
}
else
{
spaceAfterChar=spaceAfterChar+2; // formatting, maak spaties achter de getoonde letters
}
}
else // spatie naar achter zetten --> formatting
{
if(inputC[i]!=solutionC[i])
{
spaceAfterChar=spaceAfterChar+2;
}
else
{
spaceAfterChar=spaceAfterChar+2;
}
}
}
// bestaande letters van andere plaats, lijst leegmaken
for(int i=0;i<existingC.length;i++)
{
existingC[i]=' ';
}
System.out.print(existingB.toString());
// formatting: dynamisch spaties toevoegen aan de hand van de getoonde letters
for(int i=0;i<spaceAfterChar;i++) // formatting, aantal bijgehouden spaties uitprinten voor achter alle getoonde letters
{
System.out.print(" ");
}
existingCharCheck=false; // terug op false zetten om volgende letter te controleren
}
else
{
System.out.print(ConsoleColors.GREEN_BOLD +" Andere plaats: geen "+ConsoleColors.RESET); // geen letters weer te geven die op andere positie in oplossing voorkomen
}
rounds++; // Gespeelde ronde
}
}
}
while(win!=true && rounds<=max_rounds && !exit.equals(exitWord));
// Weergeven gewonnen of verloren
if(!exit.equals(exitWord)) // negeren indien gebruiker stopwoord heeft ingetypt
{
if(win)
{
Status(inputC,solutionC);
System.out.println(ConsoleColors.BLUE_BOLD +"\n\n Proficiat, je hebt het woord: "+word+" volledig geraden"+ConsoleColors.RESET);
}
else
{
System.out.println(ConsoleColors.BLUE_BOLD +"\n\n Jammer, je hebt het woord: "+word+" niet geraden"+ConsoleColors.RESET);
}
System.out.println(ConsoleColors.PURPLE_BOLD +"\n **************************************************** "+ConsoleColors.RESET);
}
}
// FUNCTIE sysout --> Reeds geraden letters weergeven van de juiste oplossing
private static void Status(char[] inputC, char[] solutionC)
{
// letters van gebruikersinvoer printen
System.out.print(ConsoleColors.GREEN_BOLD+" | "+ConsoleColors.BLACK);
for(int i=0;i<inputC.length;i++)
{
System.out.print(inputC[i]+" ");
}
// oplossing printen
System.out.print(ConsoleColors.GREEN_BOLD+" | Geraden: ");
for(int i =0;i<solutionC.length;i++)
{
System.out.print(ConsoleColors.BLUE_BOLD+solutionC[i]+" "+ConsoleColors.RESET);
}
System.out.print(ConsoleColors.GREEN_BOLD + "|"+ConsoleColors.RESET);
}
}
| kennyverheyden/SpelLingo | src/classes/Game.java | 2,575 | // wordt verder in programma vergeleken met variabele exitWord (stopwoord) om te verlaten | line_comment | nl | package classes;
import java.util.Arrays;
import java.util.Scanner;
import classes.ConsoleColors;
public class Game {
ConsoleColors consolecolor = new ConsoleColors();
public static void Play(String word)
{
Scanner input = new Scanner(System.in); // antwoord van gebruiker opvangen
int rounds=1; // start vanaf ronde
int max_rounds=10; // max aantal rondes van spel sessie
char[] wordC = word.toUpperCase().toCharArray(); // Te raden woord (opsplitsen in letters)
char[] existingC = {' ',' ',' ',' ',' '}; //Bijhouden geraden letters die in het woord voorkomen maar op een andere positie
char[] solutionC = {'*','*','*','*','*'};//Bijhouden geraden oplossing, letters op juiste plaats = woord
String exit = " "; // vergelijkt met exitWord
String exitWord ="stop"; // vergelijkt met exit
boolean win=false; //Spel beëndigen wanneer het woord is geraden
boolean existingCharCheck = false; //Bijhouden of minstens een letter van andere positie werd geraden voor sysout melding
char[] inputC = new char[5]; //gebruikers input opslitsen in letters voor verdere verwerking
//Welkom bericht
//System.out.println(ConsoleColors.BLUE_BOLD + word +" \n"); //Oplossing voor programma test
System.out.println(ConsoleColors.BLUE+"\n Raad het woord bestaande uit vijf letters"+ConsoleColors.RESET);
System.out.println(ConsoleColors.BLUE_BOLD+" * * * * * \n"+ConsoleColors.RESET);
do // zolang rondes (rounds) en niet gewonnen (win)
{
// Geef antwoord in
if(rounds==1)
{
System.out.print(ConsoleColors.PURPLE_BOLD +" | Type "+ConsoleColors.YELLOW_BACKGROUND_BRIGHT+"stop"+ConsoleColors.RESET+ConsoleColors.PURPLE_BOLD+" om het spel te verlaten\n"+ConsoleColors.RESET);
System.out.print(ConsoleColors.PURPLE_BOLD +" | Start met een woord van vijf letters. Je hebt "+max_rounds+" kansen om te raden\n : "+ConsoleColors.RESET);
}
else
{
String space;
if(rounds<10) {
space=" ";
}
else{
space="";
}
System.out.print(ConsoleColors.PURPLE_BOLD +"| Kans "+space+rounds+"/"+max_rounds+" | : "+ConsoleColors.RESET);
}
String inputString = (input.nextLine().toString().toUpperCase()); // Antwoord van gebruiker opvangen
exit = inputString.toLowerCase(); // wordt verder in programma vergeleken met variabele exitWord (stopwoord) om te verlaten
// Controleer string op lengte
while (inputString.length()!=5 && !exit.equals(exitWord)){ //indien antwoord geen vijf letters en niet is gelijk aan stop woord
System.out.println(ConsoleColors.PURPLE_BOLD + " | Voer een geldig vijf letter woord in: "+ConsoleColors.RESET);
inputString = (input.nextLine().toString().toUpperCase()); // Herhaald antwoord gebruiker opvangen indien vorig anwtoord ongeldig
exit = inputString.toLowerCase();// wordt verder<SUF>
}
if(!exit.equals(exitWord))
{
// Controleer antwoord
inputC = inputString.toCharArray();
for(int i = 0;i<wordC.length;i++)
{
if(inputC[i]==wordC[i])
{
solutionC[i]=wordC[i]; //Oplossing bijhouden
}
}
// Controleer of er bestaande letters in het woord zitten op een andere plaats
for(int i = 0;i<wordC.length;i++)
{
for(int j=0;j<wordC.length;j++)
{
if(inputC[i]==wordC[j])
{
if(inputC[i]!=solutionC[j])
{
existingC[i] = inputC[i];
existingCharCheck=true; //Bijhouden of minstens een letter van andere positie geraden voor sysout melding
}
}
}
}
if(Arrays.equals(solutionC, wordC))
{
win=true; // Gewonnen, doorbreek de while loop
}
else
{
Status(inputC,solutionC);
// Bestaande letters weergeven die in het woord voorkomen
if(existingCharCheck)//indien minstens letter bestaat die in het woord voorkomt op andere plaats
{
int spaceAfterChar=0;// formatting, bijhouden hoeveel spaties nodig zijn voor achter getoonde lettes
System.out.print(ConsoleColors.YELLOW_BOLD+" Andere plaats: ");
StringBuilder existingB = new StringBuilder(); // stringbuilder om de letters bij elkaar te zetten, ontdoen van hun array positie, om lege ruimtes te voorkomen bij print
for(int i=0;i<existingC.length;i++)
{
boolean check_double=false;
if(existingC[i]!=' ')// zorgen dat er geen lege ruimte komt tussen de letters, letters bij elkaar en spaties achteraan --> formatting
{
for(int j=0;j<i;j++)
{
if(existingC[j]==existingC[i])
{
check_double=true; // controle om de dubbele letters er uit te halen
}
}
if(!check_double) {
existingB.append(existingC[i]);
existingB.append(" ");// formatting, achter elke letter een spatie
}
else
{
spaceAfterChar=spaceAfterChar+2; // formatting, maak spaties achter de getoonde letters
}
}
else // spatie naar achter zetten --> formatting
{
if(inputC[i]!=solutionC[i])
{
spaceAfterChar=spaceAfterChar+2;
}
else
{
spaceAfterChar=spaceAfterChar+2;
}
}
}
// bestaande letters van andere plaats, lijst leegmaken
for(int i=0;i<existingC.length;i++)
{
existingC[i]=' ';
}
System.out.print(existingB.toString());
// formatting: dynamisch spaties toevoegen aan de hand van de getoonde letters
for(int i=0;i<spaceAfterChar;i++) // formatting, aantal bijgehouden spaties uitprinten voor achter alle getoonde letters
{
System.out.print(" ");
}
existingCharCheck=false; // terug op false zetten om volgende letter te controleren
}
else
{
System.out.print(ConsoleColors.GREEN_BOLD +" Andere plaats: geen "+ConsoleColors.RESET); // geen letters weer te geven die op andere positie in oplossing voorkomen
}
rounds++; // Gespeelde ronde
}
}
}
while(win!=true && rounds<=max_rounds && !exit.equals(exitWord));
// Weergeven gewonnen of verloren
if(!exit.equals(exitWord)) // negeren indien gebruiker stopwoord heeft ingetypt
{
if(win)
{
Status(inputC,solutionC);
System.out.println(ConsoleColors.BLUE_BOLD +"\n\n Proficiat, je hebt het woord: "+word+" volledig geraden"+ConsoleColors.RESET);
}
else
{
System.out.println(ConsoleColors.BLUE_BOLD +"\n\n Jammer, je hebt het woord: "+word+" niet geraden"+ConsoleColors.RESET);
}
System.out.println(ConsoleColors.PURPLE_BOLD +"\n **************************************************** "+ConsoleColors.RESET);
}
}
// FUNCTIE sysout --> Reeds geraden letters weergeven van de juiste oplossing
private static void Status(char[] inputC, char[] solutionC)
{
// letters van gebruikersinvoer printen
System.out.print(ConsoleColors.GREEN_BOLD+" | "+ConsoleColors.BLACK);
for(int i=0;i<inputC.length;i++)
{
System.out.print(inputC[i]+" ");
}
// oplossing printen
System.out.print(ConsoleColors.GREEN_BOLD+" | Geraden: ");
for(int i =0;i<solutionC.length;i++)
{
System.out.print(ConsoleColors.BLUE_BOLD+solutionC[i]+" "+ConsoleColors.RESET);
}
System.out.print(ConsoleColors.GREEN_BOLD + "|"+ConsoleColors.RESET);
}
}
| false | 2,008 | 25 | 2,364 | 28 | 2,128 | 23 | 2,364 | 28 | 3,098 | 24 | false | false | false | false | false | true |
1,235 | 83873_6 | package be.kuleuven.candycrush;
import java.util.*;
import java.util.function.Function;
public class Board<T> {
private volatile Map<Position,T> map;
private volatile Map<T, List<Position>> reverseMap;
private volatile BoardSize boardsize;
public Board(BoardSize boardsize){
this.boardsize = boardsize;
map = new HashMap<>(boardsize.columns()* boardsize.rows());//map for your cells content
reverseMap = new HashMap<>(boardsize.columns()* boardsize.rows());
}
public BoardSize getBoardsize(){
return boardsize;
}
public synchronized T getCellAt(Position position){//om de cel op een gegeven positie van het bord op te vragen.
return this.map.get(position);
//return typeList.get(position.toIndex());
}
public synchronized void replaceCellAt(Position position, T newCell) {
T oldCellContent = map.get(position);
map.put(position, newCell);
List<Position> positions = reverseMap.get(oldCellContent);
if (positions != null) {
positions.remove(position);
if (positions.isEmpty()) {
reverseMap.remove(oldCellContent);
}
}
reverseMap.computeIfAbsent(newCell, k -> new ArrayList<>()).add(position);
}
public synchronized void fill(Function<Position, T> cellCreator){//om het hele bord te vullen. De fill-functie heeft als parameter een Function-object (cellCreator) die, gegeven een Positie-object, een nieuw cel-object teruggeeft.
map.clear();
reverseMap.clear();
// Clear the map first
for (int i = 0; i < this.boardsize.columns()*this.boardsize.rows(); i++){
// For every position put a random candy using cellCreator
Position positionIndex = Position.fromIndex(i,this.boardsize);
T cellContent = cellCreator.apply(positionIndex);
map.put(positionIndex, cellContent);
reverseMap.computeIfAbsent(cellContent, k -> new ArrayList<>()).add(positionIndex);
}
}
public synchronized void copyTo(Board<T> otherBoard)
{ // Die alle cellen van het huidige bord kopieert naar het meegegeven bord. Als het meegegeven bord niet dezelfde afmetingen heeft, gooit het een exception.
// Gooi exception als het lukt
if(!Objects.equals(boardsize.columns(), otherBoard.boardsize.columns()) && !Objects.equals(boardsize.rows(), otherBoard.boardsize.rows()))
{
throw new IllegalArgumentException("De boardsizes komen niet overeen.\r\nFunction -> copyTo");
}
else
{
for (Map.Entry<Position, T> entry : map.entrySet()) {
Position position = entry.getKey();
T value = entry.getValue();
otherBoard.map.put(new Position(position.rowOfIndex(), position.colOfIndex(), otherBoard.boardsize), value);
}
}
}
// Methode om alle posities van een element (cel) op te halen
public synchronized List<Position> getPositionsOfElement(T element) {
return reverseMap.getOrDefault(element, Collections.emptyList());
}
public void emptyBoard(){
map.clear();
}
} | OforiDarren/Candy_Crush_repo | candycrush/src/main/java/be/kuleuven/candycrush/Board.java | 885 | // Gooi exception als het lukt | line_comment | nl | package be.kuleuven.candycrush;
import java.util.*;
import java.util.function.Function;
public class Board<T> {
private volatile Map<Position,T> map;
private volatile Map<T, List<Position>> reverseMap;
private volatile BoardSize boardsize;
public Board(BoardSize boardsize){
this.boardsize = boardsize;
map = new HashMap<>(boardsize.columns()* boardsize.rows());//map for your cells content
reverseMap = new HashMap<>(boardsize.columns()* boardsize.rows());
}
public BoardSize getBoardsize(){
return boardsize;
}
public synchronized T getCellAt(Position position){//om de cel op een gegeven positie van het bord op te vragen.
return this.map.get(position);
//return typeList.get(position.toIndex());
}
public synchronized void replaceCellAt(Position position, T newCell) {
T oldCellContent = map.get(position);
map.put(position, newCell);
List<Position> positions = reverseMap.get(oldCellContent);
if (positions != null) {
positions.remove(position);
if (positions.isEmpty()) {
reverseMap.remove(oldCellContent);
}
}
reverseMap.computeIfAbsent(newCell, k -> new ArrayList<>()).add(position);
}
public synchronized void fill(Function<Position, T> cellCreator){//om het hele bord te vullen. De fill-functie heeft als parameter een Function-object (cellCreator) die, gegeven een Positie-object, een nieuw cel-object teruggeeft.
map.clear();
reverseMap.clear();
// Clear the map first
for (int i = 0; i < this.boardsize.columns()*this.boardsize.rows(); i++){
// For every position put a random candy using cellCreator
Position positionIndex = Position.fromIndex(i,this.boardsize);
T cellContent = cellCreator.apply(positionIndex);
map.put(positionIndex, cellContent);
reverseMap.computeIfAbsent(cellContent, k -> new ArrayList<>()).add(positionIndex);
}
}
public synchronized void copyTo(Board<T> otherBoard)
{ // Die alle cellen van het huidige bord kopieert naar het meegegeven bord. Als het meegegeven bord niet dezelfde afmetingen heeft, gooit het een exception.
// Gooi exception<SUF>
if(!Objects.equals(boardsize.columns(), otherBoard.boardsize.columns()) && !Objects.equals(boardsize.rows(), otherBoard.boardsize.rows()))
{
throw new IllegalArgumentException("De boardsizes komen niet overeen.\r\nFunction -> copyTo");
}
else
{
for (Map.Entry<Position, T> entry : map.entrySet()) {
Position position = entry.getKey();
T value = entry.getValue();
otherBoard.map.put(new Position(position.rowOfIndex(), position.colOfIndex(), otherBoard.boardsize), value);
}
}
}
// Methode om alle posities van een element (cel) op te halen
public synchronized List<Position> getPositionsOfElement(T element) {
return reverseMap.getOrDefault(element, Collections.emptyList());
}
public void emptyBoard(){
map.clear();
}
} | false | 687 | 9 | 793 | 10 | 812 | 8 | 793 | 10 | 872 | 8 | false | false | false | false | false | true |
1,882 | 32612_1 | package data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.*;
public class GameLogic {
private int clickCount = 0; // Begin state
private int pairsMatched = 0;
private MainButton firstClickedButton = null;
private List<Integer> number = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8));
private String[] imagePaths = {
"data/images/apple.png", "data/images/avocado.png", "data/images/banana.png", "data/images/genipe.png",
"data/images/mandarin.png", "data/images/orange.png", "data/images/pumpkin.png", "data/images/watermelon.png"
};
private JPanel panel;
public GameLogic(JPanel panel) {
this.panel = panel;
Collections.shuffle(number);
initializeButtons();
}
private void initializeButtons() {
// Begin state voor de buttons
for (int buttonAmount = 0; buttonAmount < 16; buttonAmount++) {
int imageCount = number.get(buttonAmount) - 1;
MainButton button = new MainButton();
button.setFruitImage(imagePaths[imageCount]);
button.setName(Integer.toString(buttonAmount));
panel.add(button);
button.addActionListener(ac);
}
}
public void resetGame() {
clickCount = 0; // Begin state
pairsMatched = 0;
number.clear();
number.addAll(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8));
Collections.shuffle(number);
panel.removeAll();
initializeButtons();
panel.revalidate();
panel.repaint();
}
ActionListener ac = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clickCount++;
System.out.println(clickCount);
MainButton button = (MainButton)e.getSource();
if (clickCount == 1) {
firstClickedButton = button;
button.setBgImage(button.getFruitImage());
}
if (clickCount == 2) {
button.setBgImage(button.getFruitImage());
if (firstClickedButton != button && button.getFruitImage().equals(firstClickedButton.getFruitImage())) {
// Als zee gelijk zijn worden de buttens gedisabled.
System.out.println("Dit klopt");
button.setEnabled(false);
firstClickedButton.setEnabled(false);
pairsMatched++;
if (pairsMatched == 8) { // Als alles gelijk is krijg je een succes message en word de game gereset.
JOptionPane.showMessageDialog(panel, "You won!");
resetGame();
}
clickCount = 0; // reset the clickcount als het 2 is
firstClickedButton = null;
} else {
// Timer met 2 sec delay
Timer t = new Timer(1000, event -> {
System.out.println("Dit klopt niet");
firstClickedButton.setBgImage(null);
button.setBgImage(null);
clickCount = 0;
firstClickedButton = null;
});
t.start();
t.setRepeats(false); // Zorgt ervoor dat de timer maar een keer word uitgevoerd
}
}
}
};
} | Woaby/Memory-game-java | data/GameLogic.java | 1,055 | // Als zee gelijk zijn worden de buttens gedisabled. | line_comment | nl | package data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.*;
public class GameLogic {
private int clickCount = 0; // Begin state
private int pairsMatched = 0;
private MainButton firstClickedButton = null;
private List<Integer> number = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8));
private String[] imagePaths = {
"data/images/apple.png", "data/images/avocado.png", "data/images/banana.png", "data/images/genipe.png",
"data/images/mandarin.png", "data/images/orange.png", "data/images/pumpkin.png", "data/images/watermelon.png"
};
private JPanel panel;
public GameLogic(JPanel panel) {
this.panel = panel;
Collections.shuffle(number);
initializeButtons();
}
private void initializeButtons() {
// Begin state voor de buttons
for (int buttonAmount = 0; buttonAmount < 16; buttonAmount++) {
int imageCount = number.get(buttonAmount) - 1;
MainButton button = new MainButton();
button.setFruitImage(imagePaths[imageCount]);
button.setName(Integer.toString(buttonAmount));
panel.add(button);
button.addActionListener(ac);
}
}
public void resetGame() {
clickCount = 0; // Begin state
pairsMatched = 0;
number.clear();
number.addAll(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8));
Collections.shuffle(number);
panel.removeAll();
initializeButtons();
panel.revalidate();
panel.repaint();
}
ActionListener ac = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clickCount++;
System.out.println(clickCount);
MainButton button = (MainButton)e.getSource();
if (clickCount == 1) {
firstClickedButton = button;
button.setBgImage(button.getFruitImage());
}
if (clickCount == 2) {
button.setBgImage(button.getFruitImage());
if (firstClickedButton != button && button.getFruitImage().equals(firstClickedButton.getFruitImage())) {
// Als zee<SUF>
System.out.println("Dit klopt");
button.setEnabled(false);
firstClickedButton.setEnabled(false);
pairsMatched++;
if (pairsMatched == 8) { // Als alles gelijk is krijg je een succes message en word de game gereset.
JOptionPane.showMessageDialog(panel, "You won!");
resetGame();
}
clickCount = 0; // reset the clickcount als het 2 is
firstClickedButton = null;
} else {
// Timer met 2 sec delay
Timer t = new Timer(1000, event -> {
System.out.println("Dit klopt niet");
firstClickedButton.setBgImage(null);
button.setBgImage(null);
clickCount = 0;
firstClickedButton = null;
});
t.start();
t.setRepeats(false); // Zorgt ervoor dat de timer maar een keer word uitgevoerd
}
}
}
};
} | false | 789 | 15 | 885 | 15 | 939 | 13 | 885 | 15 | 1,065 | 16 | false | false | false | false | false | true |
2,281 | 22436_1 | package projectd;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class Item {
private int xCoordinate;
private int yCoordinate;
protected int width;
protected int height;
private JLabel sprite = null;
private BufferedImage myPicture = null;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getxCoordinate() {
return xCoordinate;
}
public void setxCoordinate(int _xCoordinate) {//verplaatsen naar view
this.xCoordinate = _xCoordinate;
sprite.setLocation(xCoordinate, yCoordinate + 100);
sprite.setBounds(xCoordinate, yCoordinate + 100, width, height);
}
public int getyCoordinate() {
return yCoordinate;
}
public void setyCoordinate(int _yCoordinate) {
this.yCoordinate = _yCoordinate;
sprite.setLocation(xCoordinate, yCoordinate + 100);
sprite.setBounds(xCoordinate, yCoordinate + 100, width, height);
}
public JLabel getSprite() {
return sprite;
}
public void setSprite(String path) throws IOException {
myPicture = ImageIO.read(new File(path));
sprite = new JLabel(new ImageIcon(myPicture));
}
public boolean isColliding(Item i) {//Doordat we werken met velden en zonder soepele bewegingen
//this collider
int r1 = (int) (getxCoordinate() + width);
int l1 = (int) (getxCoordinate());
int t1 = (int) (getyCoordinate() + width);
int b1 = (int) (getyCoordinate());
//the other collider
int r2 = (int) (i.getxCoordinate() + i.getWidth());
int l2 = (int) (i.getxCoordinate());
int t2 = (int) (i.getyCoordinate() + i.getHeight());
int b2 = (int) (i.getyCoordinate());
if (r1 < l2 || l1 > r2 || t1 < b2 || b1 > t2) {
return false;
} else {
return true;
}
}
}
| bootv2/ProjectD_9e | project/ProjectD/src/projectd/Item.java | 715 | //Doordat we werken met velden en zonder soepele bewegingen | line_comment | nl | package projectd;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class Item {
private int xCoordinate;
private int yCoordinate;
protected int width;
protected int height;
private JLabel sprite = null;
private BufferedImage myPicture = null;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getxCoordinate() {
return xCoordinate;
}
public void setxCoordinate(int _xCoordinate) {//verplaatsen naar view
this.xCoordinate = _xCoordinate;
sprite.setLocation(xCoordinate, yCoordinate + 100);
sprite.setBounds(xCoordinate, yCoordinate + 100, width, height);
}
public int getyCoordinate() {
return yCoordinate;
}
public void setyCoordinate(int _yCoordinate) {
this.yCoordinate = _yCoordinate;
sprite.setLocation(xCoordinate, yCoordinate + 100);
sprite.setBounds(xCoordinate, yCoordinate + 100, width, height);
}
public JLabel getSprite() {
return sprite;
}
public void setSprite(String path) throws IOException {
myPicture = ImageIO.read(new File(path));
sprite = new JLabel(new ImageIcon(myPicture));
}
public boolean isColliding(Item i) {//Doordat we<SUF>
//this collider
int r1 = (int) (getxCoordinate() + width);
int l1 = (int) (getxCoordinate());
int t1 = (int) (getyCoordinate() + width);
int b1 = (int) (getyCoordinate());
//the other collider
int r2 = (int) (i.getxCoordinate() + i.getWidth());
int l2 = (int) (i.getxCoordinate());
int t2 = (int) (i.getyCoordinate() + i.getHeight());
int b2 = (int) (i.getyCoordinate());
if (r1 < l2 || l1 > r2 || t1 < b2 || b1 > t2) {
return false;
} else {
return true;
}
}
}
| false | 549 | 19 | 613 | 21 | 649 | 14 | 613 | 21 | 734 | 20 | false | false | false | false | false | true |
3,530 | 1689_3 | package com.busenzo.domein;
import java.time.LocalDateTime;
public class Rit {
private LocalDateTime verwachteAankomstTijd;
private LocalDateTime aankomstTijd;
private Bus bus;
private Lijn lijn;
private String ID;
/**
* Maak een rit aan op een bepaalde lijn
* @param verwachtteAankomstTijd De verwachtte aankomsttijd bij de eindhalte
* @param lijn: De lijn waarbij deze rit hoort, nooit null
*/
public Rit(LocalDateTime verwachtteAankomstTijd, Lijn lijn, String ritID) {
this.lijn = lijn;
this.verwachteAankomstTijd = verwachtteAankomstTijd;
this.ID = ritID;
}
/**
* Haal de bus op die deze rit rijdt.
* @return De bus die deze rit rijdt. Kan null zijn als de rit nog niet vertrokken is
*/
public Bus getBus() {
return this.bus;
}
public String getRitID()
{
return this.ID;
}
public void setAankomstTijd(LocalDateTime aankomstTijd)
{
this.aankomstTijd = aankomstTijd;
}
/**
* Haal de lijn op waarbij deze rit hoort
* @return De lijn waarop deze rit rijdt
*/
public Lijn getLijn() {
return this.lijn;
}
/**
* Haal de verwachtte aankomsttijd bij de eindhalte op
* @return de verwachtte aankomsttijd bij de eindhalte
*/
public LocalDateTime getVerwachteAankomstTijd() {
return verwachteAankomstTijd;
}
/**
* Vraag de verwachtte aankomsttijd op bij de volgende halte
* @return De verwachtte aankomsttijd bij de volgende halte
*/
public LocalDateTime getAankomstTijd() {
return aankomstTijd;
}
/**
* Voeg een bus toe welke deze rit gaat rijden.
* @param bus : De bus die deze rit gaat rijden, mag niet null zijn
*/
public void setBus(Bus bus) {
this.bus = bus;
}
} | maartenpeels/Bus-Tracker | src/com/busenzo/domein/Rit.java | 618 | /**
* Haal de verwachtte aankomsttijd bij de eindhalte op
* @return de verwachtte aankomsttijd bij de eindhalte
*/ | block_comment | nl | package com.busenzo.domein;
import java.time.LocalDateTime;
public class Rit {
private LocalDateTime verwachteAankomstTijd;
private LocalDateTime aankomstTijd;
private Bus bus;
private Lijn lijn;
private String ID;
/**
* Maak een rit aan op een bepaalde lijn
* @param verwachtteAankomstTijd De verwachtte aankomsttijd bij de eindhalte
* @param lijn: De lijn waarbij deze rit hoort, nooit null
*/
public Rit(LocalDateTime verwachtteAankomstTijd, Lijn lijn, String ritID) {
this.lijn = lijn;
this.verwachteAankomstTijd = verwachtteAankomstTijd;
this.ID = ritID;
}
/**
* Haal de bus op die deze rit rijdt.
* @return De bus die deze rit rijdt. Kan null zijn als de rit nog niet vertrokken is
*/
public Bus getBus() {
return this.bus;
}
public String getRitID()
{
return this.ID;
}
public void setAankomstTijd(LocalDateTime aankomstTijd)
{
this.aankomstTijd = aankomstTijd;
}
/**
* Haal de lijn op waarbij deze rit hoort
* @return De lijn waarop deze rit rijdt
*/
public Lijn getLijn() {
return this.lijn;
}
/**
* Haal de verwachtte<SUF>*/
public LocalDateTime getVerwachteAankomstTijd() {
return verwachteAankomstTijd;
}
/**
* Vraag de verwachtte aankomsttijd op bij de volgende halte
* @return De verwachtte aankomsttijd bij de volgende halte
*/
public LocalDateTime getAankomstTijd() {
return aankomstTijd;
}
/**
* Voeg een bus toe welke deze rit gaat rijden.
* @param bus : De bus die deze rit gaat rijden, mag niet null zijn
*/
public void setBus(Bus bus) {
this.bus = bus;
}
} | false | 563 | 46 | 603 | 44 | 547 | 35 | 603 | 44 | 649 | 45 | false | false | false | false | false | true |
3,310 | 172963_2 | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList();
}
/**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.currentTimeMillis();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec.";
}
}
/**
* override van toString methode. Geeft alle tijdsperiode weer.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
} | jussihailu1/Rat-in-a-maze-Backtracking | FUN-Algorithm/src/main/java/TimeStamp.java | 1,266 | /**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/ | block_comment | nl | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList();
}
/**
* zet begintijdstip. gebruik<SUF>*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.currentTimeMillis();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec.";
}
}
/**
* override van toString methode. Geeft alle tijdsperiode weer.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
} | false | 1,079 | 32 | 1,173 | 30 | 1,115 | 25 | 1,173 | 30 | 1,286 | 32 | false | false | false | false | false | true |
2,985 | 51838_0 | package nl.novi.Structural.Adapter.holes;
public class SquarePegAdapter extends RoundPeg{
public SquarePeg peg;
public SquarePegAdapter(SquarePeg peg) {
super(0); // wat je hier invult is niet belangrijk
this.peg = peg;
}
public int getRadius(){
return (int) (peg.getWidth() * Math.sqrt(2)/2);
}
}
| hogeschoolnovi/design-patterns-voorbeelden | src/main/java/nl/novi/Structural/Adapter/holes/SquarePegAdapter.java | 111 | // wat je hier invult is niet belangrijk | line_comment | nl | package nl.novi.Structural.Adapter.holes;
public class SquarePegAdapter extends RoundPeg{
public SquarePeg peg;
public SquarePegAdapter(SquarePeg peg) {
super(0); // wat je<SUF>
this.peg = peg;
}
public int getRadius(){
return (int) (peg.getWidth() * Math.sqrt(2)/2);
}
}
| false | 92 | 10 | 103 | 13 | 99 | 9 | 103 | 13 | 119 | 10 | false | false | false | false | false | true |
694 | 127922_0 | class Student {
// STRINGS ==============================================
// Schrijf een functie "String repeat(String str, int n)" die een nieuwe string construeert
// door n keer de string str te herhalen. Je mag ervan uitgaan dat n niet negatief is.
//
// E.g. repeat("abc", 3) returns "abcabcabc"
} | Het-Didactische-Hulpmiddelen-Team/MJQuestions | 04-strings/repeat/Student.java | 96 | // Schrijf een functie "String repeat(String str, int n)" die een nieuwe string construeert | line_comment | nl | class Student {
// STRINGS ==============================================
// Schrijf een<SUF>
// door n keer de string str te herhalen. Je mag ervan uitgaan dat n niet negatief is.
//
// E.g. repeat("abc", 3) returns "abcabcabc"
} | false | 85 | 23 | 89 | 26 | 89 | 22 | 89 | 26 | 101 | 26 | false | false | false | false | false | true |
756 | 53303_7 | /*_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.EpCompiler;_x000D_
_x000D_
import java.io.IOException;_x000D_
_x000D_
import org.apache.log4j.Logger;_x000D_
_x000D_
import nl.imvertor.common.Configurator;_x000D_
import nl.imvertor.common.Step;_x000D_
import nl.imvertor.common.Transformer;_x000D_
import nl.imvertor.common.exceptions.ConfiguratorException;_x000D_
import nl.imvertor.common.file.AnyFile;_x000D_
import nl.imvertor.common.file.AnyFolder;_x000D_
import nl.imvertor.common.file.XmlFile;_x000D_
_x000D_
// see also https://github.com/Imvertor/Imvertor-Maven/issues/56_x000D_
_x000D_
public class EpCompiler extends Step {_x000D_
_x000D_
protected static final Logger logger = Logger.getLogger(EpCompiler.class);_x000D_
_x000D_
public static final String STEP_NAME = "EpCompiler";_x000D_
public static final String VC_IDENTIFIER = "$Id: $";_x000D_
_x000D_
/**_x000D_
* run the main translation_x000D_
*/_x000D_
public boolean run() throws Exception{_x000D_
_x000D_
// set up the configuration for this step_x000D_
configurator.setActiveStepName(STEP_NAME);_x000D_
prepare();_x000D_
_x000D_
runner.info(logger,"Compiling EP");_x000D_
_x000D_
generate();_x000D_
_x000D_
configurator.setStepDone(STEP_NAME);_x000D_
_x000D_
// save any changes to the work configuration for report and future steps_x000D_
configurator.save();_x000D_
_x000D_
report();_x000D_
_x000D_
return runner.succeeds();_x000D_
}_x000D_
_x000D_
/**_x000D_
* Generate EP file suited for Kadaster and OGC Json schema._x000D_
* _x000D_
* @throws Exception_x000D_
*/_x000D_
public boolean generate() throws Exception {_x000D_
_x000D_
// create a transformer_x000D_
Transformer transformer = new Transformer();_x000D_
_x000D_
boolean succeeds = true;_x000D_
_x000D_
runner.debug(logger,"CHAIN","Generating EP");_x000D_
_x000D_
String epSchema = (requiresMIM() ? "EP2.xsd" : "EP.xsd");_x000D_
_x000D_
transformer.setXslParm("ep-schema-path","xsd/" + epSchema); _x000D_
_x000D_
// Create EP_x000D_
if (requiresMIM()) {_x000D_
// check of MIM resultaat beschikbaar is _x000D_
succeeds = succeeds && AnyFile.exists(configurator.getXParm("properties/WORK_MIMFORMAT_XMLPATH",false));_x000D_
// verwerk MIM naar EP_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_MIMFORMAT_XMLPATH","properties/WORK_EP_XMLPATH_PRE", "properties/IMVERTOR_EP2_XSLPATH_PRE");_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_PRE","properties/WORK_EP_XMLPATH_CORE", "properties/IMVERTOR_EP2_XSLPATH_CORE");_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_CORE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP2_XSLPATH_POST");_x000D_
} else _x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EMBELLISH_FILE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP_XSLPATH");_x000D_
_x000D_
_x000D_
// if this succeeds, copy the EP schema to the app and validate_x000D_
if (succeeds) {_x000D_
AnyFolder workAppFolder = new AnyFolder(Configurator.getInstance().getXParm("system/work-app-folder-path"));_x000D_
_x000D_
XmlFile resultEpFile = new XmlFile(configurator.getXParm("properties/WORK_EP_XMLPATH_FINAL"));_x000D_
XmlFile targetEpFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/ep.xml"); // TODO nette naam, bepaald door gebruiker oid._x000D_
resultEpFile.copyFile(targetEpFile);_x000D_
_x000D_
XmlFile managedSchemaFile = new XmlFile(Configurator.getInstance().getBaseFolder().getCanonicalPath() + "/etc/xsd/EP/" + epSchema);_x000D_
XmlFile targetSchemaFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/xsd/" + epSchema);_x000D_
managedSchemaFile.copyFile(targetSchemaFile);_x000D_
_x000D_
// Debug: test if EP is okay_x000D_
succeeds = succeeds && resultEpFile.isValid();_x000D_
}_x000D_
configurator.setXParm("system/ep-schema-created",succeeds);_x000D_
configurator.setXParm("system/ep-schema-version",requiresMIM() ? "2" : "1"); // when MIM based, generated EP version 2_x000D_
_x000D_
return succeeds;_x000D_
}_x000D_
_x000D_
public static Boolean requiresMIM() throws IOException, ConfiguratorException {_x000D_
// bepaal of hier de MIM schema variant moet worden gebruikt_x000D_
String jsonschemasource = Configurator.getInstance().getXParm("cli/jsonschemasource",false);_x000D_
return (jsonschemasource == null || jsonschemasource.equals("MIM"));_x000D_
} _x000D_
_x000D_
}_x000D_
| Imvertor/Imvertor-Maven | src/main/java/nl/imvertor/EpCompiler/EpCompiler.java | 1,599 | // check of MIM resultaat beschikbaar is _x000D_ | line_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.EpCompiler;_x000D_
_x000D_
import java.io.IOException;_x000D_
_x000D_
import org.apache.log4j.Logger;_x000D_
_x000D_
import nl.imvertor.common.Configurator;_x000D_
import nl.imvertor.common.Step;_x000D_
import nl.imvertor.common.Transformer;_x000D_
import nl.imvertor.common.exceptions.ConfiguratorException;_x000D_
import nl.imvertor.common.file.AnyFile;_x000D_
import nl.imvertor.common.file.AnyFolder;_x000D_
import nl.imvertor.common.file.XmlFile;_x000D_
_x000D_
// see also https://github.com/Imvertor/Imvertor-Maven/issues/56_x000D_
_x000D_
public class EpCompiler extends Step {_x000D_
_x000D_
protected static final Logger logger = Logger.getLogger(EpCompiler.class);_x000D_
_x000D_
public static final String STEP_NAME = "EpCompiler";_x000D_
public static final String VC_IDENTIFIER = "$Id: $";_x000D_
_x000D_
/**_x000D_
* run the main translation_x000D_
*/_x000D_
public boolean run() throws Exception{_x000D_
_x000D_
// set up the configuration for this step_x000D_
configurator.setActiveStepName(STEP_NAME);_x000D_
prepare();_x000D_
_x000D_
runner.info(logger,"Compiling EP");_x000D_
_x000D_
generate();_x000D_
_x000D_
configurator.setStepDone(STEP_NAME);_x000D_
_x000D_
// save any changes to the work configuration for report and future steps_x000D_
configurator.save();_x000D_
_x000D_
report();_x000D_
_x000D_
return runner.succeeds();_x000D_
}_x000D_
_x000D_
/**_x000D_
* Generate EP file suited for Kadaster and OGC Json schema._x000D_
* _x000D_
* @throws Exception_x000D_
*/_x000D_
public boolean generate() throws Exception {_x000D_
_x000D_
// create a transformer_x000D_
Transformer transformer = new Transformer();_x000D_
_x000D_
boolean succeeds = true;_x000D_
_x000D_
runner.debug(logger,"CHAIN","Generating EP");_x000D_
_x000D_
String epSchema = (requiresMIM() ? "EP2.xsd" : "EP.xsd");_x000D_
_x000D_
transformer.setXslParm("ep-schema-path","xsd/" + epSchema); _x000D_
_x000D_
// Create EP_x000D_
if (requiresMIM()) {_x000D_
// check of<SUF>
succeeds = succeeds && AnyFile.exists(configurator.getXParm("properties/WORK_MIMFORMAT_XMLPATH",false));_x000D_
// verwerk MIM naar EP_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_MIMFORMAT_XMLPATH","properties/WORK_EP_XMLPATH_PRE", "properties/IMVERTOR_EP2_XSLPATH_PRE");_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_PRE","properties/WORK_EP_XMLPATH_CORE", "properties/IMVERTOR_EP2_XSLPATH_CORE");_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_CORE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP2_XSLPATH_POST");_x000D_
} else _x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EMBELLISH_FILE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP_XSLPATH");_x000D_
_x000D_
_x000D_
// if this succeeds, copy the EP schema to the app and validate_x000D_
if (succeeds) {_x000D_
AnyFolder workAppFolder = new AnyFolder(Configurator.getInstance().getXParm("system/work-app-folder-path"));_x000D_
_x000D_
XmlFile resultEpFile = new XmlFile(configurator.getXParm("properties/WORK_EP_XMLPATH_FINAL"));_x000D_
XmlFile targetEpFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/ep.xml"); // TODO nette naam, bepaald door gebruiker oid._x000D_
resultEpFile.copyFile(targetEpFile);_x000D_
_x000D_
XmlFile managedSchemaFile = new XmlFile(Configurator.getInstance().getBaseFolder().getCanonicalPath() + "/etc/xsd/EP/" + epSchema);_x000D_
XmlFile targetSchemaFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/xsd/" + epSchema);_x000D_
managedSchemaFile.copyFile(targetSchemaFile);_x000D_
_x000D_
// Debug: test if EP is okay_x000D_
succeeds = succeeds && resultEpFile.isValid();_x000D_
}_x000D_
configurator.setXParm("system/ep-schema-created",succeeds);_x000D_
configurator.setXParm("system/ep-schema-version",requiresMIM() ? "2" : "1"); // when MIM based, generated EP version 2_x000D_
_x000D_
return succeeds;_x000D_
}_x000D_
_x000D_
public static Boolean requiresMIM() throws IOException, ConfiguratorException {_x000D_
// bepaal of hier de MIM schema variant moet worden gebruikt_x000D_
String jsonschemasource = Configurator.getInstance().getXParm("cli/jsonschemasource",false);_x000D_
return (jsonschemasource == null || jsonschemasource.equals("MIM"));_x000D_
} _x000D_
_x000D_
}_x000D_
| false | 1,942 | 18 | 2,171 | 19 | 2,183 | 14 | 2,171 | 19 | 2,475 | 19 | false | false | false | false | false | true |
1,852 | 44930_0 | package org.imec.ivlab.core.kmehr.model;
import java.io.Serializable;
import java.util.Objects;
public enum FrequencyCode implements Serializable {
UH("UH", Frequency.HOUR, 0.5, "Om het half uur", true),
U("U", Frequency.HOUR, 1, "Om het uur", true),
UT("UT", Frequency.HOUR, 2, "Om de twee uren", true),
UD("UD", Frequency.HOUR, 3, "Om de 3 uren", true),
UV("UV", Frequency.HOUR, 4, "om de 4 uren", true),
UQ("UQ", Frequency.HOUR, 5, "om de 5 uren", true), // niet toegelaten in medicatieschema
UZ("UZ", Frequency.HOUR, 6, "om de 6 uren", true),
US("US", Frequency.HOUR, 7, "om de 7 uren", true), // niet toegelaten in medicatieschema
UA("UA", Frequency.HOUR, 8, "om de 8 uren", true),
UN("UN", Frequency.HOUR, 9, "om de 9 uren", true), // niet toegelaten in medicatieschema
UX("UX", Frequency.HOUR, 10, "om de 10 uren", true),// niet toegelaten in medicatieschema
UE("UE", Frequency.HOUR, 11, "om de 11 uren", true),// niet toegelaten in medicatieschema
UW("UW", Frequency.HOUR, 12, "om de 12 uren", true),
D("D", Frequency.DAY, 1, "Dagelijks", true),
O1("O1", Frequency.DAY, 2, "Om de 2 dagen", true), // TODO: uit te klaren. Volgens kmehr: om de dag, volgens medicatie schema cookbook om de 2 dagen
DT("DT", Frequency.DAY, 2, "om de 2 dagen", true),
DD("DD", Frequency.DAY, 3, "Om de 3 dagen", true),
DV("DV", Frequency.DAY, 4, "Om de 4 dagen", true),
DQ("DQ", Frequency.DAY, 5, "Om de 5 dagen", true),
DZ("DZ", Frequency.DAY, 6, "Om de 6 dagen", true),
DA("DA", Frequency.DAY, 8, "Om de 8 dagen", true),
DN("DN", Frequency.DAY, 9, "Om de 9 dagen", true),
DX("DX", Frequency.DAY, 10, "Om de 10 dagen", true),
DE("DE", Frequency.DAY, 11, "Om de 11 dagen", true),
DW("DW", Frequency.DAY, 12, "Om de 12 dagen", true),
W("W", Frequency.WEEK, 1, "Wekelijks", true),
WT("WT", Frequency.WEEK, 2, "Om de 2 weken", true),
WD("WD", Frequency.WEEK, 3, "Om de 3 weken", true),
WV("WV", Frequency.WEEK, 4, "Om de 4 weken", true),
WQ("WQ", Frequency.WEEK, 5, "Om de 5 weken", true),
WZ("WZ", Frequency.WEEK, 6, "Om de 6 weken", true),
WS("WS", Frequency.WEEK, 7, "Om de 7 weken", true),
WA("WA", Frequency.WEEK, 8, "Om de 8 weken", true),
WN("WN", Frequency.WEEK, 9, "Om de 9 weken", true),
WX("WX", Frequency.WEEK, 10, "Om de 10 weken", true),
WE("WE", Frequency.WEEK, 11, "Om de 11 weken", true),
WW("WW", Frequency.WEEK, 12, "Om de 12 weken", true),
WP("WP", Frequency.WEEK, 24, "Om de 24 weken", true),
M("M", Frequency.MONTH, 1, "Maandelijks", true),
MT("MT", Frequency.MONTH, 2, "Om de 2 maanden", true),
MD("MD", Frequency.MONTH, 3, "Om de 3 maanden", true),
MV("MV", Frequency.MONTH, 4, "Om de 4 maanden", true),
MQ("MQ", Frequency.MONTH, 5, "Om de 5 maanden", true),
MZ2("MZ2", Frequency.MONTH, 6, "Om de 6 maanden", true),
MS("MS", Frequency.MONTH, 7, "Om de 7 maanden", true),
MA("MA", Frequency.MONTH, 8, "Om de 8 maanden", true),
MN("MN", Frequency.MONTH, 9, "Om de 9 maanden", true),
MX("MX", Frequency.MONTH, 10, "Om de 10 maanden", true),
ME("ME", Frequency.MONTH, 11, "Om de 11 maanden", true),
MC("MC", Frequency.MONTH, 18, "Om de 18 maanden", true),
JH2("JH2", Frequency.MONTH, 6, "Halfjaarlijks", true), // YEAR, 0.5 in specs
J("J", Frequency.YEAR, 1, "Jaarlijks", true),
JT("JT", Frequency.YEAR, 2, "Om de 2 jaar", true),
JD("JD", Frequency.YEAR, 3, "Om de 3 jaar", true),
JV("JV", Frequency.YEAR, 4, "Om de 4 jaar", true),
JQ("JQ", Frequency.YEAR, 5, "Om de 5 jaar", true),
JZ("JZ", Frequency.YEAR, 6, "Om de 6 jaar", true),
ONDEMAND("ondemand", null, 0, "Op aanvraag", false);
private Frequency frequency;
private Double multiplier;
private String translation;
private boolean supportedByVitalink;
private String value;
FrequencyCode(String value, Frequency frequency, int multiplier, String translation, boolean supportedByVitalink) {
this(value, frequency, Double.valueOf(multiplier), translation, supportedByVitalink);
}
FrequencyCode(String value, Frequency frequency, Double multiplier, String translation, boolean supportedByVitalink) {
this.value = value;
this.frequency = frequency;
this.multiplier = multiplier;
this.translation = translation;
this.supportedByVitalink = supportedByVitalink;
}
public Double getMultiplier() {
return multiplier;
}
public Frequency getFrequency() {
return frequency;
}
public String getTranslation() {
return translation;
}
public boolean hasFrequency(Frequency frequency) {
return Objects.equals(this.frequency, frequency);
}
public boolean isSupportedByVitalink() {
return supportedByVitalink;
}
public static FrequencyCode fromValue(String input) {
for (FrequencyCode frequencyCode : values()) {
if (frequencyCode.value.equalsIgnoreCase(input)) {
return frequencyCode;
}
}
throw new IllegalArgumentException("Invalid frequencycode value: " + input);
}
public String getValue() {
return value;
}
} | Vitalink/evs | core/src/main/java/org/imec/ivlab/core/kmehr/model/FrequencyCode.java | 2,026 | // niet toegelaten in medicatieschema | line_comment | nl | package org.imec.ivlab.core.kmehr.model;
import java.io.Serializable;
import java.util.Objects;
public enum FrequencyCode implements Serializable {
UH("UH", Frequency.HOUR, 0.5, "Om het half uur", true),
U("U", Frequency.HOUR, 1, "Om het uur", true),
UT("UT", Frequency.HOUR, 2, "Om de twee uren", true),
UD("UD", Frequency.HOUR, 3, "Om de 3 uren", true),
UV("UV", Frequency.HOUR, 4, "om de 4 uren", true),
UQ("UQ", Frequency.HOUR, 5, "om de 5 uren", true), // niet toegelaten<SUF>
UZ("UZ", Frequency.HOUR, 6, "om de 6 uren", true),
US("US", Frequency.HOUR, 7, "om de 7 uren", true), // niet toegelaten in medicatieschema
UA("UA", Frequency.HOUR, 8, "om de 8 uren", true),
UN("UN", Frequency.HOUR, 9, "om de 9 uren", true), // niet toegelaten in medicatieschema
UX("UX", Frequency.HOUR, 10, "om de 10 uren", true),// niet toegelaten in medicatieschema
UE("UE", Frequency.HOUR, 11, "om de 11 uren", true),// niet toegelaten in medicatieschema
UW("UW", Frequency.HOUR, 12, "om de 12 uren", true),
D("D", Frequency.DAY, 1, "Dagelijks", true),
O1("O1", Frequency.DAY, 2, "Om de 2 dagen", true), // TODO: uit te klaren. Volgens kmehr: om de dag, volgens medicatie schema cookbook om de 2 dagen
DT("DT", Frequency.DAY, 2, "om de 2 dagen", true),
DD("DD", Frequency.DAY, 3, "Om de 3 dagen", true),
DV("DV", Frequency.DAY, 4, "Om de 4 dagen", true),
DQ("DQ", Frequency.DAY, 5, "Om de 5 dagen", true),
DZ("DZ", Frequency.DAY, 6, "Om de 6 dagen", true),
DA("DA", Frequency.DAY, 8, "Om de 8 dagen", true),
DN("DN", Frequency.DAY, 9, "Om de 9 dagen", true),
DX("DX", Frequency.DAY, 10, "Om de 10 dagen", true),
DE("DE", Frequency.DAY, 11, "Om de 11 dagen", true),
DW("DW", Frequency.DAY, 12, "Om de 12 dagen", true),
W("W", Frequency.WEEK, 1, "Wekelijks", true),
WT("WT", Frequency.WEEK, 2, "Om de 2 weken", true),
WD("WD", Frequency.WEEK, 3, "Om de 3 weken", true),
WV("WV", Frequency.WEEK, 4, "Om de 4 weken", true),
WQ("WQ", Frequency.WEEK, 5, "Om de 5 weken", true),
WZ("WZ", Frequency.WEEK, 6, "Om de 6 weken", true),
WS("WS", Frequency.WEEK, 7, "Om de 7 weken", true),
WA("WA", Frequency.WEEK, 8, "Om de 8 weken", true),
WN("WN", Frequency.WEEK, 9, "Om de 9 weken", true),
WX("WX", Frequency.WEEK, 10, "Om de 10 weken", true),
WE("WE", Frequency.WEEK, 11, "Om de 11 weken", true),
WW("WW", Frequency.WEEK, 12, "Om de 12 weken", true),
WP("WP", Frequency.WEEK, 24, "Om de 24 weken", true),
M("M", Frequency.MONTH, 1, "Maandelijks", true),
MT("MT", Frequency.MONTH, 2, "Om de 2 maanden", true),
MD("MD", Frequency.MONTH, 3, "Om de 3 maanden", true),
MV("MV", Frequency.MONTH, 4, "Om de 4 maanden", true),
MQ("MQ", Frequency.MONTH, 5, "Om de 5 maanden", true),
MZ2("MZ2", Frequency.MONTH, 6, "Om de 6 maanden", true),
MS("MS", Frequency.MONTH, 7, "Om de 7 maanden", true),
MA("MA", Frequency.MONTH, 8, "Om de 8 maanden", true),
MN("MN", Frequency.MONTH, 9, "Om de 9 maanden", true),
MX("MX", Frequency.MONTH, 10, "Om de 10 maanden", true),
ME("ME", Frequency.MONTH, 11, "Om de 11 maanden", true),
MC("MC", Frequency.MONTH, 18, "Om de 18 maanden", true),
JH2("JH2", Frequency.MONTH, 6, "Halfjaarlijks", true), // YEAR, 0.5 in specs
J("J", Frequency.YEAR, 1, "Jaarlijks", true),
JT("JT", Frequency.YEAR, 2, "Om de 2 jaar", true),
JD("JD", Frequency.YEAR, 3, "Om de 3 jaar", true),
JV("JV", Frequency.YEAR, 4, "Om de 4 jaar", true),
JQ("JQ", Frequency.YEAR, 5, "Om de 5 jaar", true),
JZ("JZ", Frequency.YEAR, 6, "Om de 6 jaar", true),
ONDEMAND("ondemand", null, 0, "Op aanvraag", false);
private Frequency frequency;
private Double multiplier;
private String translation;
private boolean supportedByVitalink;
private String value;
FrequencyCode(String value, Frequency frequency, int multiplier, String translation, boolean supportedByVitalink) {
this(value, frequency, Double.valueOf(multiplier), translation, supportedByVitalink);
}
FrequencyCode(String value, Frequency frequency, Double multiplier, String translation, boolean supportedByVitalink) {
this.value = value;
this.frequency = frequency;
this.multiplier = multiplier;
this.translation = translation;
this.supportedByVitalink = supportedByVitalink;
}
public Double getMultiplier() {
return multiplier;
}
public Frequency getFrequency() {
return frequency;
}
public String getTranslation() {
return translation;
}
public boolean hasFrequency(Frequency frequency) {
return Objects.equals(this.frequency, frequency);
}
public boolean isSupportedByVitalink() {
return supportedByVitalink;
}
public static FrequencyCode fromValue(String input) {
for (FrequencyCode frequencyCode : values()) {
if (frequencyCode.value.equalsIgnoreCase(input)) {
return frequencyCode;
}
}
throw new IllegalArgumentException("Invalid frequencycode value: " + input);
}
public String getValue() {
return value;
}
} | false | 1,678 | 11 | 1,779 | 11 | 1,754 | 9 | 1,779 | 11 | 2,075 | 11 | false | false | false | false | false | true |
19 | 132832_0 | package Shipflex;
import Boat.Boat;
import Boat.Option;
import Customer.CustomCustomer;
import Customer.BusinessCustomer;
import Customer.FoundationCustomer;
import Customer.GovermentCustomer;
import DataInOut.Info;
import DataInOut.Printer;
import java.util.ArrayList;
import java.util.List;
public class Quote {
private Company companyShipbuild;
private CustomCustomer customCustomer;
private BusinessCustomer businessCustomer;
private GovermentCustomer govermentCustomer;
private FoundationCustomer foundationCustomer;
private String date;
private String quoteDate;
private String about;
private double workHoursCost;
private Boat boat;
public Quote(Company companyShipbuild, Boat boat) {
this.companyShipbuild = companyShipbuild;
this.businessCustomer = null;
this.customCustomer = null;
this.govermentCustomer = null;
this.foundationCustomer = null;
this.boat = boat;
}
public void setCustomCustomer(CustomCustomer customCustomer) {
this.customCustomer = customCustomer;
}
public void setBusinessCustomer(BusinessCustomer businessCustomer) {
this.businessCustomer = businessCustomer;
}
public void setGovermentCustomer(GovermentCustomer govermentCustomer) {
this.govermentCustomer = govermentCustomer;
}
public void setFoundationCustomer(FoundationCustomer foundationCustomer) {
this.foundationCustomer = foundationCustomer;
}
public void setAbout(String about) {
this.about = about;
}
public void setDate(String date) {
this.date = date;
}
public void setQuoteDate(String quoteDate) {
this.quoteDate = quoteDate;
}
public void setBoat(Boat boat) {
this.boat = boat;
}
public Boat getBoat() {
return boat;
}
public CustomCustomer getCustomCustomer() {
return customCustomer;
}
public BusinessCustomer getBusinessCustomer() {
return businessCustomer;
}
public GovermentCustomer getGovermentCustomer() {
return govermentCustomer;
}
public FoundationCustomer getFoundationCustomer() {
return foundationCustomer;
}
public void setWorkHoursCost(double workHoursCost) {
this.workHoursCost = workHoursCost;
}
public void printCustomer() {
switch (checkCustomerType()) {
case "goverment":
govermentCustomer.printCustomer();
break;
case "business":
businessCustomer.printCustomer();
break;
case "foundation":
foundationCustomer.printCustomer();
break;
case "customer":
customCustomer.printCustomer();
break;
default:
Printer.getInstance().printLine("Nog geen klant toegevoegd");
break;
}
}
private String checkCustomerType() {
if (govermentCustomer != null) {
return "goverment";
} else if (businessCustomer != null) {
return "business";
} else if (customCustomer != null) {
return "customer";
} else if (foundationCustomer != null) {
return "foundation";
} else {
return "";
}
}
public void printOptions(boolean showIndex) {
for (Option option : this.boat.getOptions()) {
if (showIndex)
Info.printOptionInfo(option, Info.getOptions().indexOf(option));
else
Info.printOptionInfo(option, -1);
Printer.getInstance().emptyLine();
}
}
public void printDate() {
if (this.date != null && !this.date.equals("")) {
Printer.getInstance().printLine("Datum: " + this.date);
} else {
Printer.getInstance().printLine("Datum nog niet ingevuld");
}
if (this.quoteDate != null && !this.quoteDate.equals("")) {
Printer.getInstance().printLine("Geldigsheid datum: " + this.quoteDate);
} else {
Printer.getInstance().printLine("Geldigsheid datum nog niet ingevuld");
}
}
public void printBasicInformation() {
companyShipbuild.printCompany();
Printer.getInstance().emptyLine();
printCustomer();
Printer.getInstance().emptyLine();
printDate();
Printer.getInstance().emptyLine();
if(this.about != null && !this.about.equals("")) {
Printer.getInstance().printLine("Betreft: " + this.about);
}else {
Printer.getInstance().printLine("Betreft is nog niet ingevuld");
}
Printer.getInstance().emptyLine();
}
public void printQuote() {
Printer.getInstance().printCharacters(129, '━');
Printer.getInstance().emptyLine();
this.printBasicInformation();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
boat.printBoat();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
this.printOptions();
Printer.getInstance().emptyLine();
this.printTotal();
Printer.getInstance().emptyLine();
Printer.getInstance().printCharacters(129, '━');
}
public void printOptions() {
List<Option> essentialOptions = new ArrayList<>();
List<Option> extraOptions = new ArrayList<>();
for (Option option : boat.getOptions()) {
if (option.getEssentialForBoatType().contains(boat.getType().toLowerCase()))
essentialOptions.add(option);
else
extraOptions.add(option);
}
printOptionsListFormatted(essentialOptions);
printOptionsListFormatted(extraOptions);
}
private void printOptionsListFormatted(List<Option> options) {
for (Option option : options) {
option.printOptionInfoForBoat(boat.getType());
}
}
public int getDiscount() {
int discount = 0;
switch (checkCustomerType()) {
case "goverment":
discount = govermentCustomer.getDiscount();
break;
case "business":
discount = businessCustomer.getDiscount();
break;
case "foundation":
discount = foundationCustomer.getDiscount();
break;
case "customer":
discount = customCustomer.getDiscount();
break;
}
return 100 - discount;
}
public double calculatePercentage(int percentage, double price) {
return (price / 100) * percentage;
}
public double calculateBoatPrice() {
double price = 0;
price += boat.getBasePrice();
for (Option option : boat.getOptions()) {
price += option.getPrice();
}
return price;
}
public void printTotal() {
Printer.getInstance().emptyLine();
//Totaal prijs boot
double totalPriceBoat = calculateBoatPrice();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaal prijs boot met korting
if (getDiscount() < 100 && getDiscount() > 0) {
totalPriceBoat = calculatePercentage(getDiscount(), totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot met korting:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
}
//prijs arbeids uren
Printer.getInstance().emptyLine();
double workCost = workHoursCost;
Printer.getInstance().printFormatInfo("Prijs arbeids uren:");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
Printer.getInstance().emptyLine();
//prijs arbeids uren incl
workCost = calculatePercentage(109, workCost);
Printer.getInstance().printFormatInfo(String.format("Prijs arbeids uren incl. Btw(9%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
//Totaal prijs boot incl btw
totalPriceBoat = calculatePercentage(121, totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot incl. Btw(21%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaalprijs offerte
totalPriceBoat += workHoursCost;
Printer.getInstance().printSpaces(128);
Printer.getInstance().printCharacters(1,'+');
Printer.getInstance().emptyLine();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs offerte:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
}
} | 22082476/PROJ1-Milkshake | src/Shipflex/Quote.java | 2,681 | //Totaal prijs boot | line_comment | nl | package Shipflex;
import Boat.Boat;
import Boat.Option;
import Customer.CustomCustomer;
import Customer.BusinessCustomer;
import Customer.FoundationCustomer;
import Customer.GovermentCustomer;
import DataInOut.Info;
import DataInOut.Printer;
import java.util.ArrayList;
import java.util.List;
public class Quote {
private Company companyShipbuild;
private CustomCustomer customCustomer;
private BusinessCustomer businessCustomer;
private GovermentCustomer govermentCustomer;
private FoundationCustomer foundationCustomer;
private String date;
private String quoteDate;
private String about;
private double workHoursCost;
private Boat boat;
public Quote(Company companyShipbuild, Boat boat) {
this.companyShipbuild = companyShipbuild;
this.businessCustomer = null;
this.customCustomer = null;
this.govermentCustomer = null;
this.foundationCustomer = null;
this.boat = boat;
}
public void setCustomCustomer(CustomCustomer customCustomer) {
this.customCustomer = customCustomer;
}
public void setBusinessCustomer(BusinessCustomer businessCustomer) {
this.businessCustomer = businessCustomer;
}
public void setGovermentCustomer(GovermentCustomer govermentCustomer) {
this.govermentCustomer = govermentCustomer;
}
public void setFoundationCustomer(FoundationCustomer foundationCustomer) {
this.foundationCustomer = foundationCustomer;
}
public void setAbout(String about) {
this.about = about;
}
public void setDate(String date) {
this.date = date;
}
public void setQuoteDate(String quoteDate) {
this.quoteDate = quoteDate;
}
public void setBoat(Boat boat) {
this.boat = boat;
}
public Boat getBoat() {
return boat;
}
public CustomCustomer getCustomCustomer() {
return customCustomer;
}
public BusinessCustomer getBusinessCustomer() {
return businessCustomer;
}
public GovermentCustomer getGovermentCustomer() {
return govermentCustomer;
}
public FoundationCustomer getFoundationCustomer() {
return foundationCustomer;
}
public void setWorkHoursCost(double workHoursCost) {
this.workHoursCost = workHoursCost;
}
public void printCustomer() {
switch (checkCustomerType()) {
case "goverment":
govermentCustomer.printCustomer();
break;
case "business":
businessCustomer.printCustomer();
break;
case "foundation":
foundationCustomer.printCustomer();
break;
case "customer":
customCustomer.printCustomer();
break;
default:
Printer.getInstance().printLine("Nog geen klant toegevoegd");
break;
}
}
private String checkCustomerType() {
if (govermentCustomer != null) {
return "goverment";
} else if (businessCustomer != null) {
return "business";
} else if (customCustomer != null) {
return "customer";
} else if (foundationCustomer != null) {
return "foundation";
} else {
return "";
}
}
public void printOptions(boolean showIndex) {
for (Option option : this.boat.getOptions()) {
if (showIndex)
Info.printOptionInfo(option, Info.getOptions().indexOf(option));
else
Info.printOptionInfo(option, -1);
Printer.getInstance().emptyLine();
}
}
public void printDate() {
if (this.date != null && !this.date.equals("")) {
Printer.getInstance().printLine("Datum: " + this.date);
} else {
Printer.getInstance().printLine("Datum nog niet ingevuld");
}
if (this.quoteDate != null && !this.quoteDate.equals("")) {
Printer.getInstance().printLine("Geldigsheid datum: " + this.quoteDate);
} else {
Printer.getInstance().printLine("Geldigsheid datum nog niet ingevuld");
}
}
public void printBasicInformation() {
companyShipbuild.printCompany();
Printer.getInstance().emptyLine();
printCustomer();
Printer.getInstance().emptyLine();
printDate();
Printer.getInstance().emptyLine();
if(this.about != null && !this.about.equals("")) {
Printer.getInstance().printLine("Betreft: " + this.about);
}else {
Printer.getInstance().printLine("Betreft is nog niet ingevuld");
}
Printer.getInstance().emptyLine();
}
public void printQuote() {
Printer.getInstance().printCharacters(129, '━');
Printer.getInstance().emptyLine();
this.printBasicInformation();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
boat.printBoat();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
this.printOptions();
Printer.getInstance().emptyLine();
this.printTotal();
Printer.getInstance().emptyLine();
Printer.getInstance().printCharacters(129, '━');
}
public void printOptions() {
List<Option> essentialOptions = new ArrayList<>();
List<Option> extraOptions = new ArrayList<>();
for (Option option : boat.getOptions()) {
if (option.getEssentialForBoatType().contains(boat.getType().toLowerCase()))
essentialOptions.add(option);
else
extraOptions.add(option);
}
printOptionsListFormatted(essentialOptions);
printOptionsListFormatted(extraOptions);
}
private void printOptionsListFormatted(List<Option> options) {
for (Option option : options) {
option.printOptionInfoForBoat(boat.getType());
}
}
public int getDiscount() {
int discount = 0;
switch (checkCustomerType()) {
case "goverment":
discount = govermentCustomer.getDiscount();
break;
case "business":
discount = businessCustomer.getDiscount();
break;
case "foundation":
discount = foundationCustomer.getDiscount();
break;
case "customer":
discount = customCustomer.getDiscount();
break;
}
return 100 - discount;
}
public double calculatePercentage(int percentage, double price) {
return (price / 100) * percentage;
}
public double calculateBoatPrice() {
double price = 0;
price += boat.getBasePrice();
for (Option option : boat.getOptions()) {
price += option.getPrice();
}
return price;
}
public void printTotal() {
Printer.getInstance().emptyLine();
//Totaal prijs<SUF>
double totalPriceBoat = calculateBoatPrice();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaal prijs boot met korting
if (getDiscount() < 100 && getDiscount() > 0) {
totalPriceBoat = calculatePercentage(getDiscount(), totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot met korting:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
}
//prijs arbeids uren
Printer.getInstance().emptyLine();
double workCost = workHoursCost;
Printer.getInstance().printFormatInfo("Prijs arbeids uren:");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
Printer.getInstance().emptyLine();
//prijs arbeids uren incl
workCost = calculatePercentage(109, workCost);
Printer.getInstance().printFormatInfo(String.format("Prijs arbeids uren incl. Btw(9%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
//Totaal prijs boot incl btw
totalPriceBoat = calculatePercentage(121, totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot incl. Btw(21%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaalprijs offerte
totalPriceBoat += workHoursCost;
Printer.getInstance().printSpaces(128);
Printer.getInstance().printCharacters(1,'+');
Printer.getInstance().emptyLine();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs offerte:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
}
} | false | 1,944 | 7 | 2,150 | 7 | 2,269 | 5 | 2,150 | 7 | 2,579 | 7 | false | false | false | false | false | true |
4,579 | 169859_1 | /**
*
* Copyright 2012-2017 TNO Geologische Dienst Nederland
*
* Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
* the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*
* This work was sponsored by the Dutch Rijksoverheid, Basisregistratie
* Ondergrond (BRO) Programme (https://bro.pleio.nl/)
*/
package nl.bro.cpt.gef.main;
import static org.fest.assertions.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LogRecord;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import nl.bro.cpt.gef.main.util.TestHandler;
public class ConverGefTest {
@Before
public void init() {
TestHandler.LOG_RECORDS.clear();
}
@After
public void cleanup() {
TestHandler.LOG_RECORDS.clear();
}
private List<String> getMessages() {
List<String> messages = new ArrayList<>();
for ( LogRecord record : TestHandler.LOG_RECORDS ) {
messages.add( record.getMessage() );
}
return messages;
}
@Test
public void testNoArguments() {
// -- action
ConvertGef.main( new String[0] );
// -- verify
List<String> messages = getMessages();
assertThat( messages ).contains( "Missing t option", "Missing r option", "Missing q option" );
}
@Test
public void testNonExistingFile() {
ConvertGef.main( new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "TEST.GEF" } );
List<String> messages = getMessages();
assertThat( messages.toString() ).contains( "kan niet gevonden worden" );
}
/**
* Ignore tot dat filenaam probleem is opgelost
*/
@Test
@Ignore
public void testNormal() {
ConvertGef.main(
new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "-d", "target", "src/test/resources/CPT-F3b-i3-23913-completion-CPT.GEF",
"src/test/resources/CPT-F3b-i3-23913-completion-DISS.GEF" } );
}
}
| tvcstseng/CPT_GEF_CONVERTER | gef_standalone/src/test/java/nl/bro/cpt/gef/main/ConverGefTest.java | 795 | /**
* Ignore tot dat filenaam probleem is opgelost
*/ | block_comment | nl | /**
*
* Copyright 2012-2017 TNO Geologische Dienst Nederland
*
* Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
* the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*
* This work was sponsored by the Dutch Rijksoverheid, Basisregistratie
* Ondergrond (BRO) Programme (https://bro.pleio.nl/)
*/
package nl.bro.cpt.gef.main;
import static org.fest.assertions.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LogRecord;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import nl.bro.cpt.gef.main.util.TestHandler;
public class ConverGefTest {
@Before
public void init() {
TestHandler.LOG_RECORDS.clear();
}
@After
public void cleanup() {
TestHandler.LOG_RECORDS.clear();
}
private List<String> getMessages() {
List<String> messages = new ArrayList<>();
for ( LogRecord record : TestHandler.LOG_RECORDS ) {
messages.add( record.getMessage() );
}
return messages;
}
@Test
public void testNoArguments() {
// -- action
ConvertGef.main( new String[0] );
// -- verify
List<String> messages = getMessages();
assertThat( messages ).contains( "Missing t option", "Missing r option", "Missing q option" );
}
@Test
public void testNonExistingFile() {
ConvertGef.main( new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "TEST.GEF" } );
List<String> messages = getMessages();
assertThat( messages.toString() ).contains( "kan niet gevonden worden" );
}
/**
* Ignore tot dat<SUF>*/
@Test
@Ignore
public void testNormal() {
ConvertGef.main(
new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "-d", "target", "src/test/resources/CPT-F3b-i3-23913-completion-CPT.GEF",
"src/test/resources/CPT-F3b-i3-23913-completion-DISS.GEF" } );
}
}
| false | 642 | 18 | 739 | 17 | 734 | 17 | 739 | 17 | 823 | 20 | false | false | false | false | false | true |
4,417 | 151743_47 | package BomberButtiClient;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
/**
*The class Bomber Player includes all data from the player
* Which player has its own object of this class
*/
public class BomberPlayer {
BomberMap map;
BomberGame game;
int id; //Each player has a unique ID
int x;
int y;
boolean isDead; //True if player is dead
int speed; //Indication of speed at which the character can move on the playing field
int totalBombs; //Total number of trees that the player can simultaneously
int bombStrike; //Scope of the bows of the bombs that explains this player
int usedBombs; //Number of bombs that the player has used
int direction; //Direction in which the player moves on the field (to be performed at this.act ()
boolean dropBomb; //True if player wants to lay a bomb (performed at this.act ())
ArrayList<Bomb> bombs = new ArrayList<>(); //tracking the bombs laid by this player
String name; //The username of this player
int[] keys;
private static final int DIR_UP = 1;
private static final int DIR_DOWN = 2;
private static final int DIR_LEFT = 3;
private static final int DIR_RIGHT = 4;
private static final int UP = 0;
private static final int DOWN = 1;
private static final int LEFT = 2;
private static final int RIGHT = 3;
private static final int BOMB = 4;
/**
* Default constructor
*/
public BomberPlayer() {
keys = new int[5];
id = 0;
x = 0;
y = 0;
isDead = false;
speed = 1;
totalBombs = 1;
bombStrike = 0;
usedBombs = 0;
direction = 0;
dropBomb = false;
name = "Unknown player";
}
/**
* Constructor
* @param game
* @param map
* @param id
* @param x
* @param y
*/
public BomberPlayer(BomberGame game, BomberMap map, int id, int x, int y, String name) {
this();
this.game = game;
this.map = map;
this.id = id;
this.x = x;
this.y = y;
this.name = name;
}
/**
* Control Keys pick for this player from the keyconfig class
*/
public void loadKeys() {
KeyConfig kC = new KeyConfig();
keys[UP] = kC.keys[id-1][UP];
keys[DOWN] = kC.keys[id-1][DOWN];
keys[LEFT] = kC.keys[id-1][LEFT];
keys[RIGHT] = kC.keys[id-1][RIGHT];
keys[BOMB] = kC.keys[id-1][BOMB];
}
/**
* @return
*/
public BomberMap getMap() {
return this.map;
}
/**
* @return
*/
public BomberGame getGame() {
return this.game;
}
/**
* @return
*/
public int getId() {
return this.id;
}
/**
* @return
*/
public int getX() {
return this.x;
}
/**
* @return
*/
public int getY() {
return this.y;
}
/**
* @return
*/
public Coord getCoords() {
return new Coord(this.x,this.y);
}
/**
* @return
*/
public boolean getIsDead() {
return this.isDead;
}
/**
* @return
*/
public int getSpeed() {
return this.speed;
}
/**
* @return
*/
public int getTotalBombs() {
return this.totalBombs;
}
/**
* @return
*/
public int getBombStrike() {
return this.bombStrike;
}
/**
* @return
*/
public int getUsedBombs() {
return this.usedBombs;
}
/**
* Get function for the ArrayList of the bombs laid by this player
* @return
*/
public ArrayList<Bomb> getBombs() {
return this.bombs;
}
/**
* @return
*/
public String getName() {
return this.name;
}
/**
* Set functions; So that external classes can set the variables of these classes
*/
public void setMap(BomberMap map) {
this.map = map;
}
public void setGame(BomberGame game) {
this.game = game;
}
public void setId(int id) {
this.id = id;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setIsDead(boolean isDead) {
this.isDead = isDead;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setTotalBombs(int totalBombs) {
this.totalBombs = totalBombs;
}
public void setBombStrike(int bombStrike) {
this.bombStrike = bombStrike;
}
public void setUsedBombs(int usedBombs) {
this.usedBombs = usedBombs;
}
public void setDirection(int direction) {
this.direction = direction;
}
public void setDropBomb(boolean dropBomb) {
this.dropBomb = dropBomb;
}
public void setBombs(ArrayList<Bomb> bombs) {
this.bombs = bombs;
}
/**
* Semi-set functions
*/
public void incSpeed(int a) {
speed = speed+a;
}
public void decSpeed(int a) {
speed = speed-a;
}
public void incTotalBombs(int a) {
totalBombs = totalBombs+a;
}
public void decTotalBombs(int a) {
totalBombs = totalBombs-a;
}
public void incBombStrike(int a) {
bombStrike = bombStrike+a;
}
public void decBombStrike(int a) {
bombStrike = bombStrike-a;
}
/**
* Is performed by pressing a button
* @param evt: Contains information key pressed
*/
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == keys[UP]) {
this.direction = DIR_UP;
}
else if (evt.getKeyCode() == keys[DOWN]) {
this.direction = DIR_DOWN;
}
else if (evt.getKeyCode() == keys[LEFT]) {
this.direction = DIR_LEFT;
}
else if (evt.getKeyCode() == keys[RIGHT]) {
this.direction = DIR_RIGHT;
}
else if (evt.getKeyCode() == keys[BOMB]) {
dropBomb = true;
}
}
/**
* Is performed at the release of a key
* @param evt: Contains information about the release button
*/
public void keyReleased(KeyEvent evt) {
if ((evt.getKeyCode() == keys[UP]) && (direction == DIR_UP)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[DOWN]) && (direction == DIR_DOWN)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[LEFT]) && (direction == DIR_LEFT)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[RIGHT]) && (direction == DIR_RIGHT)) {
direction = 0;
}
}
/**
* Players will be 'killed'
*/
public void kill() {
this.isDead = true;
}
/**
* Is performed at each "pulse timer", from here everything is performed every
*/
public void act() {
//Loop all the bombs laid by the player to remove the unexploded bombs from the list
for (Iterator i = bombs.listIterator(); i.hasNext();) {
Bomb b = (Bomb) i.next(); //Current 'bomb' in the course
if (b.isExploded()) {
i.remove();
}
}
Coord c = new Coord(x,y);
if (map.isStrike(c)) {
this.kill();
game.endGame();
}
else {
map.checkBonus(this);
if (dropBomb) {
if (bombs.size() < totalBombs) {
Bomb b = new Bomb(this,x,y);
bombs.add(b);
map.createBomb(b);
usedBombs++;
}
}
dropBomb = false;
//Control or player wants to move
switch(direction) {
case DIR_UP: //Players will move upwards
c.decY(); //Current coordinate one box up
if (!map.isObstacle(c)) {
this.y--;
} //n-> Move Up
break;
case DIR_DOWN: //Player wants to move downwardly
c.incY(); //Current coordinate 1 box down
if (!map.isObstacle(c)) {
this.y++;
} //n-> Move Down
break;
case DIR_LEFT: //Players will move to the left
c.decX(); //Current coordinate one box to the left
if (!map.isObstacle(c)) {
this.x--;
} //n-> move left
break;
case DIR_RIGHT: //Players will move to the right
c.incX(); //Current coordinate one box to the right
if (!map.isObstacle(c)) {
this.x++;
} //n->naar rechts verlaatsen
break;
default: //Player does not want to move -> nothing
}
}
}
}
| surdarmaputra/bomberman | BomberPlayer.java | 2,953 | //n->naar rechts verlaatsen | line_comment | nl | package BomberButtiClient;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
/**
*The class Bomber Player includes all data from the player
* Which player has its own object of this class
*/
public class BomberPlayer {
BomberMap map;
BomberGame game;
int id; //Each player has a unique ID
int x;
int y;
boolean isDead; //True if player is dead
int speed; //Indication of speed at which the character can move on the playing field
int totalBombs; //Total number of trees that the player can simultaneously
int bombStrike; //Scope of the bows of the bombs that explains this player
int usedBombs; //Number of bombs that the player has used
int direction; //Direction in which the player moves on the field (to be performed at this.act ()
boolean dropBomb; //True if player wants to lay a bomb (performed at this.act ())
ArrayList<Bomb> bombs = new ArrayList<>(); //tracking the bombs laid by this player
String name; //The username of this player
int[] keys;
private static final int DIR_UP = 1;
private static final int DIR_DOWN = 2;
private static final int DIR_LEFT = 3;
private static final int DIR_RIGHT = 4;
private static final int UP = 0;
private static final int DOWN = 1;
private static final int LEFT = 2;
private static final int RIGHT = 3;
private static final int BOMB = 4;
/**
* Default constructor
*/
public BomberPlayer() {
keys = new int[5];
id = 0;
x = 0;
y = 0;
isDead = false;
speed = 1;
totalBombs = 1;
bombStrike = 0;
usedBombs = 0;
direction = 0;
dropBomb = false;
name = "Unknown player";
}
/**
* Constructor
* @param game
* @param map
* @param id
* @param x
* @param y
*/
public BomberPlayer(BomberGame game, BomberMap map, int id, int x, int y, String name) {
this();
this.game = game;
this.map = map;
this.id = id;
this.x = x;
this.y = y;
this.name = name;
}
/**
* Control Keys pick for this player from the keyconfig class
*/
public void loadKeys() {
KeyConfig kC = new KeyConfig();
keys[UP] = kC.keys[id-1][UP];
keys[DOWN] = kC.keys[id-1][DOWN];
keys[LEFT] = kC.keys[id-1][LEFT];
keys[RIGHT] = kC.keys[id-1][RIGHT];
keys[BOMB] = kC.keys[id-1][BOMB];
}
/**
* @return
*/
public BomberMap getMap() {
return this.map;
}
/**
* @return
*/
public BomberGame getGame() {
return this.game;
}
/**
* @return
*/
public int getId() {
return this.id;
}
/**
* @return
*/
public int getX() {
return this.x;
}
/**
* @return
*/
public int getY() {
return this.y;
}
/**
* @return
*/
public Coord getCoords() {
return new Coord(this.x,this.y);
}
/**
* @return
*/
public boolean getIsDead() {
return this.isDead;
}
/**
* @return
*/
public int getSpeed() {
return this.speed;
}
/**
* @return
*/
public int getTotalBombs() {
return this.totalBombs;
}
/**
* @return
*/
public int getBombStrike() {
return this.bombStrike;
}
/**
* @return
*/
public int getUsedBombs() {
return this.usedBombs;
}
/**
* Get function for the ArrayList of the bombs laid by this player
* @return
*/
public ArrayList<Bomb> getBombs() {
return this.bombs;
}
/**
* @return
*/
public String getName() {
return this.name;
}
/**
* Set functions; So that external classes can set the variables of these classes
*/
public void setMap(BomberMap map) {
this.map = map;
}
public void setGame(BomberGame game) {
this.game = game;
}
public void setId(int id) {
this.id = id;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setIsDead(boolean isDead) {
this.isDead = isDead;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setTotalBombs(int totalBombs) {
this.totalBombs = totalBombs;
}
public void setBombStrike(int bombStrike) {
this.bombStrike = bombStrike;
}
public void setUsedBombs(int usedBombs) {
this.usedBombs = usedBombs;
}
public void setDirection(int direction) {
this.direction = direction;
}
public void setDropBomb(boolean dropBomb) {
this.dropBomb = dropBomb;
}
public void setBombs(ArrayList<Bomb> bombs) {
this.bombs = bombs;
}
/**
* Semi-set functions
*/
public void incSpeed(int a) {
speed = speed+a;
}
public void decSpeed(int a) {
speed = speed-a;
}
public void incTotalBombs(int a) {
totalBombs = totalBombs+a;
}
public void decTotalBombs(int a) {
totalBombs = totalBombs-a;
}
public void incBombStrike(int a) {
bombStrike = bombStrike+a;
}
public void decBombStrike(int a) {
bombStrike = bombStrike-a;
}
/**
* Is performed by pressing a button
* @param evt: Contains information key pressed
*/
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == keys[UP]) {
this.direction = DIR_UP;
}
else if (evt.getKeyCode() == keys[DOWN]) {
this.direction = DIR_DOWN;
}
else if (evt.getKeyCode() == keys[LEFT]) {
this.direction = DIR_LEFT;
}
else if (evt.getKeyCode() == keys[RIGHT]) {
this.direction = DIR_RIGHT;
}
else if (evt.getKeyCode() == keys[BOMB]) {
dropBomb = true;
}
}
/**
* Is performed at the release of a key
* @param evt: Contains information about the release button
*/
public void keyReleased(KeyEvent evt) {
if ((evt.getKeyCode() == keys[UP]) && (direction == DIR_UP)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[DOWN]) && (direction == DIR_DOWN)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[LEFT]) && (direction == DIR_LEFT)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[RIGHT]) && (direction == DIR_RIGHT)) {
direction = 0;
}
}
/**
* Players will be 'killed'
*/
public void kill() {
this.isDead = true;
}
/**
* Is performed at each "pulse timer", from here everything is performed every
*/
public void act() {
//Loop all the bombs laid by the player to remove the unexploded bombs from the list
for (Iterator i = bombs.listIterator(); i.hasNext();) {
Bomb b = (Bomb) i.next(); //Current 'bomb' in the course
if (b.isExploded()) {
i.remove();
}
}
Coord c = new Coord(x,y);
if (map.isStrike(c)) {
this.kill();
game.endGame();
}
else {
map.checkBonus(this);
if (dropBomb) {
if (bombs.size() < totalBombs) {
Bomb b = new Bomb(this,x,y);
bombs.add(b);
map.createBomb(b);
usedBombs++;
}
}
dropBomb = false;
//Control or player wants to move
switch(direction) {
case DIR_UP: //Players will move upwards
c.decY(); //Current coordinate one box up
if (!map.isObstacle(c)) {
this.y--;
} //n-> Move Up
break;
case DIR_DOWN: //Player wants to move downwardly
c.incY(); //Current coordinate 1 box down
if (!map.isObstacle(c)) {
this.y++;
} //n-> Move Down
break;
case DIR_LEFT: //Players will move to the left
c.decX(); //Current coordinate one box to the left
if (!map.isObstacle(c)) {
this.x--;
} //n-> move left
break;
case DIR_RIGHT: //Players will move to the right
c.incX(); //Current coordinate one box to the right
if (!map.isObstacle(c)) {
this.x++;
} //n->naar rechts<SUF>
break;
default: //Player does not want to move -> nothing
}
}
}
}
| false | 2,219 | 11 | 2,409 | 12 | 2,653 | 7 | 2,409 | 12 | 2,914 | 11 | false | false | false | false | false | true |
4,371 | 41780_0 | import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Day8 {
static final class LR {
private final String left;
private final String right;
public LR(String left, String right) {
this.left = left;
this.right = right;
}
public String get(Character lOrR){
if(lOrR.equals('L'))
return left;
if(lOrR.equals('R'))
return right;
throw new RuntimeException();
}
}
public static void main(String[] args) {
calculate1("src/day8/example1.txt");
calculate1("src/day8/input.txt");
calculate2("src/day8/example2.txt");
calculate2("src/day8/input.txt");
}
private static void calculate1(String filename) {
Util.applyToFile(filename, lines -> {
var split = lines.split("\n\n");
var instructions = split[0].strip().chars().mapToObj(c -> (char)c).toList();
var size = instructions.size();
var nodes = getNodeMap(split[1]);
var i = 0;
String node = "AAA";
while(true){
var c = instructions.get(i % size);
node = nodes.get(node).get(c);
if(node.equals("ZZZ")){
System.out.println(i+1);
return;
}
i++;
}
});
}
private static void calculate2(String filename) {
Util.applyToFile(filename, lines -> {
var split = lines.split("\n\n");
var instructions = split[0].strip().chars().mapToObj(c -> (char)c).toList();
var size = instructions.size();
var nodes = getNodeMap(split[1]);
var node = nodes.keySet().stream().filter(s -> s.endsWith("A")).collect(Collectors.toList());
List<Integer> tails = new ArrayList<>();
List<Integer> cycleLengths = new ArrayList<>();
List<Integer> zPos = new ArrayList<>();
for(var n : node){
var i = 0;
var cycle = new ArrayList<String>();
var next = n;
inner: while(true){
var c = instructions.get(i % size);
next = nodes.get(next).get(c);
if(cycle.contains(next) && cycle.indexOf(next) - i % size == 0){
tails.add(cycle.indexOf(next));
cycleLengths.add(i - cycle.indexOf(next));
break inner;
}
cycle.add(next);
if(next.endsWith("Z"))
zPos.add(cycle.indexOf(next));
i++;
}
}
System.out.println(cycleLengths); //Gebruik wolfram alpha om lcm te berekenen, Java is moeilijk.
});
}
private static Map<String,LR> getNodeMap(String string) {
return Util.split(string,"\n").map(s -> s.split("="))
.collect(Collectors.toMap(s -> s[0].strip(), s -> {
var s2 = s[1].strip();
return new LR(s2.substring(1,4), s2.substring(6,9));
}));
}
}
| spr3nk3ls/aoc_2023 | src/Day8.java | 923 | //Gebruik wolfram alpha om lcm te berekenen, Java is moeilijk. | line_comment | nl | import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Day8 {
static final class LR {
private final String left;
private final String right;
public LR(String left, String right) {
this.left = left;
this.right = right;
}
public String get(Character lOrR){
if(lOrR.equals('L'))
return left;
if(lOrR.equals('R'))
return right;
throw new RuntimeException();
}
}
public static void main(String[] args) {
calculate1("src/day8/example1.txt");
calculate1("src/day8/input.txt");
calculate2("src/day8/example2.txt");
calculate2("src/day8/input.txt");
}
private static void calculate1(String filename) {
Util.applyToFile(filename, lines -> {
var split = lines.split("\n\n");
var instructions = split[0].strip().chars().mapToObj(c -> (char)c).toList();
var size = instructions.size();
var nodes = getNodeMap(split[1]);
var i = 0;
String node = "AAA";
while(true){
var c = instructions.get(i % size);
node = nodes.get(node).get(c);
if(node.equals("ZZZ")){
System.out.println(i+1);
return;
}
i++;
}
});
}
private static void calculate2(String filename) {
Util.applyToFile(filename, lines -> {
var split = lines.split("\n\n");
var instructions = split[0].strip().chars().mapToObj(c -> (char)c).toList();
var size = instructions.size();
var nodes = getNodeMap(split[1]);
var node = nodes.keySet().stream().filter(s -> s.endsWith("A")).collect(Collectors.toList());
List<Integer> tails = new ArrayList<>();
List<Integer> cycleLengths = new ArrayList<>();
List<Integer> zPos = new ArrayList<>();
for(var n : node){
var i = 0;
var cycle = new ArrayList<String>();
var next = n;
inner: while(true){
var c = instructions.get(i % size);
next = nodes.get(next).get(c);
if(cycle.contains(next) && cycle.indexOf(next) - i % size == 0){
tails.add(cycle.indexOf(next));
cycleLengths.add(i - cycle.indexOf(next));
break inner;
}
cycle.add(next);
if(next.endsWith("Z"))
zPos.add(cycle.indexOf(next));
i++;
}
}
System.out.println(cycleLengths); //Gebruik wolfram<SUF>
});
}
private static Map<String,LR> getNodeMap(String string) {
return Util.split(string,"\n").map(s -> s.split("="))
.collect(Collectors.toMap(s -> s[0].strip(), s -> {
var s2 = s[1].strip();
return new LR(s2.substring(1,4), s2.substring(6,9));
}));
}
}
| false | 665 | 20 | 780 | 22 | 845 | 15 | 780 | 22 | 908 | 21 | false | false | false | false | false | true |
314 | 174333_3 | package nl.cerios.cerioscoop.service;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.sql.DataSource;
import nl.cerios.cerioscoop.ValueObjects.ShowPresentationVO;
import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO;
import nl.cerios.cerioscoop.domain.Customer;
import nl.cerios.cerioscoop.domain.Movie;
import nl.cerios.cerioscoop.domain.MovieBuilder;
import nl.cerios.cerioscoop.domain.Show;
import nl.cerios.cerioscoop.domain.User;
import nl.cerios.cerioscoop.util.DateUtils;
@Stateless //Stateless is de status van de gevulde opjecten. Best Practice is stateless.
public class GeneralService {
@Resource(name = "jdbc/cerioscoop") //Content Dependency Injection techniek
private DataSource dataSource;
private DateUtils dateUtils = new DateUtils();
public List<Movie> getMovies(){
final List<Movie> movies = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()) { //AutoCloseable
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT movie_id, title, movie_description FROM movie");
while (resultSet.next()) {
final Movie movie = new MovieBuilder()
.withMovieId(resultSet.getBigDecimal("movie_id").toBigInteger())
.withMovieTitle(resultSet.getString("title"))
.withMovieDescription(resultSet.getString("movie_description"))
.build();
movies.add(movie);
}
return movies;
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the movie.", e);
}
}
public List<Show> getShows(){
final List<Show> shows = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()){
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT show_id, movie_id, room_id, show_date, show_time, available_places, show_price FROM show_table"); {
while (resultSet.next()) {
final int showId = resultSet.getInt("show_id");
final int movieId = resultSet.getInt("movie_id");
final int roomId = resultSet.getInt("room_id");
final Date showDate = resultSet.getDate("show_date");
final Time showTime = resultSet.getTime("show_time");
final int availablePlaces = resultSet.getInt("available_places");
final float showPrice = resultSet.getInt("show_price");
shows.add(new Show(showId, movieId, roomId, showDate, showTime, availablePlaces, showPrice));
}
return shows;
}
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the first date.", e);
}
}
public List<Customer> getCustomers(){
final List<Customer> customers = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()){
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT customer_id, first_name, last_name, username, password, email FROM customer"); {
while (resultSet.next()) {
final int customerId = resultSet.getInt("customer_id");
final String firstName = resultSet.getString("first_name");
final String lastName = resultSet.getString("last_name");
final String username = resultSet.getString("username");
final String password = resultSet.getString("password");
final String email = resultSet.getString("email");
customers.add(new Customer(customerId, firstName, lastName, username, password, email));
}
return customers;
}
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the customers.", e);
}
}
/**
* Returns a first showing record.
*
* @return firstShowing
*/
public Show getFirstShowforToday(final List<Show> listOfShows){
Show firstShow = null;
for (final Show show : listOfShows) {
if(dateUtils.toDateTime(show.getShowDate(), show.getShowTime()).after(dateUtils.getCurrentSqlTime())){
if(firstShow == null){ //hier wordt voor 1x eerstVolgendeFilm gevuld
firstShow = show;
}
else if(show.getShowTime().before(firstShow.getShowTime())){
firstShow = show;
}
}
}
return firstShow;
}
public Movie getMovieByMovieId(final int movieId, final List<Movie> listOfMovies) throws MovieNotFoundException {
final List<Movie> movies = listOfMovies;
Movie movieByMovieId = null;
for (final Movie movieItem : movies){
if (movieItem.getMovieId().intValue() == movieId) {
movieByMovieId = movieItem;
}
}
return movieByMovieId;
}
public void registerCustomer(final Customer customer){
try (final Connection connection = dataSource.getConnection();
final PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO customer (first_name, last_name, username, password, email) VALUES (?,?,?,?,?)")) {
preparedStatement.setString(1, customer.getFirstName());
preparedStatement.setString(2, customer.getLastName());
preparedStatement.setString(3, customer.getUsername());
preparedStatement.setString(4, customer.getPassword());
preparedStatement.setString(5, customer.getEmail());
preparedStatement.executeUpdate();
System.out.println("Data inserted.");
}catch (final SQLException e) {
throw new ServiceException("Something went wrong while inserting the customer items.", e);
}
}
public User authenticateCustomer(User customer, List<Customer> listOfCustomers){
final List<Customer> dbCustomers = listOfCustomers;
final String usernameCustomer = customer.getUsername();
final String passwordCustomer = customer.getPassword();
User authenticatedCustomer = null;
for (final Customer customerItem : dbCustomers){
if(customerItem.getUsername().equals(usernameCustomer) && customerItem.getPassword().equals(passwordCustomer)){
authenticatedCustomer = customerItem;
}
}
return authenticatedCustomer;
}
public Boolean authenticateUser(User authenticatedUser){
if(authenticatedUser == null){
return false;
}
return true;
}
public List<ShowsPresentationVO> generateShowTable(final List<Show> shows, final List<Movie> movies) throws MovieNotFoundException {
List<ShowsPresentationVO> todaysShowsTable = new ArrayList<ShowsPresentationVO>();
// voeg alle shows toe aan de tabel
for (Show todaysShow : shows) {
ShowsPresentationVO existingShowsPresentationVORow = null; // checkt of de movie van de huidige tabel al is opgenomen
for (ShowsPresentationVO showsRowIter : todaysShowsTable) {
if (todaysShow.getMovieId() == showsRowIter.getMovie().getMovieId().intValue()) {// hier bestaat de movie al in de index
ShowPresentationVO newShowPresentationVO = new ShowPresentationVO();
newShowPresentationVO.setShow(todaysShow);
newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces()));
showsRowIter.shows.add(newShowPresentationVO);
existingShowsPresentationVORow = showsRowIter;
}
}
if (existingShowsPresentationVORow == null) {//Nieuwe MovieRow worst gemaakt
ShowPresentationVO newShowPresentationVO = new ShowPresentationVO();
newShowPresentationVO.setShow(todaysShow);
newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces()));
ShowsPresentationVO newShowsPresentationRowVO = new ShowsPresentationVO();
List<ShowPresentationVO> showPresentationVOList = new ArrayList<ShowPresentationVO>();
showPresentationVOList.add(newShowPresentationVO);
newShowsPresentationRowVO.setMovie(getMovieByMovieId(todaysShow.getMovieId(), movies));
newShowsPresentationRowVO.setShowsPresentationVO(showPresentationVOList);
todaysShowsTable.add(newShowsPresentationRowVO);
}
}
return todaysShowsTable;
}
public String generateRandomUsername(){
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString();
}
public Boolean checkIfThereAreNoAvailablePlaces(int availablePlaces){
if(availablePlaces == 0){
return true;
}else{
return false;
}
}
}
| Cerios/cerioscoop-web | src/main/java/nl/cerios/cerioscoop/service/GeneralService.java | 2,747 | //hier wordt voor 1x eerstVolgendeFilm gevuld | line_comment | nl | package nl.cerios.cerioscoop.service;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.sql.DataSource;
import nl.cerios.cerioscoop.ValueObjects.ShowPresentationVO;
import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO;
import nl.cerios.cerioscoop.domain.Customer;
import nl.cerios.cerioscoop.domain.Movie;
import nl.cerios.cerioscoop.domain.MovieBuilder;
import nl.cerios.cerioscoop.domain.Show;
import nl.cerios.cerioscoop.domain.User;
import nl.cerios.cerioscoop.util.DateUtils;
@Stateless //Stateless is de status van de gevulde opjecten. Best Practice is stateless.
public class GeneralService {
@Resource(name = "jdbc/cerioscoop") //Content Dependency Injection techniek
private DataSource dataSource;
private DateUtils dateUtils = new DateUtils();
public List<Movie> getMovies(){
final List<Movie> movies = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()) { //AutoCloseable
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT movie_id, title, movie_description FROM movie");
while (resultSet.next()) {
final Movie movie = new MovieBuilder()
.withMovieId(resultSet.getBigDecimal("movie_id").toBigInteger())
.withMovieTitle(resultSet.getString("title"))
.withMovieDescription(resultSet.getString("movie_description"))
.build();
movies.add(movie);
}
return movies;
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the movie.", e);
}
}
public List<Show> getShows(){
final List<Show> shows = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()){
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT show_id, movie_id, room_id, show_date, show_time, available_places, show_price FROM show_table"); {
while (resultSet.next()) {
final int showId = resultSet.getInt("show_id");
final int movieId = resultSet.getInt("movie_id");
final int roomId = resultSet.getInt("room_id");
final Date showDate = resultSet.getDate("show_date");
final Time showTime = resultSet.getTime("show_time");
final int availablePlaces = resultSet.getInt("available_places");
final float showPrice = resultSet.getInt("show_price");
shows.add(new Show(showId, movieId, roomId, showDate, showTime, availablePlaces, showPrice));
}
return shows;
}
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the first date.", e);
}
}
public List<Customer> getCustomers(){
final List<Customer> customers = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()){
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT customer_id, first_name, last_name, username, password, email FROM customer"); {
while (resultSet.next()) {
final int customerId = resultSet.getInt("customer_id");
final String firstName = resultSet.getString("first_name");
final String lastName = resultSet.getString("last_name");
final String username = resultSet.getString("username");
final String password = resultSet.getString("password");
final String email = resultSet.getString("email");
customers.add(new Customer(customerId, firstName, lastName, username, password, email));
}
return customers;
}
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the customers.", e);
}
}
/**
* Returns a first showing record.
*
* @return firstShowing
*/
public Show getFirstShowforToday(final List<Show> listOfShows){
Show firstShow = null;
for (final Show show : listOfShows) {
if(dateUtils.toDateTime(show.getShowDate(), show.getShowTime()).after(dateUtils.getCurrentSqlTime())){
if(firstShow == null){ //hier wordt<SUF>
firstShow = show;
}
else if(show.getShowTime().before(firstShow.getShowTime())){
firstShow = show;
}
}
}
return firstShow;
}
public Movie getMovieByMovieId(final int movieId, final List<Movie> listOfMovies) throws MovieNotFoundException {
final List<Movie> movies = listOfMovies;
Movie movieByMovieId = null;
for (final Movie movieItem : movies){
if (movieItem.getMovieId().intValue() == movieId) {
movieByMovieId = movieItem;
}
}
return movieByMovieId;
}
public void registerCustomer(final Customer customer){
try (final Connection connection = dataSource.getConnection();
final PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO customer (first_name, last_name, username, password, email) VALUES (?,?,?,?,?)")) {
preparedStatement.setString(1, customer.getFirstName());
preparedStatement.setString(2, customer.getLastName());
preparedStatement.setString(3, customer.getUsername());
preparedStatement.setString(4, customer.getPassword());
preparedStatement.setString(5, customer.getEmail());
preparedStatement.executeUpdate();
System.out.println("Data inserted.");
}catch (final SQLException e) {
throw new ServiceException("Something went wrong while inserting the customer items.", e);
}
}
public User authenticateCustomer(User customer, List<Customer> listOfCustomers){
final List<Customer> dbCustomers = listOfCustomers;
final String usernameCustomer = customer.getUsername();
final String passwordCustomer = customer.getPassword();
User authenticatedCustomer = null;
for (final Customer customerItem : dbCustomers){
if(customerItem.getUsername().equals(usernameCustomer) && customerItem.getPassword().equals(passwordCustomer)){
authenticatedCustomer = customerItem;
}
}
return authenticatedCustomer;
}
public Boolean authenticateUser(User authenticatedUser){
if(authenticatedUser == null){
return false;
}
return true;
}
public List<ShowsPresentationVO> generateShowTable(final List<Show> shows, final List<Movie> movies) throws MovieNotFoundException {
List<ShowsPresentationVO> todaysShowsTable = new ArrayList<ShowsPresentationVO>();
// voeg alle shows toe aan de tabel
for (Show todaysShow : shows) {
ShowsPresentationVO existingShowsPresentationVORow = null; // checkt of de movie van de huidige tabel al is opgenomen
for (ShowsPresentationVO showsRowIter : todaysShowsTable) {
if (todaysShow.getMovieId() == showsRowIter.getMovie().getMovieId().intValue()) {// hier bestaat de movie al in de index
ShowPresentationVO newShowPresentationVO = new ShowPresentationVO();
newShowPresentationVO.setShow(todaysShow);
newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces()));
showsRowIter.shows.add(newShowPresentationVO);
existingShowsPresentationVORow = showsRowIter;
}
}
if (existingShowsPresentationVORow == null) {//Nieuwe MovieRow worst gemaakt
ShowPresentationVO newShowPresentationVO = new ShowPresentationVO();
newShowPresentationVO.setShow(todaysShow);
newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces()));
ShowsPresentationVO newShowsPresentationRowVO = new ShowsPresentationVO();
List<ShowPresentationVO> showPresentationVOList = new ArrayList<ShowPresentationVO>();
showPresentationVOList.add(newShowPresentationVO);
newShowsPresentationRowVO.setMovie(getMovieByMovieId(todaysShow.getMovieId(), movies));
newShowsPresentationRowVO.setShowsPresentationVO(showPresentationVOList);
todaysShowsTable.add(newShowsPresentationRowVO);
}
}
return todaysShowsTable;
}
public String generateRandomUsername(){
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString();
}
public Boolean checkIfThereAreNoAvailablePlaces(int availablePlaces){
if(availablePlaces == 0){
return true;
}else{
return false;
}
}
}
| false | 1,908 | 16 | 2,265 | 18 | 2,298 | 14 | 2,265 | 18 | 2,893 | 20 | false | false | false | false | false | true |
566 | 21120_0 | package be.intecbrussel.the_notebook.app;
import be.intecbrussel.the_notebook.entities.animal_entities.Animal;
import be.intecbrussel.the_notebook.entities.animal_entities.Carnivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Herbivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Omnivore;
import be.intecbrussel.the_notebook.entities.plant_entities.*;
import be.intecbrussel.the_notebook.service.ForestNotebook;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
public class NatureApp {
public static void main(String[] args) {
lineGenerator();
System.out.println("FOREST NOTEBOOK TEST");
lineGenerator();
ForestNotebook forestNotebook = new ForestNotebook();
Plant plant = new Plant("Orchid", 0.55);
Tree tree = new Tree("Pine tree", 40.5);
tree.setLeafType(LeafType.NEEDLE);
Flower flower = new Flower("Rose", 0.15);
flower.setSmell(Scent.SWEET);
Weed weed = new Weed("Dandelion", 0.05);
// Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurig cijfer daarin geplaatst.
weed.setArea(10.5);
Bush bush = new Bush("Blueberry bush", 3.5);
bush.setLeafType(LeafType.SPEAR);
bush.setFruit("Blueberry");
forestNotebook.addPlant(plant);
forestNotebook.addPlant(tree);
forestNotebook.addPlant(flower);
forestNotebook.addPlant(weed);
forestNotebook.addPlant(bush);
forestNotebook.addPlant(plant);
List<Carnivore> carnivoreList = new ArrayList<>();
List<Herbivore> herbivoreList = new ArrayList<>();
List<Omnivore> omnivoreList = new ArrayList<>();
Carnivore lion = new Carnivore("Lion", 190, 1.2, 2.1);
// Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurige maat daarin geplaatst.
lion.setMaxFoodSize(1.5);
carnivoreList.add(lion);
forestNotebook.setCarnivores(carnivoreList);
Herbivore elephant = new Herbivore("Elephant", 6000, 3.2, 6.5);
Set<Plant> elephantDiet = new LinkedHashSet<>();
Plant plant1 = new Plant("Grasses");
Plant plant2 = new Plant("Leaves");
Plant plant3 = new Plant("Fruits");
Plant plant4 = new Plant("Roots");
elephantDiet.add(plant1);
elephantDiet.add(plant2);
elephantDiet.add(plant3);
elephant.setPlantDiet(elephantDiet);
elephant.addPlantToDiet(plant4);
herbivoreList.add(elephant);
forestNotebook.setHerbivores(herbivoreList);
Omnivore bear = new Omnivore("Bear", 500, 1.5, 2.8);
bear.setMaxFoodSize(1.5);
Set<Plant> bearDiet = new LinkedHashSet<>();
bearDiet.add(new Plant("Berries"));
bearDiet.add(plant1);
bear.setPlantDiet(bearDiet);
bear.addPlantToDiet(plant4);
omnivoreList.add(bear);
forestNotebook.setOmnivores(omnivoreList);
Animal animal1 = new Animal("Gorilla", 270, 1.8, 1.7);
Animal animal2 = new Animal("Anaconda", 250, 0.3, 8.5);
Animal animal3 = new Animal("Red fox", 14, 0.5, 0.85);
Animal animal4 = new Animal("Rabbit", 2, 0.22, 0.45);
Animal animal5 = new Animal("Wolf", 80, 0.85, 1.6);
Animal animal6 = new Animal("Eagle", 6, 0.61, 0.90);
forestNotebook.addAnimal(lion);
forestNotebook.addAnimal(elephant);
forestNotebook.addAnimal(bear);
forestNotebook.addAnimal(animal1);
forestNotebook.addAnimal(animal2);
forestNotebook.addAnimal(animal3);
forestNotebook.addAnimal(animal4);
forestNotebook.addAnimal(animal5);
forestNotebook.addAnimal(animal6);
forestNotebook.addAnimal(lion);
lineGenerator();
System.out.println("TOTAL PLANTS AND ANIMALS");
lineGenerator();
System.out.println("Plants -> " + forestNotebook.getPlantCount());
System.out.println("Animals -> " + forestNotebook.getAnimalCount());
lineGenerator();
System.out.println("UNSORTED LIST OF PLANTS AND ANIMALS");
lineGenerator();
forestNotebook.printNotebook();
lineGenerator();
System.out.println("LIST OF CARNIVORE, OMNIVORE AND HERBIVORE ANIMALS");
lineGenerator();
forestNotebook.getCarnivores().forEach(System.out::println);
forestNotebook.getOmnivores().forEach(System.out::println);
forestNotebook.getHerbivores().forEach(System.out::println);
lineGenerator();
System.out.println("LIST OF PLANTS AND ANIMALS SORTED BY NAME");
lineGenerator();
forestNotebook.sortAnimalsByName();
forestNotebook.sortPlantsByName();
forestNotebook.printNotebook();
// Ik heb alle metingen omgezet naar meters om correct te kunnen sorteren.
lineGenerator();
System.out.println("BONUS - LIST OF PLANTS AND ANIMALS SORTED BY HEIGHT");
lineGenerator();
forestNotebook.sortAnimalsByHeight();
forestNotebook.sortPlantsHeight();
forestNotebook.printNotebook();
}
public static void lineGenerator() {
System.out.println("-".repeat(100));
}
}
| Gabe-Alvess/ForestNoteBook | src/be/intecbrussel/the_notebook/app/NatureApp.java | 1,805 | // Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurig cijfer daarin geplaatst. | line_comment | nl | package be.intecbrussel.the_notebook.app;
import be.intecbrussel.the_notebook.entities.animal_entities.Animal;
import be.intecbrussel.the_notebook.entities.animal_entities.Carnivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Herbivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Omnivore;
import be.intecbrussel.the_notebook.entities.plant_entities.*;
import be.intecbrussel.the_notebook.service.ForestNotebook;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
public class NatureApp {
public static void main(String[] args) {
lineGenerator();
System.out.println("FOREST NOTEBOOK TEST");
lineGenerator();
ForestNotebook forestNotebook = new ForestNotebook();
Plant plant = new Plant("Orchid", 0.55);
Tree tree = new Tree("Pine tree", 40.5);
tree.setLeafType(LeafType.NEEDLE);
Flower flower = new Flower("Rose", 0.15);
flower.setSmell(Scent.SWEET);
Weed weed = new Weed("Dandelion", 0.05);
// Geen idee<SUF>
weed.setArea(10.5);
Bush bush = new Bush("Blueberry bush", 3.5);
bush.setLeafType(LeafType.SPEAR);
bush.setFruit("Blueberry");
forestNotebook.addPlant(plant);
forestNotebook.addPlant(tree);
forestNotebook.addPlant(flower);
forestNotebook.addPlant(weed);
forestNotebook.addPlant(bush);
forestNotebook.addPlant(plant);
List<Carnivore> carnivoreList = new ArrayList<>();
List<Herbivore> herbivoreList = new ArrayList<>();
List<Omnivore> omnivoreList = new ArrayList<>();
Carnivore lion = new Carnivore("Lion", 190, 1.2, 2.1);
// Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurige maat daarin geplaatst.
lion.setMaxFoodSize(1.5);
carnivoreList.add(lion);
forestNotebook.setCarnivores(carnivoreList);
Herbivore elephant = new Herbivore("Elephant", 6000, 3.2, 6.5);
Set<Plant> elephantDiet = new LinkedHashSet<>();
Plant plant1 = new Plant("Grasses");
Plant plant2 = new Plant("Leaves");
Plant plant3 = new Plant("Fruits");
Plant plant4 = new Plant("Roots");
elephantDiet.add(plant1);
elephantDiet.add(plant2);
elephantDiet.add(plant3);
elephant.setPlantDiet(elephantDiet);
elephant.addPlantToDiet(plant4);
herbivoreList.add(elephant);
forestNotebook.setHerbivores(herbivoreList);
Omnivore bear = new Omnivore("Bear", 500, 1.5, 2.8);
bear.setMaxFoodSize(1.5);
Set<Plant> bearDiet = new LinkedHashSet<>();
bearDiet.add(new Plant("Berries"));
bearDiet.add(plant1);
bear.setPlantDiet(bearDiet);
bear.addPlantToDiet(plant4);
omnivoreList.add(bear);
forestNotebook.setOmnivores(omnivoreList);
Animal animal1 = new Animal("Gorilla", 270, 1.8, 1.7);
Animal animal2 = new Animal("Anaconda", 250, 0.3, 8.5);
Animal animal3 = new Animal("Red fox", 14, 0.5, 0.85);
Animal animal4 = new Animal("Rabbit", 2, 0.22, 0.45);
Animal animal5 = new Animal("Wolf", 80, 0.85, 1.6);
Animal animal6 = new Animal("Eagle", 6, 0.61, 0.90);
forestNotebook.addAnimal(lion);
forestNotebook.addAnimal(elephant);
forestNotebook.addAnimal(bear);
forestNotebook.addAnimal(animal1);
forestNotebook.addAnimal(animal2);
forestNotebook.addAnimal(animal3);
forestNotebook.addAnimal(animal4);
forestNotebook.addAnimal(animal5);
forestNotebook.addAnimal(animal6);
forestNotebook.addAnimal(lion);
lineGenerator();
System.out.println("TOTAL PLANTS AND ANIMALS");
lineGenerator();
System.out.println("Plants -> " + forestNotebook.getPlantCount());
System.out.println("Animals -> " + forestNotebook.getAnimalCount());
lineGenerator();
System.out.println("UNSORTED LIST OF PLANTS AND ANIMALS");
lineGenerator();
forestNotebook.printNotebook();
lineGenerator();
System.out.println("LIST OF CARNIVORE, OMNIVORE AND HERBIVORE ANIMALS");
lineGenerator();
forestNotebook.getCarnivores().forEach(System.out::println);
forestNotebook.getOmnivores().forEach(System.out::println);
forestNotebook.getHerbivores().forEach(System.out::println);
lineGenerator();
System.out.println("LIST OF PLANTS AND ANIMALS SORTED BY NAME");
lineGenerator();
forestNotebook.sortAnimalsByName();
forestNotebook.sortPlantsByName();
forestNotebook.printNotebook();
// Ik heb alle metingen omgezet naar meters om correct te kunnen sorteren.
lineGenerator();
System.out.println("BONUS - LIST OF PLANTS AND ANIMALS SORTED BY HEIGHT");
lineGenerator();
forestNotebook.sortAnimalsByHeight();
forestNotebook.sortPlantsHeight();
forestNotebook.printNotebook();
}
public static void lineGenerator() {
System.out.println("-".repeat(100));
}
}
| false | 1,417 | 39 | 1,607 | 45 | 1,495 | 27 | 1,607 | 45 | 1,844 | 42 | false | false | false | false | false | true |
2,730 | 153258_7 | /* Generated by Together */
package bank.bankieren;
import java.io.*;
import java.text.*;
public class Money implements Serializable, Comparable<Money> {
private static final long serialVersionUID = 1L;
public static final String EURO = "\u20AC";
/* private Money() {
currency="undefined";
}
*/
/**
* er is een geldbedrag van munteenheid currency en waarde cents gecreeerd
*
* @param amount
* @param currency
* @throws RuntimeException
* als currency een lege string is
*/
public Money(long cents, String currency) {
if (currency.equals(""))
throw new RuntimeException("currency may not be the empty string");
this.cents=cents;
this.currency = currency;
}
/**
*
* @return de munteenheid gevolgd door een spatie en de waarde in twee
* decimalen nauwkeurig
*/
public String toString() {
return currency + " " + getValue();
}
/**
*
* @return <b>true</b> als het Money-object groter dan 0 is, anders
* <b>false</b>
*/
public boolean isPositive() {
return cents > 0;
}
public String getCurrency() {
return currency;
}
/**
*
* @return de waarde in twee decimalen nauwkeurig
*/
public String getValue() {
DecimalFormat df = new DecimalFormat("0.00");
return df.format(((double) cents) / 100);
}
public long getCents() {
return cents;
}
/**
* voorwaarde: currency van m1 en m2 moeten gelijk zijn
* @returns het verschil tussen m1 en m2
*/
public static Money difference(Money m1, Money m2) {
if (!m1.currency.equals(m2.currency))
throw new RuntimeException("munteenheden in aanroep 'difference' ongelijk, te weten: " +
m1.currency + " en " + m2.currency
);
return new Money(m1.cents-m2.cents, m1.currency);
}
/**
* voorwaarde: currency van m1 en m2 moeten gelijk zijn
* @returns de som van m1 en m2
*/
public static Money sum(Money m1, Money m2) {
if (!m1.currency.equals(m2.currency))
throw new RuntimeException("munteenheden in aanroep 'sum' ongelijk, te weten: " +
m1.currency + " en " + m2.currency
);
return new Money(m1.cents+m2.cents, m1.currency);
}
public boolean equals(Object o) {
if (!(o instanceof Money))
return false;
Money m = (Money) o;
return this.currency.equals(m.currency) && this.cents == m.cents;
}
private String currency;
private long cents;
public int compareTo(Money o) {
Money m = (Money) o;
if (!this.currency.equals(m.currency))
throw new RuntimeException("comparing amounts with different currency is not implemented");
if (this.cents==m.cents) return 0;
if (this.cents<m.cents) return -1;
else return +1;
}
}
| frankie285/Netbeans | BankierenNoObserverFX/src/bank/bankieren/Money.java | 937 | /**
* voorwaarde: currency van m1 en m2 moeten gelijk zijn
* @returns de som van m1 en m2
*/ | block_comment | nl | /* Generated by Together */
package bank.bankieren;
import java.io.*;
import java.text.*;
public class Money implements Serializable, Comparable<Money> {
private static final long serialVersionUID = 1L;
public static final String EURO = "\u20AC";
/* private Money() {
currency="undefined";
}
*/
/**
* er is een geldbedrag van munteenheid currency en waarde cents gecreeerd
*
* @param amount
* @param currency
* @throws RuntimeException
* als currency een lege string is
*/
public Money(long cents, String currency) {
if (currency.equals(""))
throw new RuntimeException("currency may not be the empty string");
this.cents=cents;
this.currency = currency;
}
/**
*
* @return de munteenheid gevolgd door een spatie en de waarde in twee
* decimalen nauwkeurig
*/
public String toString() {
return currency + " " + getValue();
}
/**
*
* @return <b>true</b> als het Money-object groter dan 0 is, anders
* <b>false</b>
*/
public boolean isPositive() {
return cents > 0;
}
public String getCurrency() {
return currency;
}
/**
*
* @return de waarde in twee decimalen nauwkeurig
*/
public String getValue() {
DecimalFormat df = new DecimalFormat("0.00");
return df.format(((double) cents) / 100);
}
public long getCents() {
return cents;
}
/**
* voorwaarde: currency van m1 en m2 moeten gelijk zijn
* @returns het verschil tussen m1 en m2
*/
public static Money difference(Money m1, Money m2) {
if (!m1.currency.equals(m2.currency))
throw new RuntimeException("munteenheden in aanroep 'difference' ongelijk, te weten: " +
m1.currency + " en " + m2.currency
);
return new Money(m1.cents-m2.cents, m1.currency);
}
/**
* voorwaarde: currency van<SUF>*/
public static Money sum(Money m1, Money m2) {
if (!m1.currency.equals(m2.currency))
throw new RuntimeException("munteenheden in aanroep 'sum' ongelijk, te weten: " +
m1.currency + " en " + m2.currency
);
return new Money(m1.cents+m2.cents, m1.currency);
}
public boolean equals(Object o) {
if (!(o instanceof Money))
return false;
Money m = (Money) o;
return this.currency.equals(m.currency) && this.cents == m.cents;
}
private String currency;
private long cents;
public int compareTo(Money o) {
Money m = (Money) o;
if (!this.currency.equals(m.currency))
throw new RuntimeException("comparing amounts with different currency is not implemented");
if (this.cents==m.cents) return 0;
if (this.cents<m.cents) return -1;
else return +1;
}
}
| false | 742 | 34 | 881 | 34 | 843 | 33 | 881 | 34 | 1,006 | 36 | false | false | false | false | false | true |
2,349 | 56075_1 | package exapus.model.forest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.google.common.base.Charsets;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import exapus.model.visitors.IForestVisitor;
public class Member extends MemberContainer {
public Member(UqName id, Element e) {
super(id);
element = e;
references = new ArrayList<Ref>();
}
private String filePath;
private List<Ref> references;
private Element element;
public Element getElement() {
return element;
}
public Iterable<Ref> getReferences() {
return references;
}
public Iterable<Ref> getAllReferences() {
Iterable<Ref> references = getReferences();
for(Member m : getMembers()) {
references = Iterables.concat(references, m.getAllReferences());
}
return references;
}
public void addAPIReference(Ref reference) {
references.add(reference);
reference.setParent(this);
getParentFactForest().fireUpdate(reference);
}
public String toString() {
return "M[" + element.toString() + ": " + getName() + "(" + references.size() + ")" + "]";
}
public Member getTopLevelMember() {
Member parent = this;
Member oldParent = this;
while (parent instanceof Member) {
oldParent = parent;
parent = parent.getParentMember();
}
return oldParent;
}
public String getSourceString() {
try {
String path = getFilePath();
if(path == null) {
Member topLevelMember = getTopLevelMember();
path = topLevelMember.getFilePath();
}
if(path != null) {
return Files.toString(new File(path), Charsets.UTF_8);
}
return null;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean isTopLevel() {
ForestElement parent = getParent();
return !(parent instanceof Member);
}
public ICompilationUnit getCorrespondingICompilationUnit() {
IMember member = getCorrespondingIMember();
if (member != null)
return member.getCompilationUnit();
return null;
}
public IMember getCorrespondingIMember() {
//TODO: only if element = class/etc, or change to getCorrespondingMember
//en daarna getMethod, getField ..
IJavaProject project = getCorrespondingJavaProject();
if(project == null)
return null;
try {
if (element.declaresType())
return project.findType(getQName().toString(), (IProgressMonitor) null);
Member declaringMember = getParentTypeDeclaringMember();
if(declaringMember == null)
return null;
IMember declaringIMember = declaringMember.getCorrespondingIMember();
if(declaringIMember instanceof IType) {
IType declaringIType = (IType) declaringIMember;
if(element.isField())
return declaringIType.getField(this.getName().toString());
if(element.isMethod()) {
UqName uqName = getName();
String shortName = uqName.getMethodName();
String[] parameterSignatures = uqName.getMethodParameterTypeSignatures();
IMethod method = declaringIType.getMethod(shortName, parameterSignatures);
return method;
}
return null;
}
return null;
} catch (JavaModelException e) {
e.printStackTrace();
return null;
}
}
public int getSourceCharacterIndexOffset() {
IMember element = getCorrespondingIMember();
if (element == null)
return 0;
try {
return element.getSourceRange().getOffset();
} catch (JavaModelException e) {
e.printStackTrace();
return 0;
}
}
public int getSourceLineNumberOffset() {
IMember element = getCorrespondingIMember();
if (element == null)
return 0;
try {
int characterIndexOffset = element.getSourceRange().getOffset();
ICompilationUnit icu = element.getCompilationUnit();
IJavaProject ip = icu.getJavaProject();
ICompilationUnit[] icus = {icu};
//TODO: silly to reparse for this, but the usual IDocument means are unavailable (as RAP is incompatible with org.eclipse.jface.text)
return Parser.parse(ip, icus, null)[0].getLineNumber(characterIndexOffset);
} catch (JavaModelException e) {
e.printStackTrace();
return 0;
}
}
public void acceptVisitor(IForestVisitor v) {
if(v.visitMember(this)) {
for(Member m : getMembers())
m.acceptVisitor(v);
for(Ref r : getReferences())
r.acceptVisitor(v);
}
}
public ForestElement getCorrespondingForestElement(ForestElement element) {
if(element instanceof Ref) {
for(Ref ref : getReferences())
if(ref.equals(element))
return ref;
return null;
}
if(element instanceof Member) {
Member member = (Member) element;
return getMember(member);
}
return null;
}
@Override
public ForestElement getCorrespondingForestElement(boolean copyWhenMissing, ForestElement element) {
if(element instanceof Ref) {
if(copyWhenMissing) {
Ref copy = Ref.from((Ref) element);
addAPIReference(copy);
return copy;
}
else {
for(Ref ref : getReferences())
if(ref.equals(element))
return ref;
}
return null;
}
return super.getCorrespondingForestElement(copyWhenMissing, element);
}
public static Member from(Member original) {
Member member = new Member(original.getName(), original.getElement());
member.setFilePath(original.getFilePath());
member.copyTagsFrom(original);
return member;
}
@Override
public boolean hasChildren() {
return !members.isEmpty() || !references.isEmpty();
}
public boolean removeReference(Ref ref) {
return references.remove(ref);
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
| cderoove/exapus | ExapusRAP/src/exapus/model/forest/Member.java | 2,056 | //en daarna getMethod, getField .. | line_comment | nl | package exapus.model.forest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.google.common.base.Charsets;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import exapus.model.visitors.IForestVisitor;
public class Member extends MemberContainer {
public Member(UqName id, Element e) {
super(id);
element = e;
references = new ArrayList<Ref>();
}
private String filePath;
private List<Ref> references;
private Element element;
public Element getElement() {
return element;
}
public Iterable<Ref> getReferences() {
return references;
}
public Iterable<Ref> getAllReferences() {
Iterable<Ref> references = getReferences();
for(Member m : getMembers()) {
references = Iterables.concat(references, m.getAllReferences());
}
return references;
}
public void addAPIReference(Ref reference) {
references.add(reference);
reference.setParent(this);
getParentFactForest().fireUpdate(reference);
}
public String toString() {
return "M[" + element.toString() + ": " + getName() + "(" + references.size() + ")" + "]";
}
public Member getTopLevelMember() {
Member parent = this;
Member oldParent = this;
while (parent instanceof Member) {
oldParent = parent;
parent = parent.getParentMember();
}
return oldParent;
}
public String getSourceString() {
try {
String path = getFilePath();
if(path == null) {
Member topLevelMember = getTopLevelMember();
path = topLevelMember.getFilePath();
}
if(path != null) {
return Files.toString(new File(path), Charsets.UTF_8);
}
return null;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean isTopLevel() {
ForestElement parent = getParent();
return !(parent instanceof Member);
}
public ICompilationUnit getCorrespondingICompilationUnit() {
IMember member = getCorrespondingIMember();
if (member != null)
return member.getCompilationUnit();
return null;
}
public IMember getCorrespondingIMember() {
//TODO: only if element = class/etc, or change to getCorrespondingMember
//en daarna<SUF>
IJavaProject project = getCorrespondingJavaProject();
if(project == null)
return null;
try {
if (element.declaresType())
return project.findType(getQName().toString(), (IProgressMonitor) null);
Member declaringMember = getParentTypeDeclaringMember();
if(declaringMember == null)
return null;
IMember declaringIMember = declaringMember.getCorrespondingIMember();
if(declaringIMember instanceof IType) {
IType declaringIType = (IType) declaringIMember;
if(element.isField())
return declaringIType.getField(this.getName().toString());
if(element.isMethod()) {
UqName uqName = getName();
String shortName = uqName.getMethodName();
String[] parameterSignatures = uqName.getMethodParameterTypeSignatures();
IMethod method = declaringIType.getMethod(shortName, parameterSignatures);
return method;
}
return null;
}
return null;
} catch (JavaModelException e) {
e.printStackTrace();
return null;
}
}
public int getSourceCharacterIndexOffset() {
IMember element = getCorrespondingIMember();
if (element == null)
return 0;
try {
return element.getSourceRange().getOffset();
} catch (JavaModelException e) {
e.printStackTrace();
return 0;
}
}
public int getSourceLineNumberOffset() {
IMember element = getCorrespondingIMember();
if (element == null)
return 0;
try {
int characterIndexOffset = element.getSourceRange().getOffset();
ICompilationUnit icu = element.getCompilationUnit();
IJavaProject ip = icu.getJavaProject();
ICompilationUnit[] icus = {icu};
//TODO: silly to reparse for this, but the usual IDocument means are unavailable (as RAP is incompatible with org.eclipse.jface.text)
return Parser.parse(ip, icus, null)[0].getLineNumber(characterIndexOffset);
} catch (JavaModelException e) {
e.printStackTrace();
return 0;
}
}
public void acceptVisitor(IForestVisitor v) {
if(v.visitMember(this)) {
for(Member m : getMembers())
m.acceptVisitor(v);
for(Ref r : getReferences())
r.acceptVisitor(v);
}
}
public ForestElement getCorrespondingForestElement(ForestElement element) {
if(element instanceof Ref) {
for(Ref ref : getReferences())
if(ref.equals(element))
return ref;
return null;
}
if(element instanceof Member) {
Member member = (Member) element;
return getMember(member);
}
return null;
}
@Override
public ForestElement getCorrespondingForestElement(boolean copyWhenMissing, ForestElement element) {
if(element instanceof Ref) {
if(copyWhenMissing) {
Ref copy = Ref.from((Ref) element);
addAPIReference(copy);
return copy;
}
else {
for(Ref ref : getReferences())
if(ref.equals(element))
return ref;
}
return null;
}
return super.getCorrespondingForestElement(copyWhenMissing, element);
}
public static Member from(Member original) {
Member member = new Member(original.getName(), original.getElement());
member.setFilePath(original.getFilePath());
member.copyTagsFrom(original);
return member;
}
@Override
public boolean hasChildren() {
return !members.isEmpty() || !references.isEmpty();
}
public boolean removeReference(Ref ref) {
return references.remove(ref);
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
| false | 1,515 | 9 | 1,852 | 9 | 1,864 | 8 | 1,853 | 10 | 2,280 | 10 | false | false | false | false | false | true |
2,451 | 190006_1 | package main.java.be.ipeters.ottoz.cpbelcar.services;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import main.java.be.ipeters.ottoz.cpbelcar.domain.Order;
import main.java.be.ipeters.ottoz.cpbelcar.domain.Orderline;
import main.java.be.ipeters.ottoz.cpbelcar.mappers.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderService implements CrudService<Order, Integer>{
@Autowired
private OrderMapper orderMapper;
@Autowired
private OrderlineService orderlineService;
private Orderline orderline;
public int prefabOrderId;
@Override
public void save(Order entity) {
/*
* maak een voorlopig order hou de id bij
*
*/
orderMapper.insert(entity);
//postman, zet input van order met orderlien klaar
}
public void save2(Order entity) {
/*
* maak een voorlopig order hou de id bij
* maak orderlijnen en vul hier bovenstaande id in als orderId
* Op het einde een update doen van het order
*
*/
// create prefab order
prefabOrderId=prefabOrderCreation().getId();
// oproep create orderline
orderlineService.save(orderline);
// oproep validate
orderMapper.insert(entity);
//postman, zet input van order met orderlien klaar
}
@Override
public Order findById(Integer key) {
return orderMapper.findById(key);
}
@Override
public List<Order> findAll() {
return orderMapper.findAll();
}
@Override
public void deleteById(Integer key) {
orderMapper.deleteById(key);
}
@Override
public void update(Order entity) {
orderMapper.update(entity);
}
private void orderValidation(Order order) {
// check minstens 1 orderline
}
private Order prefabOrderCreation() {
Order prefab = new Order(); //(1, "prefab", 1, LocalDate.now(), LocalDate.now(),
//1, 2, 3, "dummy", 5.0);
prefab.setTypeOrder("prefab");
prefab.setOrderDate(LocalDateTime.now());
prefab.setDeliveryDate(LocalDate.now());
prefab.setCustomerId(1);
prefab.setSupplierId(2);
prefab.setEmployeeId(3);
prefab.setStatus("dummy");
prefab.setPercentage(0);
return prefab;
}
}
| cpjjpeters/BelcarFX | src/main/java/be/ipeters/ottoz/cpbelcar/services/OrderService.java | 748 | //postman, zet input van order met orderlien klaar | line_comment | nl | package main.java.be.ipeters.ottoz.cpbelcar.services;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import main.java.be.ipeters.ottoz.cpbelcar.domain.Order;
import main.java.be.ipeters.ottoz.cpbelcar.domain.Orderline;
import main.java.be.ipeters.ottoz.cpbelcar.mappers.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderService implements CrudService<Order, Integer>{
@Autowired
private OrderMapper orderMapper;
@Autowired
private OrderlineService orderlineService;
private Orderline orderline;
public int prefabOrderId;
@Override
public void save(Order entity) {
/*
* maak een voorlopig order hou de id bij
*
*/
orderMapper.insert(entity);
//postman, zet<SUF>
}
public void save2(Order entity) {
/*
* maak een voorlopig order hou de id bij
* maak orderlijnen en vul hier bovenstaande id in als orderId
* Op het einde een update doen van het order
*
*/
// create prefab order
prefabOrderId=prefabOrderCreation().getId();
// oproep create orderline
orderlineService.save(orderline);
// oproep validate
orderMapper.insert(entity);
//postman, zet input van order met orderlien klaar
}
@Override
public Order findById(Integer key) {
return orderMapper.findById(key);
}
@Override
public List<Order> findAll() {
return orderMapper.findAll();
}
@Override
public void deleteById(Integer key) {
orderMapper.deleteById(key);
}
@Override
public void update(Order entity) {
orderMapper.update(entity);
}
private void orderValidation(Order order) {
// check minstens 1 orderline
}
private Order prefabOrderCreation() {
Order prefab = new Order(); //(1, "prefab", 1, LocalDate.now(), LocalDate.now(),
//1, 2, 3, "dummy", 5.0);
prefab.setTypeOrder("prefab");
prefab.setOrderDate(LocalDateTime.now());
prefab.setDeliveryDate(LocalDate.now());
prefab.setCustomerId(1);
prefab.setSupplierId(2);
prefab.setEmployeeId(3);
prefab.setStatus("dummy");
prefab.setPercentage(0);
return prefab;
}
}
| false | 562 | 14 | 692 | 15 | 670 | 12 | 692 | 15 | 804 | 16 | false | false | false | false | false | true |